Control Flow
Conditionals: if / elif / else
Section titled “Conditionals: if / elif / else”Python conditionals use indentation instead of braces. Any expression that evaluates to a truthy or falsy value can be used as the condition.
score = 85
if score >= 90: grade = "A"elif score >= 80: grade = "B"elif score >= 70: grade = "C"else: grade = "F"
print(grade) # BThere is no switch statement in Python — use if/elif chains or, since Python 3.10, structural pattern matching (match/case).
for loops over iterables
Section titled “for loops over iterables”Python’s for loop iterates over any iterable — a list, string, range, file, dictionary, or custom object that implements __iter__.
fruits = ["apple", "banana", "cherry"]for fruit in fruits: print(fruit)
# Iterate over characters in a stringfor ch in "hello": print(ch)Use enumerate() when you need both the index and the value:
for i, fruit in enumerate(fruits, start=1): print(f"{i}. {fruit}")range()
Section titled “range()”range(stop), range(start, stop), and range(start, stop, step) generate integer sequences without building a list in memory.
for i in range(5): # 0, 1, 2, 3, 4 print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8 print(i)while loops
Section titled “while loops”while repeats as long as its condition is truthy.
count = 0while count < 3: print(count) count += 1break, continue, and loop else
Section titled “break, continue, and loop else”breakexits the innermost loop immediately.continueskips the rest of the current iteration and moves to the next.- The
elseclause on a loop runs only if the loop completed without hitting abreak.
for n in [1, 3, 5, 7]: if n % 2 == 0: print("found even") breakelse: print("no even number found") # this runsThe walrus operator :=
Section titled “The walrus operator :=”Introduced in Python 3.8, := assigns a value and evaluates to that value in the same expression.
It is most useful in while and if conditions to avoid repeating an expression.
data = [4, 7, 2, 9, 1]if (largest := max(data)) > 5: print(f"Largest value {largest} exceeds 5")Full runnable demo
Section titled “Full runnable demo”score = 85if score >= 90: grade = "A"elif score >= 80: grade = "B"elif score >= 70: grade = "C"else: grade = "F"print(f"Score {score} -> Grade {grade}")
total = 0for i in range(1, 6): total += iprint(f"Sum 1..5 = {total}")
numbers = [1, 3, 5, 7]for n in numbers: if n % 2 == 0: print(f"Found even: {n}") breakelse: print("No even numbers found")
count = 0while True: count += 1 if count % 2 == 0: continue if count > 7: break print(f"odd: {count}")
data = [4, 7, 2, 9, 1]if (largest := max(data)) > 5: print(f"Largest value {largest} exceeds 5")Loading Python runtime (first run only)…