Python Loops & Conditions · Control Your Program's Flow

Mingming Li — Click any blue heading below to expand the content.

Table of Contents

1. Conditional statements (if, elif, else)

Conditionals allow your program to make decisions based on whether a condition is True or False.

Think of conditionals like asking a question: "Is it raining?" If yes, take an umbrella. If no, go outside.
# Basic if statement
age = 18
if age >= 18:
    print("You are an adult")

# if-else statement
score = 75
if score >= 60:
    print("You passed!")
else:
    print("You failed.")

# if-elif-else (multiple conditions)
grade = 85
if grade >= 90:
    print("A")
elif grade >= 80:
    print("B")
elif grade >= 70:
    print("C")
elif grade >= 60:
    print("D")
else:
    print("F")

# Comparison operators
# ==  equal to
# !=  not equal to
# >   greater than
# <   less than
# >=  greater than or equal to
# <=  less than or equal to

# Logical operators
# and - both conditions must be True
# or  - at least one condition must be True
# not - reverses the condition

age = 20
has_license = True
if age >= 18 and has_license:
    print("You can drive")

if age < 12 or age > 65:
    print("You get a discount")

# Nested conditions (if inside if)
num = 10
if num > 0:
    if num % 2 == 0:
        print("Positive even number")
    else:
        print("Positive odd number")
Important: Python uses indentation (spaces or tabs) to define blocks of code. All code inside an if statement MUST be indented!

2. For loop

A for loop is used to iterate over a sequence (list, tuple, string, range, etc.). Use it when you know how many times to repeat.

# Looping through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Looping through a string
for char in "Python":
    print(char)

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

for i in range(2, 8):   # 2, 3, 4, 5, 6, 7
    print(i)

for i in range(1, 10, 2):  # 1, 3, 5, 7, 9 (step = 2)
    print(i)

# Looping through dictionary
student = {"name": "Alice", "age": 25, "grade": "A"}
for key in student:
    print(f"{key}: {student[key]}")

for key, value in student.items():
    print(f"{key}: {value}")

# Using enumerate() to get index and value
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
    print(f"{index}: {color}")

# Using zip() to loop through multiple lists together
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
    print(f"{name} scored {score}")

3. While loop

A while loop repeats as long as a condition is True. Use it when you DON'T know how many times to repeat.

Warning: Be careful with infinite loops! Always make sure your condition will eventually become False.
# Basic while loop
count = 0
while count < 5:
    print(count)
    count += 1

# While loop with user input
user_input = ""
while user_input != "quit":
    user_input = input("Enter 'quit' to exit: ")
    print(f"You entered: {user_input}")

# While loop with break (exit loop early)
num = 0
while True:
    if num >= 10:
        break
    print(num)
    num += 1

# While loop with continue (skip current iteration)
num = 0
while num < 10:
    num += 1
    if num % 2 == 0:
        continue    # skip even numbers
    print(num)      # prints only odd numbers

# While loop with else (runs after loop ends normally, not if break)
num = 0
while num < 3:
    print(num)
    num += 1
else:
    print("Loop completed without break")
Pro tip: Use break to exit a loop early. Use continue to skip to the next iteration.

4. For vs While - When to use which?

Use for loop when... Use while loop when...
You know how many times to iterate You don't know how many times
Iterating over a sequence (list, string, range) Waiting for a condition to change (user input, game loop)
Processing each item in a collection Running until a specific event occurs
# For loop example - known number of iterations
for i in range(10):
    print(i)

# While loop example - unknown number of iterations (game loop!)
game_active = True
while game_active:
    # game keeps running until player loses
    if player_hits_cactus:
        game_active = False

5. Nested loops

Nested loops are loops inside other loops. The inner loop completes all its iterations for each iteration of the outer loop.

# Nested for loops
for i in range(3):
    for j in range(3):
        print(f"({i}, {j})", end=" ")
    print()   # new line after each outer loop

# Output:
# (0, 0) (0, 1) (0, 2)
# (1, 0) (1, 1) (1, 2)
# (2, 0) (2, 1) (2, 2)

# Multiplication table
for i in range(1, 6):
    for j in range(1, 6):
        print(f"{i * j:4}", end="")
    print()

6. Break, continue, and pass

# break - exits the loop entirely
for i in range(10):
    if i == 5:
        break
    print(i)    # prints 0,1,2,3,4

# continue - skips to the next iteration
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)    # prints 1,3,5,7,9

# pass - does nothing, used as a placeholder
for i in range(5):
    if i == 2:
        pass     # TODO: add code later
    print(i)

# Example: Find first even number (using break)
numbers = [1, 3, 5, 8, 10, 13]
for num in numbers:
    if num % 2 == 0:
        print(f"First even number is {num}")
        break   # stop after finding it
Summary: break = stop the loop entirely. continue = skip this iteration and go to the next. pass = do nothing (placeholder).

7. Quick reference

# CONDITIONALS
if condition:
    # code
elif condition2:
    # code
else:
    # code

# Comparison operators: ==, !=, <, >, <=, >=
# Logical operators: and, or, not

# FOR LOOP
for item in sequence:
    # code

for i in range(stop):
for i in range(start, stop):
for i in range(start, stop, step):

for index, item in enumerate(sequence):
for item1, item2 in zip(seq1, seq2):
for key, value in dict.items():

# WHILE LOOP
while condition:
    # code

# LOOP CONTROL
break   # exit loop completely
continue # skip to next iteration
pass    # do nothing (placeholder)

8. Quick Challenge: Spot the Flow Control

Look at this code from our game (Code-1). Can you find the conditionals and loops?

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
    
    keys = pygame.key.get_pressed()
    if keys[pygame.K_SPACE] and player.bottom >= 400:
        gravity = -20
    
    gravity += 1
    player.y += gravity
    if player.bottom > 400:
        player.bottom = 400

Questions:

  1. What type of loop is while True:? (How does it end?)
  2. What does for event in pygame.event.get(): loop through?
  3. What happens when if event.type == pygame.QUIT is True?
  4. What condition controls the player's jump?
  5. What happens when player.bottom > 400 is True?
Click for answers
  1. It's an infinite loop that only ends when the user closes the window (pygame.QUIT triggers break/exit).
  2. All events that happened since the last frame (key presses, mouse clicks, quit events).
  3. The game exits (pygame.quit() and exit()).
  4. keys[pygame.K_SPACE] and player.bottom >= 400 (space key pressed AND player on ground)
  5. Player is moved back to ground (can't fall through floor).

9. Exercises

Try these exercises to practice loops and conditionals. Write your code in Thonny.

  • Exercise 1: Write an if-elif-else statement that prints a letter grade (A, B, C, D, F) based on a numeric score.
  • Exercise 2: Use a for loop to print numbers 1 to 20. Then modify to print only even numbers.
  • Exercise 3: Use a while loop to count down from 10 to 1.
  • Exercise 4: Ask user for a number and print if it's positive, negative, or zero.
  • Exercise 5: Calculate the sum of all numbers from 1 to 100 using a for loop.
  • Exercise 6: Find and print the largest number in a list of 10 random numbers.
  • Exercise 7: Keep asking for a password until the user enters the correct one (while loop).
  • Exercise 8: Print a multiplication table (1-10) using nested loops.
  • Exercise 9: FizzBuzz: Print 1-50. For multiples of 3 print "Fizz", multiples of 5 print "Buzz", multiples of both print "FizzBuzz".
  • Exercise 10: Count vowels (a, e, i, o, u) in the string "hello world".
  • Exercise 11: Find the first number divisible by 7 between 1 and 100 (use break).
  • Exercise 12: Print each fruit in ["apple","banana","cherry"] with its index using enumerate().
  • Exercise 13: Keep asking for numbers until user enters 0, then print sum (exclude 0).
  • Exercise 14: Print a pattern using nested loops:
    *
    **
    ***
    ****
    *****
  • Exercise 15: Check if a number is prime.
  • Exercise 16: Use continue to print numbers 1-20 except those divisible by 3.

10. Common Errors & Solutions

  • IndentationError: expected an indented block
    -> You forgot to indent code inside if, for, or while statements. Python needs 4 spaces!
  • Infinite loop (program never stops)
    -> Your while condition never becomes False. Add a way to change the condition inside the loop.
  • NameError: name 'variable' is not defined
    -> You used a variable before creating it. Check spelling and order.
  • TypeError: 'int' object is not iterable
    -> You tried to loop over a number. Use range() instead: for i in range(5):
  • Forgetting the colon (:) at the end of if/for/while lines
    -> Every if, elif, else, for, while needs a colon at the end.
Debugging tip: Use print() statements inside loops to see what's happening. Add print(f"i={i}") to track loop variables.

11. Check Your Understanding

  1. What is the difference between if and elif?
  2. What does range(5) produce?
  3. When would you use a while loop instead of a for loop?
  4. What is the difference between break and continue?
  5. What happens if you write while True: without a break?
  6. What is a nested loop?
Click for Answers
  1. if starts the condition check; elif checks additional conditions only if previous conditions were False.
  2. range(5) produces numbers 0, 1, 2, 3, 4 (5 numbers, starting at 0).
  3. Use a while loop when you don't know how many iterations you need (e.g., waiting for user input).
  4. break exits the entire loop; continue skips the current iteration and goes to the next.
  5. It creates an infinite loop that never stops (program freezes).
  6. A loop inside another loop. The inner loop runs completely for each outer loop iteration.

12. Your Progress Tracker

Check off each item as you master it:
I understand if, elif, and else statements
I know the comparison operators (==, !=, <, >, <=, >=)
I understand logical operators (and, or, not)
I can use for loops with range(), lists, and strings
I can use while loops and avoid infinite loops
I understand when to use for vs while
I can use break and continue
I can create nested loops
I completed at least 10 exercises
I can spot loops and conditions in our game code