Loops & Conditions

for, while loops, if/else statements

BEGINNER

Master Loops & Conditions

Control the flow of your programs. Make decisions with if/else and repeat tasks efficiently with for/while loops. The heart of every real application.

Flow Control Fundamentals

By default, Python executes code line by line from top to bottom. Flow control lets you change this behavior to make dynamic, intelligent programs.

Structure Purpose When to Use
if/elif/else Make decisions User input validation
for item in collection Known iterations Process lists, ranges
while condition Unknown iterations Games, user menus
break/continue Control loop flow Early exit, skip items

if/elif/else Statements

Basic Decision Making

age = 20 if age >= 18: print("You can vote!") # Runs if TRUE elif age >= 16: print("You can drive!") # Runs if first FALSE else: print("You're too young!") # Runs if all FALSE

Multiple Conditions

score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F" print(f"Your grade: {grade}")

Logical Operators

has_ticket = True has_id = True age = 21 if has_ticket and has_id and age >= 18: print("Entry granted!") # All must be TRUE if has_ticket or has_id: # Either TRUE print("You have credentials") if not has_id: # Opposite print("Need ID")

for Loops - Known Iterations

Iterate Lists

fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"I like {fruit}s") # Output: # I like apples # I like bananas # I like cherries

range() Function

# Numbers 0 to 4 for i in range(5): print(i) # Numbers 1 to 5 for i in range(1, 6): print(i) # Step by 2 for i in range(0, 10, 2): print(i) # 0, 2, 4, 6, 8

enumerate() - Index + Value

students = ["Alice", "Bob", "Charlie"] for index, name in enumerate(students): print(f"{index + 1}: {name}") # 1: Alice # 2: Bob # 3: Charlie

while Loops - Unknown Iterations

Counting Loop

count = 0 while count < 5: print(f"Count: {count}") count += 1 # Don't forget this! # Output: 0, 1, 2, 3, 4

Guessing Game

secret = 7 guess = 0 while guess != secret: guess = int(input("Guess the number (1-10): ")) if guess < secret: print("Too low!") elif guess > secret: print("Too high!") else: print("🎉 Correct!")

break, continue, pass

break - Exit Early

for i in range(10): if i == 5: break # Exit loop completely print(i) # Output: 0, 1, 2, 3, 4

continue - Skip Iteration

for i in range(5): if i == 2: continue # Skip this iteration print(i) # Output: 0, 1, 3, 4 (skips 2)

pass - Placeholder

for fruit in fruits: if fruit == "banana": pass # TODO: Special handling print(fruit)

Nested Loops

Multiplication Table

for i in range(1, 6): # Outer loop for j in range(1, 6): # Inner loop print(f"{i} × {j} = {i*j}") print("---") # Separator

Pattern Printing

for row in range(5): spaces = " " * (4 - row) stars = "*" * (2 * row + 1) print(spaces + stars) # * # *** # ***** # ******* #*********

Practice Challenges

1. FizzBuzz Classic

Print numbers 1-100. For multiples of 3 print "Fizz", 5 print "Buzz", both print "FizzBuzz"

2. Number Guessing Game

Generate random number 1-100. Let user guess with hints until correct. Count attempts.

3. Shopping List Manager

While loop menu: add item, remove item, show list, quit. Use list + input validation.

4. Grade Calculator

Input multiple test scores until -1. Calculate average, letter grade, pass/fail.

Infinite Loop Danger!

# ❌ DANGER - Infinite Loop! count = 0 while count < 5: print(count) # count += 1 # FORGOT THIS!

Always increment counters or update conditions!

You Can Now Build Real Apps!

🎮 Projects Unlocked:

Number Guessing Game
while + random
Grade Calculator
if/else chains
Todo List
nested loops + menus
Pattern Printer
nested loops mastery
Quiz App
score tracking + conditions

Next: Functions → Data Structures → Complete Projects