Mingming Li — Click any blue heading below to expand the content.
Conditionals allow your program to make decisions based on whether a condition is True or False.
# 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")
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}")
A while loop repeats as long as a condition is True. Use it when you DON'T know how many times to repeat.
# 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")
break to exit a loop early. Use continue to skip to the next iteration.
| 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
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()
# 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
break = stop the loop entirely. continue = skip this iteration and go to the next. pass = do nothing (placeholder).
# 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)
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:
while True:? (How does it end?)for event in pygame.event.get(): loop through?if event.type == pygame.QUIT is True?player.bottom > 400 is True?keys[pygame.K_SPACE] and player.bottom >= 400 (space key pressed AND player on ground)Try these exercises to practice loops and conditionals. Write your code in Thonny.
range() instead: for i in range(5):print() statements inside loops to see what's happening. Add print(f"i={i}") to track loop variables.
if and elif?range(5) produce?break and continue?while True: without a break?if starts the condition check; elif checks additional conditions only if previous conditions were False.range(5) produces numbers 0, 1, 2, 3, 4 (5 numbers, starting at 0).break exits the entire loop; continue skips the current iteration and goes to the next.