Python If-Else, Loops and Comprehensions
Part 5 of the Python for Everyone track. Last updated: September 2026.
Control flow in Python reads almost like English — but the details (the for-else clause, comprehensions, enumerate/zip) are what separate beginners from fluent writers.
If / elif / else
score = 85
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
else:
grade = "C"
# One-line ternary
status = "pass" if score >= 40 else "fail"
Indentation is the block structure — 4 spaces per level, no braces, no exceptions.
For loops
for fruit in ["apple", "banana", "cherry"]:
print(fruit)
# Need the index too? Use enumerate — never range(len(...))
for i, fruit in enumerate(["apple", "banana"]):
print(i, fruit) # 0 apple / 1 banana
# Loop two lists together
names = ["Ada", "Grace"]
ages = [36, 85]
for name, age in zip(names, ages):
print(f"{name} is {age}")
# range() for counted loops
for i in range(3): # 0, 1, 2
print(i)
for i in range(2, 10, 3): # start, stop, step → 2, 5, 8
print(i)
While loops
count = 0
while count < 3:
print(count)
count += 1
break, continue, and the for-else surprise
for n in range(10):
if n == 3:
continue # skip this iteration
if n == 7:
break # exit the loop entirely
print(n)
# else runs only if the loop finished WITHOUT break
for n in [2, 4, 6]:
if n % 2 == 1:
print("found odd")
break
else:
print("all even") # ← this prints
The for-else pattern is the idiomatic "search with not-found handling" — common in interviews.
Comprehensions: build collections in one line
squares = [x**2 for x in range(6)] # [0, 1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
# Dict and set comprehensions exist too
square_map = {x: x**2 for x in range(4)} # {0: 0, 1: 1, 2: 4, 3: 9}
unique_lens = {len(w) for w in ["hi", "hello", "hey"]} # {2, 5, 3}
Comprehensions are faster than equivalent append loops and are expected style in Python code reviews.
Key takeaways
- Indentation defines blocks — 4 spaces, consistently.
- enumerate() for index+value; zip() for parallel loops; never range(len(x)).
- for-else: else runs when no break occurred.
- Comprehensions replace most simple build-a-list loops.
Next in this series: Python Functions: Arguments, *args, **kwargs and Lambdas.
Comments
Post a Comment