Control flow decides what code runs and how many times. In this lesson, you’ll learn conditions (if/elif/else), loops (for, while), and loop controls (break, continue, pass) with clear examples.
1) Conditions: if, elif, else
Use conditions to run code only when a test is True.
age = 17
if age >= 18:
print("You can vote.")
elif age >= 16:
print("You can apply for a learner's driving permit.")
else:
print("Focus on school and fun!")
How Python treats values in conditions
In if statements, some values are treated as False: 0, 0.0, empty strings "", empty containers like [], {}, set(), and None. Most other values are treated as True. This makes simple checks easy.
items = []
if items: # empty list is treated as False
print("Has items")
else:
print("No items")
Combining Conditions
temp = 28
is_raining = False
if temp > 25 and not is_raining:
print("Go for a walk!")
Inline Conditional (Ternary)
A compact way to write if/else in one line:
age = 18
label = "adult" if age >= 18 else "minor"
print(label) # adult
Equivalent expanded form:
if age >= 18:
label = "adult"
else:
label = "minor"
2) for Loops
for loops iterate over a sequence (list, string, range, etc.).
# Iterate over a list
fruits = ["apple", "banana", "mango"]
for f in fruits:
print(f)
# Iterate with index
for i, f in enumerate(fruits, start=1):
print(i, f)
# Iterate a fixed number of times
for n in range(3):
print("Hello", n) # 0, 1, 2
Note: range is exclusive of the stop value. You can also specify a step:
# start, stop, step (ascending)
for n in range(0, 6, 2):
print(n) # 0, 2, 4
# start, stop, step (descending)
for n in range(10, 0, -2):
print(n) # 10, 8, 6, 4, 2
for ... else (loop-else)
The else runs only if the loop did not break.
# Find the first even number; otherwise print "none found"
nums = [3, 5, 7]
for n in nums:
if n % 2 == 0:
print("First even:", n)
break
else:
print("No even numbers")
3) while Loops
Run while a condition remains True. Be careful to avoid infinite loops.
count = 3
while count > 0:
print("Countdown:", count)
count -= 1
print("Blast off!")
A Common Pattern: Input Validation
tries = 0
password = "python123"
while tries < 3:
guess = input("Enter password: ")
if guess == password:
print("Welcome!")
break
tries += 1
else:
print("Too many attempts.")
4) Loop Controls: break, continue, pass
break — stop the loop now
for n in range(1, 10):
if n == 5:
break
print(n)
# prints 1..4 then stops
continue — skip this iteration
for n in range(1, 6):
if n % 2 == 0:
continue # skip even numbers
print(n)
# prints 1, 3, 5
pass — do nothing (placeholder)
for task in ["todo1", "todo2"]:
# TODO: implement later
pass
5) Practical Mini-Examples
a) Sum of numbers 1..100
total = 0
for n in range(1, 101):
total += n
print(total)
b) FizzBuzz (classic)
for n in range(1, 21):
if n % 15 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)
c) Search with loop-else
names = ["Ali", "Ammar", "Sara"]
target = "Zain"
for name in names:
if name == target:
print("Found:", name)
break
else:
print("Not found")
Common Pitfalls & Tips
- Indentation matters: every block under
if,for,whilemust align. - Don’t modify a list while iterating it: iterate over a copy or build a new list.
- Prefer
enumerate()overrange(len(...))— clearer and safer. - Use
breakearly to exit when done: avoids extra work. - Leverage
for ... else: perfect for “search or report not found”.
Key Takeaways
- if / elif / else choose which block runs based on conditions.
- Inline conditional (
x if cond else y) is a compact way to write simple decisions. - for iterates sequences; while repeats while a condition is true.
- break exits a loop, continue skips this iteration, pass is a placeholder.
- for/while ... else runs the
elseonly if the loop didn’tbreak. - Short-circuit logic: use
andas a guard (avoid errors) andorfor defaults (with care). - Prefer
enumerate()overrange(len(...)); don’t modify a list while iterating it.
What’s next? In the next lesson, we’ll learn how to bundle logic into reusable pieces with Functions — definitions, arguments (positional, default, *args, **kwargs), return values, scope, lambdas, and recursion.
Leave a comment
Your email address will not be published. Required fields are marked *
