Python · Lesson 4 of 15
Control Flow
if/elif/else, for loops, while loops, and when to use each.
- Beginner
- 15 min read
- 3 objectives
Before this lessonLesson 3: Working with Strings
What you will learn
- Branch with if/elif/else
- Iterate with for and range()
- Use while with a clear exit
Programs get interesting when they can make decisions and repeat work. Control flow statements do both. Python marks the body of each one with indentation (four spaces by convention) instead of braces, so consistent indentation is part of the syntax.
Think in decisions and repetition
Every program you use is built from just two ideas beyond simple steps. Decisions: "if the password is wrong, show an error; otherwise let the user in." Repetition: "for every item in the cart, add up the price." Control flow is how you express those two ideas in code.
Before writing any code, get used to describing the logic in words. If you can say it as "if this, do that, otherwise do something else", the code is only a translation.
Conditionals
if runs a block when its condition is true. Add elif for extra cases and else for the fallback. Python checks them in order and runs only the first block that matches. Conditions use comparison operators (== != < > <= >=) and the logical words and, or, not.
score = 87
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
print(grade)B
for loops
A for loop walks through any sequence one item at a time. range(n) produces the numbers 0 to n-1; range(start, stop, step) gives you control over both ends and the gap. Use enumerate() when you need the position as well as the value.
for i in range(3):
print("tick", i)
for idx, color in enumerate(["red", "green"], start=1):
print(idx, color)tick 0 tick 1 tick 2 1 red 2 green
while loops
while repeats as long as its condition stays true, which makes it right when you do not know the number of repetitions in advance. Always make sure something inside the loop moves it toward the exit, or you will create an infinite loop. Use break to leave early and continue to skip to the next round.
count = 3
while count > 0:
print(count)
count -= 1
print("liftoff")3 2 1 liftoff
Combining conditions
Join tests with and (both must be true), or (at least one) and not (flip the answer). Python also lets you chain comparisons the way you would in maths: 18 <= age < 65.
age = 30
has_ticket = True
if age >= 18 and has_ticket:
print("Welcome in")
if not has_ticket or age < 18:
print("Sorry, no entry")
print(18 <= age < 65)Welcome in True
Controlling a loop: break, continue and else
break leaves the loop immediately. continue skips the rest of this round and jumps to the next one. Use them to stop as soon as you find what you want, or to ignore items you do not care about.
for n in range(1, 10):
if n == 3:
continue # skip 3
if n == 6:
break # stop completely
print(n)1 2 4 5
Nested loops: a multiplication table
A loop inside another loop runs the inner one completely for each turn of the outer one. Think of a clock: the minute hand does a full circle for every single step of the hour hand.
for row in range(1, 4):
for col in range(1, 4):
print(row * col, end="\t")
print()1 2 3 2 4 6 3 6 9
Worked example: guess the number (logic only)
Here is a complete mini-program that combines a loop, a decision and a counter. Trace it by hand with the values shown, writing down the value of each variable after every line. Tracing on paper is the single best way to understand loops.
secret = 7
guesses = [3, 9, 7, 2]
attempts = 0
for guess in guesses:
attempts += 1
if guess < secret:
print(guess, "is too low")
elif guess > secret:
print(guess, "is too high")
else:
print(guess, "is correct after", attempts, "attempts")
break3 is too low 9 is too high 7 is correct after 3 attempts
Common mistakes
- Using
=(assign) where you meant==(compare). - Forgetting the colon at the end of
if,fororwhilelines. - Mixing tabs and spaces, which causes
IndentationError. - Off-by-one errors:
range(5)stops at 4, not 5.
Key takeaways
if/elif/elsechoose one branch; combine tests withand,or,not.forwalks a known sequence;whilerepeats until a condition changes.breakexits a loop,continueskips to the next round.- Indentation is syntax: it defines what belongs inside each block.
# Write your solution here
