
Quick answer: Python uses if / elif / else to make decisions and for / while to repeat work. Control depends on indentation: every block under a condition or loop is indented four spaces, and moving one character sideways changes what runs. Comparisons (==, !=, <, >, in) produce booleans that drive every branch and loop.
Part 3 of our Python series. Need the prerequisite knowledge? Core data types comes first.
Why indentation is law
In most languages braces {} group statements. Python uses indentation itself — it is not cosmetic, it is the grammar. Two statements at different depths are two different blocks. This design makes Python code readable by enforcement: correct and pretty are the same thing.
temp = 35
if temp > 32:
print("Hot day") # runs only while indented
print("Drink water")De-indenting one line ends the block. totally flat or mixed tabs/spaces raise IndentationError — the error message will tell you the line number, read it literally.
if / elif / else in practice
Conditions run top-down and stop at the first match:
grade = 74
if grade >= 90:
letter = "A"
elif grade >= 75:
letter = "B" # this branch fires for 74? No — 74 < 75
elif grade >= 60:
letter = "C" # 74 lands here
else:
letter = "F"
print(letter) # Cfor loops: repeat over a collection
A for loop walks through items — lists, strings, dicts, or number ranges:
scores = [88, 92, 79]
for s in scores: # s takes 88, then 92, then 79
print("Score:", s)
for ch in "Py": # strings are sequences too
print(ch) # P then y
for n in range(3): # 0, 1, 2 — range is half-open
print(n)
for i, s in enumerate(scores): # value AND position
print(f"{i + 1}. {s}")Looping a dict: .keys() by default, .items() for both halves:
prices = {"rice": 60, "oil": 140}
for item, cost in prices.items():
print(f"{item} costs {cost}")while loops: repeat until something becomes false
for = known collection; while = unknown count, defined condition:
attempts = 0
password = "open"
while attempts < 3:
guess = input("Password: ")
attempts = attempts + 1 # (attempts += 1 is the shorthand)
if guess == password:
print("Unlocked")
break # exit the loop now
else:
print("Locked out") # runs only if the loop was never brokenThe rare while...else fires when the loop finishes naturally, with break never happening. Security systems and search loops use it constantly.
break, continue, and the two-loop idiom
break— leave the loop entirely.continue— skip to the next item.- Nested loops:
breakonly escapes the innermost one — a classic interview trap.
for n in range(10):
if n % 2 == 0:
continue # skip even numbers
if n > 7:
break # stop once past 7
print(n) # 1, 3, 5, 7Complete executable example
# flow-demo.py — control flow in one runnable script
temps = [21, 29, 35, 33, 19, 30]
hot_days = [] # collect, don't just print
for t in temps:
if t >= 30: # decision
hot_days.append(t) # side effect inside the branch
print(f"{len(hot_days)} hot days: {hot_days}")
total, count = 0, 0 # while with a running total
while count < len(temps):
total += temps[count]
count += 1
average = total / len(temps)
if average >= 30:
verdict = "Heat wave"
elif average >= 25:
verdict = "Warm week"
else:
verdict = "Pleasant week"
print(f"Average {average:.1f} — {verdict}")Line by line: the for loop filters with if and appends into a new list (the most common real-world pattern); the while replicates what sum(temps) does built-in — deliberately, so you see both; :.1f formats the float to one decimal place; the final branch picks a verdict string.
Common mistakes and edge cases
- Comparing with
=instead of==—if x = 5:is aSyntaxError;=assigns,==compares. - Forgetting the colon — every
if,elif,else,for,whileheader ends with:. - Off-by-one in range —
range(1, 5)yields 1, 2, 3, 4 — never 5. Half-open, always. - Mutating a list while looping over it — appending inside
for t in tempsgrows the loop forever in pathological cases; loop over a copy (for t in temps[:]) if you must edit the original. - Infinite
whileloops — everywhileneeds a line that moves the condition toward False. If your terminal hangs, Ctrl+C kills the script.
Key takeaways and challenge
- Indentation defines blocks; four spaces, no mixing.
if/elif/elsepicks one path;foriterates,whilerepeats on condition.breakexits,continueskips; dict loops use.items().
Challenge: write fizzbuzz.py that loops 1–15 and prints Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for both (test that case first: n % 3 == 0 and n % 5 == 0), otherwise the number. This is the single most famous screening exercise on Earth — it will be asked in interviews.
Want one-to-one help getting ramped in Python? Ampersand Academy offers hands-on training.
How does Python handle if-else without braces?
Indentation replaces braces. Every statement in the branch is indented (four spaces by convention), and the first line at the original indent level ends the block.
What is the difference between for and while loops?
A for loop iterates over a known collection or range. A while loop repeats until its condition becomes false, when you cannot know the iteration count in advance.
When does the while-else clause run?
The else block of a while loop runs only if the loop finished normally without hitting break. It is used for searches: else means nothing was found.
Is range(1, 5) inclusive?
No. range is half-open: it yields 1, 2, 3, 4 and never includes the stop value. Always assume the stop number is excluded.
Can I modify a list while looping over it?
It is possible but risky: the loop index shifts and items get skipped or duplicated. Iterate over a copy (for x in items[:]) if the loop must edit the original.
Last updated on · Written by Dinesh Kumar R
