Python Conditionals and Loops: if/elif/else, for, while, break and continue
How Python chooses which line runs next: an if/elif chain for a grade, indentation as structure, for over lists, strings and range, while with a countdown, and break, continue and pass, ending in one score processor that uses them all.
What you will learn
- Write an if/elif/else chain and explain why the first True branch wins
- Use indentation to mark blocks and read an IndentationError
- Loop with for over lists, strings and range, and with while on a condition
- Control a loop with break, continue and pass
Before you start
- Python Operators
- Python Lists, Tuples, Sets and Dicts
Every line written so far runs once, top to bottom, in order. Now your program starts choosing which lines run, and how many times. That's flow control.
Normally Python reads your code like walking down a straight road. Sometimes you reach a fork: if it's raining you take the umbrella, otherwise you don't. That's if. Sometimes there's a stack of plates in the sink and you wash each one until none are left. That's a for loop. Sometimes you don't know the count: you fill a bucket and keep the tap on while it isn't full. That's while. And you can change your mind midway, stopping early or skipping one plate: break and continue.
if, elif and else
score = 85
print("Score:", score)
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
print("Done")
Score: 85
Grade: B
Done
85 isn't at least 90, so Python skips that line. elif, short for else if, is one more check: 85 is at least 80, so it prints Grade B. Here's the important part: 85 is also above 70, but that check never runs. Once one branch is True, Python skips the rest of the chain. That's why the highest score goes first. else has no condition; it's the catch-all that runs only when every check above failed.
Indentation is the structure
temperature = 32
if temperature > 30:
print("It is hot")
print("Drink water")
print("This line always runs")
It is hot
Drink water
This line always runs
The colon opens a block. The two lines pushed in by four spaces are that block and run together. The last print starts at the left edge, so it's outside the block and runs whatever the check says. Leave the indented line flush left and Python refuses to run the file:
File "S01L08_FlowControl\indent_error.py", line 4
print("It is hot")
^^^^^
IndentationError: expected an indented block after 'if' statement on line 3
In Python, spacing isn't decoration. It's the structure of your program.
Truthiness in a condition
cart = []
name = "Asha"
if cart:
print("Cart has items")
else:
print("Cart is empty")
if name:
print("Hello,", name)
Cart is empty
Hello, Asha
A condition doesn't have to be a comparison. An if uses the same rule as bool: empty things are False, everything else True. if cart reads almost like English: "if there's something in the cart". And else is optional.
Separate ifs can each run
age = 70
is_member = True
price = 100.0
print(f"Original price: ${price}")
if age >= 65 or age < 12:
price *= 0.70
print("Age discount applied: 30% off")
if is_member:
price *= 0.90
print("Member discount applied: extra 10% off")
print(f"Final price: ${price:.2f}")
Original price: $100.0
Age discount applied: 30% off
Member discount applied: extra 10% off
Final price: $63.00
With or, 70 being at least 65 is enough, so the price goes from 100 to 70. The next line is a fresh if, not an elif, so Python checks it no matter what happened above, and 70 becomes 63. An elif chain picks one branch; separate ifs can each run.
An if inside an if
age = 20
has_ticket = True
if age >= 18:
print("Age check passed")
if has_ticket:
print("Welcome in")
else:
print("Please buy a ticket")
else:
print("Adults only")
Age check passed
Welcome in
The inner check only runs if the outer one passed. Each else lines up with its own if. Two levels read fine; much deeper gets hard to follow.
The for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("Fruit:", fruit)
print("Loop finished, last fruit was", fruit)
Fruit: apple
Fruit: banana
Fruit: cherry
Loop finished, last fruit was cherry
The first time round, Python puts the first item in fruit and runs the body. Then it goes back up, and fruit is banana, then cherry. With nothing left, the loop ends. Notice fruit is still there afterwards, holding the last value it got. You can call that variable anything; the loop gives it one item each time round.
A string is a sequence of characters, so the same loop works on it: for letter in "Python" gives P, y, t, h, o, n. If you can go through a thing one item at a time, for can loop over it.
Counting with range
for i in range(5):
print("i =", i)
print("Counting by 3:")
for n in range(0, 10, 3):
print(n)
print("Countdown:")
for n in range(5, 0, -1):
print(n)
i = 0
i = 1
i = 2
i = 3
i = 4
Counting by 3:
0
3
6
9
Countdown:
5
4
3
2
1
range(5) gives five numbers starting at 0; 5 itself isn't included. With three numbers it's start, stop, step. The step can be negative, which counts down and stops before 0. The stop number is never included.
The while loop
count = 5
print("Start:", count)
while count > 0:
print("count =", count)
count -= 1
print("Done, count is now", count)
Start: 5
count = 5
count = 4
count = 3
count = 2
count = 1
Done, count is now 0
A for loop knows its items. A while loop only knows a condition, and keeps going while it's True. Each round, count -= 1 takes it down by one, until 0 > 0 is False and the loop ends.
Watch this one. Take away the count -= 1 line and count stays at 5. The condition never turns False and the loop never ends. Something in the body has to move you towards False. Use for when you have items to go through, and while when you're waiting on a condition.
break, continue and pass
names = ["Alice", "Bob", "Charlie", "Diana"]
target = "Charlie"
for name in names:
print("Checking:", name)
if name == target:
print("Found!", target)
break
Checking: Alice
Checking: Bob
Checking: Charlie
Found! Charlie
break leaves the loop right there. Diana is never checked; there's no point looking further once you've found it.
for num in range(1, 11):
if num % 2 == 0:
continue
print("Odd:", num)
Odd: 1
Odd: 3
Odd: 5
Odd: 7
Odd: 9
continue skips only the current round. For an even number the remainder is 0, so continue sends Python straight back to the for line and the print is skipped.
role = "admin"
if role == "admin":
pass
elif role == "editor":
pass
else:
print("Regular user")
print("Program continues normally")
Program continues normally
pass does nothing and jumps nowhere. Why have it? A block can't be empty, or you'd get that same IndentationError. pass holds the place until you've written the logic.
A loop inside a loop
for row in range(1, 4):
for col in range(1, 4):
print(row, "x", col, "=", row * col)
print("row", row, "done")
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
row 1 done
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
row 2 done
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
row 3 done
The inner loop runs all the way through for every round of the outer one, like the minute hand and hour hand on a clock. The "done" print is pushed in only one level, so it belongs to the outer loop.
Everything together
scores = [88, -5, 72, 95, -1, 60]
for score in scores:
if score == -1:
print("Sentinel found, stopping.")
break
if score < 0:
print(f"Skipping invalid: {score}")
continue
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Score {score} -> Grade {grade}")
Score 88 -> Grade B
Skipping invalid: -5
Score 72 -> Grade C
Score 95 -> Grade A
Sentinel found, stopping.
-1 is a stop marker, called a sentinel: nothing more to process. -5 is below zero, so continue skips it with no grade. When -1 arrives, break ends the loop, so 60 never gets graded. One loop, one chain, one break and one continue.
Quick recap
| Tool | Remember |
|---|---|
if / elif / else | first True wins; put the strictest check first |
| indentation | decides which lines belong to what |
for | one item each time round; works on lists and strings |
range(start, stop, step) | stop is never included |
while | runs while True; the body must move it towards False |
break / continue / pass | leave / skip this round / do nothing |
For loops over real data, with enumerate, zip and dictionaries, carry on with Looping over real data.
Try it yourself
Change the scores in the last example and say what will print before you run it. Or prompt an AI tool for a similar loop, and step through every line it gives you.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python for AI: The Five Tools You Actually Need
The small part of Python that carries most AI code: dicts and JSON, typed functions with a dataclass, comprehensions and f-strings, environment variables for keys, and try/except for replies that are not JSON. Three standard-library scripts on four support tickets.
Thinking Like a Python Architect in an AI-First World
Coding is laying bricks; architecting is deciding how the pieces fit. A two-line average function shows why someone still has to understand the code an AI tool writes.
Your First Python Program: print, Comments, sep and end
Five tiny files: print and quotes, top-to-bottom order, # comments, several values with sep and end, and the SyntaxError one missing quote causes. Every output is from a real run.
Set Up PyCharm for Python: Install, First Project and First Run
Install PyCharm, create a Pure Python project, and understand the two words that confuse beginners: the interpreter (the cook) and .venv (the project's own shelf). Then run a file and read the exit code.
