Lesson 4 / 11

Control Flow: if/elif/else and Loops

Making decisions

score = 82
if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
else:
    grade = "C"
print(grade)   # B

Python checks each condition in order, top to bottom, and runs the first block whose condition is True — everything after that is skipped, even if a later condition would also technically be true. Indentation isn’t a style choice in Python — it’s how blocks are defined. Four spaces per level is the standard, and mixing tabs and spaces will cause an error, so configure your editor to insert spaces when you press Tab.

The for loop

for lesson in ["Variables", "Operators", "Loops"]:
    print(f"Studying: {lesson}")

A Python for loop iterates directly over the items of a sequence — a list, a string, a range of numbers — rather than manually managing a counter variable like you might in C or Java. To loop a fixed number of times, use range():

for i in range(5):
    print(i)   # prints 0, 1, 2, 3, 4

Note that range(5) produces five numbers starting at zero, up to (but not including) 5 — this “stops one before the number you gave it” behavior is consistent throughout Python and worth memorizing early.

The while loop

attempts = 0
while attempts < 3:
    print("Trying...")
    attempts += 1

Use while when you don’t know in advance how many times you’ll need to loop — waiting for valid user input, or retrying a network request until it succeeds, are both natural fits for while rather than for.

break and continue

for number in range(10):
    if number == 5:
        break        # exits the loop entirely
    if number % 2 == 0:
        continue     # skips to the next iteration
    print(number)   # prints 1, 3

break exits a loop early; continue skips the rest of the current iteration and jumps to the next one. Both are especially useful once loops start doing real work, like searching through data for a specific match and stopping as soon as it’s found.

A common mistake: the infinite loop

A while loop whose condition never becomes False will run forever, freezing your program. Always double-check that something inside the loop body actually changes the variable your condition depends on — forgetting attempts += 1 in the example above would make it loop endlessly.