Topic 03 / 15

Control Flow — if, while, for

~9 min read  //  Python Series  //  Coding India

if / elif / else

score = 87

if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "F"

print(grade)   # B

Comparisons: ==, !=, <, >, <=, >=. Combine them with the words and, or, not (not symbols):

if age >= 18 and country == "IN":
    print("eligible")

# chained comparisons read like math
if 0 <= marks <= 100:
    print("valid score")

Truthiness

Every value is truthy or falsy. Falsy values: False, None, 0, 0.0, "", [], {}, set(). Everything else is truthy — so idiomatic Python checks emptiness directly:

items = []
if not items:              # pythonic
    print("no items")
# instead of: if len(items) == 0

while Loops

attempts = 0
while attempts < 3:
    attempts += 1
    print(f"attempt {attempts}")

for Loops — Iterate Over Anything

Python’s for walks over collections directly — no index bookkeeping:

for tech in ["django", "react", "fastapi"]:
    print(tech)

for ch in "hello":         # strings are iterable too
    print(ch)

Need numbers? Use range():

range(5)          # 0, 1, 2, 3, 4
range(2, 10)      # 2..9
range(0, 20, 5)   # 0, 5, 10, 15

Need the index and the value? Use enumerate() — never range(len(...)):

for i, tech in enumerate(["django", "react"], start=1):
    print(i, tech)
# 1 django
# 2 react

break, continue & the Loop else

for n in range(2, 100):
    if n % 7 == 0:
        print("first multiple of 7:", n)
        break              # exit the loop entirely
    if n % 2 == 0:
        continue           # skip to the next iteration

A loop’s else block runs only if the loop finished without hitting break — handy for search loops:

for user in users:
    if user.name == "digamber":
        print("found")
        break
else:
    print("not found")

match — Structural Pattern Matching

Python 3.10+ has a switch-like statement that can also destructure:

match command.split():
    case ["go", direction]:
        move(direction)
    case ["quit"]:
        exit_game()
    case _:
        print("unknown command")