By WebNest Studio Engineering Team
Python Tutorial
Python Control Flow: Conditionals and Loops
Control flow statements determine the order in which a program's instructions execute — whether a block runs at all, and how many times it repeats. Python provides conditional branching with if/elif/else, and two looping constructs: for loops (for iterating over a known sequence) and while loops (for repeating while a condition holds).
Because Python has no switch statement in most of its history, if/elif chains carry more weight than in some other languages, and Python's for loop is fundamentally different from a C-style counting loop — it iterates directly over the items of any iterable rather than manually managing an index.
Why it matters
Without conditions and loops a program can only run the same statements once, in order. Deciding what to do and repeating work are what make it useful, and every later topic, from processing a list to handling web requests, is built from if, for and while.
if / elif / else
An if statement evaluates a condition; if it is truthy, its indented block runs. Any number of elif ("else if") branches can follow to check additional conditions in order, and an optional final else branch runs only if none of the previous conditions matched. Only the first matching branch executes — Python does not fall through to later branches the way some other languages' switch statements can.
for Loops and range()
A for loop in Python iterates directly over the elements of an iterable — a string, list, tuple, dictionary, or any other iterable object — assigning each element to the loop variable in turn. To loop a specific number of times or generate a numeric sequence, Python provides the built-in range() function: range(5) produces 0 through 4, range(2, 10) produces 2 through 9, and range(0, 10, 2) produces 0, 2, 4, 6, 8 (start, stop, step).
while Loops and break / continue
A while loop repeats its block as long as its condition remains truthy, and is best suited to situations where the number of iterations is not known in advance. Inside any loop, break immediately exits the loop entirely, while continue skips the rest of the current iteration and moves on to the next one.
The Walrus Operator
Python 3.8 introduced the walrus operator, :=, which assigns a value to a name as part of a larger expression, rather than requiring a separate assignment statement first. It is most often used to avoid computing or calling something twice, for example inside a while loop's condition: while (line := input()) != "quit": assigns and tests line in one step.
Examples
if/elif/else grading logic, plus a for loop using range()
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print("Grade:", grade)
for i in range(0, 10, 2):
if i == 6:
continue
print(i)
Grade: B
0
2
4
8
A while loop with break, and the walrus operator
count = 0
while True:
count += 1
if count > 3:
break
print("count is", count)
numbers = [1, 2, 3, 4, 5]
total = 0
i = 0
while (n := numbers[i]) < 5:
total += n
i += 1
print("total before hitting 5:", total)
count is 1
count is 2
count is 3
total before hitting 5: 10
Common Mistakes
- Forgetting that range(stop) is exclusive of stop — range(5) gives 0 through 4, not 0 through 5.
- Writing an infinite while loop by forgetting to update the loop's condition variable inside the block.
- Confusing break (exits the loop entirely) with continue (skips only the current iteration).
- Overusing the walrus operator in places where a plain assignment on its own line would be clearer.
Exercise
Using one loop over the numbers 1 to 20, work out the sum of the even numbers and count how many numbers are divisible by 3. Print both.
Expected output: 110 then 6
even_sum = 0
divisible_by_three = 0
# TODO: loop over the numbers 1 to 20 and update both variables
print(even_sum)
print(divisible_by_three)
Show hints
range(1, 21)produces 1 to 20; the end value is not included.- A number is even when
number % 2 == 0. Use two separateifstatements, since a number can satisfy both tests.
Show solution
even_sum = 0
divisible_by_three = 0
for number in range(1, 21):
if number % 2 == 0:
even_sum += number
if number % 3 == 0:
divisible_by_three += 1
print(even_sum)
print(divisible_by_three)
Quick quiz
1. Which numbers does range(5) produce?
- A. 1 to 5
- B. 0 to 4
- C. 0 to 5
- D. 1 to 4
Show answer
B. range starts at 0 by default and stops before the end value.
2. In an if / elif / else chain, how many branches can run?
- A. All whose conditions are true
- B. At most one
- C. Exactly two
- D. None
Show answer
B. The first branch whose condition is true runs, and the rest are skipped.
3. What does the walrus operator := do?
- A. Compares two values
- B. Divides and assigns
- C. Declares a constant
- D. Assigns a value to a name as part of an expression
Show answer
D. It allows a value to be stored and tested in the same line, for example in a while condition.
Interview questions
When would you use a while loop instead of a for loop?
Show answer
A for loop is used to go through the items of a collection or a known range. A while loop is used when the number of repetitions is not known in advance and depends on a condition: waiting for valid input, retrying an operation, or reading until there is no more data.
What does range() return?
Show answer
It returns a range object, not a list. The object produces its numbers one at a time when looped over, so range(1_000_000) uses almost no memory. It supports len(), indexing and in, and list(range(5)) converts it to a list when one is needed.
Key Points to Remember
- if/elif/else runs at most one matching branch; there is no automatic fall-through between branches.
- for loops iterate directly over an iterable; range() generates numeric sequences for counting loops.
- while loops repeat based on a condition and are suited to cases where the iteration count is not known ahead of time.
- break exits a loop entirely, continue skips to the next iteration, and := (walrus) assigns within an expression.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering