Control flow: if, for, while
Programs become useful when they make decisions and repeat work. Python gives you three tools for that: if
statements, for loops over sequences, and while loops that run until a condition changes.
Conditions
marks = 72
if marks >= 90:
grade = "A"
elif marks >= 60:
grade = "B"
else:
grade = "C"
print(grade) # B
Branches are tested in order and only the first match runs, so write the strictest test first.
| Operator | Meaning | Example |
|---|---|---|
==, != |
equal, not equal | city == "Pune" |
< <= > >= |
comparison | amount > 50000 |
and, or, not |
combine conditions | paid and not cancelled |
in |
membership | "Delhi" in cities |
is None |
identity with None | discount is None |
Chained comparisons are allowed: if 1000 <= amount <= 5000: reads exactly as it means.
Truthiness
Empty values are false: 0, 0.0, "", [], {}, set() and None. Everything else is true, so if orders: is
the idiomatic way to ask "is the list non-empty?".
for loops
A for loop walks through any sequence.
for fruit in ["apple", "mango", "banana"]:
print(fruit.upper())
for i in range(1, 6): # 1..5 - the stop value is excluded
print(i * i)
for position, city in enumerate(["Surat", "Kochi"], start=1):
print(position, city)
range(start, stop, step) produces numbers lazily, and range(10, 0, -2) counts down.
while loops
Use while when you do not know in advance how many repetitions are needed.
balance = 1000
while balance > 0:
balance -= 300
print("Remaining:", balance)
Something inside the loop must move the condition towards False, otherwise it never ends (Ctrl+C stops a runaway loop).
break, continue and the loop else
stock = {"laddu": 12, "barfi": 0, "peda": 7}
for item, qty in stock.items():
if qty == 0:
continue # skip out-of-stock items
if qty < 10:
print("Reorder:", item)
break # stop at the first low item
else:
print("All items comfortably stocked")
A loop's else block runs only when the loop finished without hitting break — handy for search loops.
Comprehensions
A compact way to build a list or dict from a loop:
squares = [n * n for n in range(10) if n % 2 == 0]
lengths = {w: len(w) for w in ["ai", "python", "data"]}
A worked example
sales = [12000, 4500, 78000, 300, 26000]
large = small = 0
for amount in sales:
if amount >= 10000:
large += 1
else:
small += 1
print(f"{large} large orders, {small} small ones, total Rs. {sum(sales):,}")
Common mistakes
- Using
=(assignment) where==(comparison) belongs inside a condition. - Forgetting the colon, or mis-indenting the block under
if/for. - Modifying a list while looping over it; loop over a copy with
for x in items[:]instead. - Writing
if x == True:whenif x:says the same thing. - An endless
whileloop because the counter is never updated.
Practice
Write a program that loops over twelve monthly sales figures, prints Month n: profit or Month n: loss for each,
counts how many months beat a target of ₹50,000, and stops early with a warning if any month reports a negative
figure. Rewrite the counting part as a single list comprehension.