Up until now, your programs run from top to bottom, line by line, every time. But real programs need to make decisions: "If the password is correct, let them in. Otherwise, show an error."
They also need to repeat actions: "Keep asking for input until they type 'quit'" or "Process every item in this list."
Control flow is what separates a simple calculator from a smart assistant. It's the difference between a dumb script and an intelligent program. Master these concepts and you can build almost anything.
๐ Conditionals
Make decisions based on conditions. Different inputs = different behavior.
- if statements
- else and elif
- Comparison operators
- Logical operators (and, or, not)
๐ Loops
Repeat actions multiple times. Process collections item by item.
- while loops (repeat while true)
- for loops (iterate over items)
- range() function
- break and continue
The Power of Control Flow
With variables + control flow, you can build almost anything. Games, apps, automation scripts, websites - they're all just decisions and loops. The Tic-Tac-Toe game at the end of this chapter uses only concepts from Ch01 and Ch02!
Conditional Statements: Making Decisions
The if statement is the most important control structure. It lets your code take different paths based on conditions. Without conditionals, every run of your program would be identical - boring and useless.
The Anatomy of an If Statement
# ==================== BASIC STRUCTURE ====================
# if condition:
# code to run if condition is True
# The key parts:
# 1. The 'if' keyword
# 2. A condition that evaluates to True or False
# 3. A colon : at the end of the if line
# 4. INDENTED code (4 spaces) that runs when True
age = 18
if age >= 18:
print("You are an adult") # Runs if condition is True
print("You can vote") # Also runs (same indentation)
print("This always runs") # Not indented = not part of if
# ==================== INDENTATION IS CRUCIAL ====================
# Python uses indentation to know what's "inside" the if
# This is different from most other languages!
if True:
print("Inside the if")
print("Still inside")
print("Yep, still inside")
print("Outside - this runs regardless")
# โ ๏ธ WRONG - IndentationError!
# if True:
# print("No indentation = error")
# ==================== WHAT COUNTS AS TRUE/FALSE? ====================
# Booleans:
if True: # Runs
print("This runs")
if False: # Doesn't run
print("This doesn't")
# Comparison results:
if 5 > 3: # True, so runs
print("Math works!")
# Variables containing booleans:
is_sunny = True
if is_sunny:
print("Wear sunglasses")
# ==================== TRUTHY AND FALSY VALUES ====================
# Python considers these "falsy" (treated as False):
if 0: pass # 0 is falsy
if "": pass # Empty string is falsy
if []: pass # Empty list is falsy
if None: pass # None is falsy
if False: pass # Obviously
# Everything else is "truthy":
if 1: print("Truthy!") # Any non-zero number
if -42: print("Truthy!") # Even negative
if "hello": print("Truthy!") # Non-empty string
if [1, 2, 3]: print("Truthy!") # Non-empty list
# This is useful for checking if something exists:
name = input("Enter your name: ")
if name: # If they typed something
print(f"Hello, {name}!")
else:
print("You didn't enter a name!")
If-Else: Two Paths
# ==================== IF-ELSE STRUCTURE ====================
# if condition:
# code for True
# else:
# code for False
age = 15
if age >= 18:
print("You are an adult") # Path 1
else:
print("You are a minor") # Path 2
# EXACTLY ONE of these blocks will run - never both, never neither
# ==================== VISUALIZING THE FLOW ====================
# [age >= 18?]
# / \
# True False
# | |
# "adult" "minor"
# \ /
# \ /
# [continue program]
# ==================== PRACTICAL EXAMPLE ====================
# Password checker
password = input("Enter password: ")
if password == "secret123":
print("="*30)
print(" ACCESS GRANTED")
print("="*30)
print("Welcome to the system.")
print("Loading dashboard...")
else:
print("="*30)
print(" ACCESS DENIED")
print("="*30)
print("Incorrect password.")
print("Please try again.")
# ==================== COMMON PATTERNS ====================
# 1. Checking if input is valid
user_input = input("Enter a number: ")
if user_input.isdigit():
number = int(user_input)
print(f"Your number is {number}")
else:
print("That's not a valid number!")
# 2. Checking boundaries
score = 85
if score >= 50:
print("You passed!")
else:
print("You failed.")
# 3. Either/or situations
coin = "heads" # or "tails"
if coin == "heads":
print("You win!")
else:
print("You lose!")
โ ๏ธ Common Beginner Mistakes
- Forgetting the colon:
if age >= 18 โ โ if age >= 18: โ
- Wrong indentation: Must be exactly 4 spaces (or consistent tabs)
- Using = instead of ==:
if x = 5: โ โ if x == 5: โ
- Comparing strings without quotes:
if name == Alice: โ โ if name == "Alice": โ
Comparison Operators: The Foundation of Conditions
Conditions use comparisons. Every if statement boils down to asking a yes/no question. Comparison operators are how you ask those questions. They compare two values and return True or False.
The Six Comparison Operators
# ==================== ALL COMPARISON OPERATORS ====================
x = 10
x == 10 # True Equal to (is x exactly 10?)
x != 5 # True Not equal to (is x different from 5?)
x > 5 # True Greater than (is x more than 5?)
x < 5 # False Less than (is x less than 5?)
x >= 10 # True Greater than OR equal to (is x at least 10?)
x <= 10 # True Less than OR equal to (is x at most 10?)
# ==================== REMEMBER: == vs = ====================
# = is ASSIGNMENT (storing a value)
x = 5 # Put 5 into x
# == is COMPARISON (asking a question)
x == 5 # Is x equal to 5? Returns True
# This is THE most common mistake:
# if x = 5: # โ SyntaxError! You're assigning, not comparing
# if x == 5: # โ Correct comparison
# ==================== USING IN CONDITIONS ====================
age = 25
if age >= 18:
print("Adult")
if age != 0:
print("Age is set")
if age == 25:
print("Exactly 25")
# ==================== CHAINING COMPARISONS ====================
# Python lets you chain comparisons (unique feature!)
score = 75
# Instead of:
if score >= 70 and score < 80:
print("C grade")
# You can write:
if 70 <= score < 80:
print("C grade")
# This reads more naturally: "Is 70 less-than-or-equal score less-than 80?"
# More examples:
x = 5
1 < x < 10 # True (x is between 1 and 10)
1 < x < 3 # False (x is not between 1 and 3)
10 >= x >= 1 # True (x is between 1 and 10, inclusive)
# You can chain as many as you want:
a, b, c, d = 1, 2, 3, 4
a < b < c < d # True (they're in ascending order)
Comparing Different Types
# ==================== COMPARING STRINGS ====================
name = "Alice"
name == "Alice" # True (exact match)
name == "alice" # False (CASE SENSITIVE!)
name == "ALICE" # False (case matters)
name.lower() == "alice" # True (convert to lowercase first)
# String comparisons are lexicographic (dictionary order):
"apple" < "banana" # True (a comes before b)
"apple" < "apricot" # True (compare character by character)
"Apple" < "apple" # True (uppercase letters come before lowercase!)
# Why? It uses ASCII/Unicode values:
# 'A' = 65, 'Z' = 90
# 'a' = 97, 'z' = 122
# So all uppercase < all lowercase
"10" < "9" # True! (string comparison, not numeric)
# "1" comes before "9" in first character
# ==================== COMPARING NUMBERS ====================
5 == 5.0 # True (int and float can be equal)
10 > 3 # True
-5 < 0 # True
3.14159 >= 3.14 # True
# Be careful with floats!
0.1 + 0.2 == 0.3 # False! (floating point precision)
# 0.1 + 0.2 is actually 0.30000000000000004
# For floats, use approximate comparison:
import math
math.isclose(0.1 + 0.2, 0.3) # True
# ==================== TYPES THAT CAN'T BE COMPARED ====================
# Comparing incompatible types causes TypeError:
# 5 < "5" # โ TypeError: '<' not supported between int and str
# [1, 2] < "hello" # โ TypeError
# == works on different types but returns False:
5 == "5" # False (different types = not equal)
True == 1 # True (special case: True is 1, False is 0)
False == 0 # True
Checking Types and Existence
# ==================== CHECKING IF VALUE EXISTS ====================
# Check if variable has a "real" value (not empty/zero):
name = "Alice"
if name: # True because non-empty string
print("Name exists")
count = 0
if count: # False because 0 is falsy
print("Count exists") # This won't print!
# Better for numbers:
if count is not None: # Check if it's actually set
print(f"Count is {count}")
# ==================== CHECKING DATA TYPES ====================
value = "42"
# Using type():
if type(value) == str:
print("It's a string")
if type(value) == int:
print("It's an integer") # Won't print
# Better way - isinstance():
if isinstance(value, str):
print("It's a string")
if isinstance(value, (int, float)): # Check multiple types
print("It's a number")
# ==================== MEMBERSHIP TESTING ====================
# 'in' operator checks if something is inside something else:
"a" in "apple" # True
"x" in "apple" # False
3 in [1, 2, 3, 4, 5] # True
"key" in {"key": "val"} # True (checks keys in dictionaries)
# Use with if statements:
letter = "e"
vowels = "aeiou"
if letter in vowels:
print(f"{letter} is a vowel")
else:
print(f"{letter} is a consonant")
๐ก Comparison Best Practices
- Always use
== for comparison, never =
- For None, use
is None instead of == None
- For string comparison, decide if case matters and use
.lower() if needed
- Avoid comparing floats with
==; use math.isclose()
- Use chained comparisons for ranges:
0 <= x < 100
Logical Operators: Combining Conditions
Sometimes you need to check multiple conditions at once. Logical operators let you combine conditions into more complex expressions. This is how you build sophisticated decision-making into your programs.
The Three Logical Operators
AND - Both Must Be True
Returns True only if ALL conditions are True. If any is False, the result is False.
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive")
# age >= 18? True โ
# has_license? True โ
# Both True โ Result: True
OR - At Least One True
Returns True if ANY condition is True. Only False if ALL are False.
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("No work today!")
# is_weekend? True โ
# is_holiday? False โ
# At least one True โ Result: True
NOT - Reverses the Value
Flips True to False and False to True. Inverts any condition.
is_raining = False
if not is_raining:
print("Go outside!")
# is_raining? False
# not False โ True
# Condition is True โ Code runs
Truth Tables - How They Work
# ==================== AND TRUTH TABLE ====================
# Both must be True to get True
True and True # True โ + โ = โ
True and False # False โ + โ = โ
False and True # False โ + โ = โ
False and False # False โ + โ = โ
# Think of it as: "Do I have EVERYTHING I need?"
# ==================== OR TRUTH TABLE ====================
# Only need one True to get True
True or True # True (both work)
True or False # True (first works)
False or True # True (second works)
False or False # False (neither works)
# Think of it as: "Do I have AT LEAST ONE thing I need?"
# ==================== NOT TRUTH TABLE ====================
# Simply flips the value
not True # False
not False # True
# Think of it as: "The opposite"
# ==================== COMBINING THEM ====================
# You can chain multiple logical operators:
a = True
b = False
c = True
a and b and c # False (b is False)
a or b or c # True (a is True)
a and (b or c) # True (b or c is True, a is True)
not (a and b) # True (a and b is False, not makes it True)
Order of Operations (Precedence)
# ==================== OPERATOR PRECEDENCE ====================
# Order (highest to lowest):
# 1. Parentheses ()
# 2. Comparison operators (==, !=, <, >, <=, >=)
# 3. not
# 4. and
# 5. or
# This means:
a = True
b = False
c = True
# This:
a or b and c
# Is evaluated as:
a or (b and c) # 'and' happens first!
# = True or (False and True)
# = True or False
# = True
# NOT as:
(a or b) and c # This would also be True, but for different reasons
# ==================== USE PARENTHESES FOR CLARITY ====================
# Even if you know the precedence, parentheses make code clearer:
age = 25
has_id = True
is_vip = False
# Hard to read:
if age >= 21 and has_id or is_vip:
print("Enter")
# Much clearer:
if (age >= 21 and has_id) or is_vip:
print("Enter")
# Or even better, use intermediate variables:
meets_requirements = age >= 21 and has_id
if meets_requirements or is_vip:
print("Enter")
Short-Circuit Evaluation
# ==================== WHAT IS SHORT-CIRCUITING? ====================
# Python is "lazy" - it stops evaluating as soon as the result is known
# With AND:
# If the first condition is False, the whole thing is False
# So Python doesn't even look at the second condition!
False and (1/0) # Returns False (doesn't crash!)
# 1/0 would cause ZeroDivisionError, but Python never evaluates it
# With OR:
# If the first condition is True, the whole thing is True
# So Python doesn't look at the second condition!
True or (1/0) # Returns True (doesn't crash!)
# ==================== PRACTICAL USES ====================
# 1. Safe checking (avoid errors):
name = "" # Empty string
# This would crash if name is empty:
# if name[0] == "A":
# This is safe:
if name and name[0] == "A":
print("Name starts with A")
# If name is empty (falsy), Python short-circuits and never tries name[0]
# 2. Default values:
user_input = ""
username = user_input or "Guest" # "Guest" (because user_input is falsy)
user_input = "Alice"
username = user_input or "Guest" # "Alice"
# 3. Safe division:
denominator = 0
if denominator != 0 and (100 / denominator) > 10:
print("Big result")
# Won't crash because first condition is False โ short-circuits
Practical Examples
# ==================== LOGIN SYSTEM ====================
username = input("Username: ")
password = input("Password: ")
# Check both username AND password
if username == "admin" and password == "secret123":
print("โ Login successful!")
print("Welcome, admin.")
elif username == "admin" and password != "secret123":
print("โ Wrong password!")
elif username != "admin":
print("โ User not found!")
# ==================== AGE VERIFICATION ====================
age = int(input("Enter age: "))
has_permission = input("Parental permission? (yes/no): ").lower() == "yes"
# Adult OR has permission
if age >= 18 or has_permission:
print("โ Access granted")
else:
print("โ Access denied")
# ==================== COMPLEX CONDITIONS ====================
score = 85
attendance = 0.92 # 92%
has_extra_credit = True
# Passing requires:
# - Score >= 60 AND attendance >= 80%
# OR
# - Has extra credit
if (score >= 60 and attendance >= 0.80) or has_extra_credit:
print("You passed the course!")
else:
print("You did not pass.")
# ==================== FILTERING DATA ====================
products = ["laptop", "phone", "tablet", "watch"]
cart = []
for product in products:
# Add if it's a phone OR tablet, but NOT if already in cart
if (product == "phone" or product == "tablet") and product not in cart:
cart.append(product)
print(f"Added {product} to cart")
โ ๏ธ Common Logical Operator Mistakes
- Using 'and' when you mean 'or': "age is 18 or 21" should be
age == 18 or age == 21
- Forgetting to repeat the variable:
if age == 18 or 21 โ โ if age == 18 or age == 21 โ
- Double negatives:
if not (not is_valid) โ just use if is_valid
- Overcomplicating:
if condition == True โ just use if condition
Multiple Conditions with elif
What if you have more than two possible paths? Use elif (else if) to check multiple conditions in sequence. This is how you handle situations with many possible outcomes.
The elif Structure
# ==================== BASIC STRUCTURE ====================
# if condition1:
# code for condition1
# elif condition2:
# code for condition2
# elif condition3:
# code for condition3
# else:
# code if nothing matched
# ==================== GRADING SYSTEM EXAMPLE ====================
score = int(input("Enter score (0-100): "))
if score >= 90:
grade = "A"
comment = "Excellent!"
elif score >= 80:
grade = "B"
comment = "Good job!"
elif score >= 70:
grade = "C"
comment = "Satisfactory"
elif score >= 60:
grade = "D"
comment = "Needs improvement"
else:
grade = "F"
comment = "Failed - see me after class"
print(f"Score: {score}")
print(f"Grade: {grade}")
print(f"Comment: {comment}")
# ==================== HOW IT WORKS ====================
# For score = 85:
# 1. Is 85 >= 90? No โ skip
# 2. Is 85 >= 80? Yes! โ grade = "B", stop checking
# 3. Never reaches score >= 70, 60, or else
# Only ONE block ever runs!
# ==================== THE FLOW ====================
# [score >= 90?]
# |
# No โ Yes โ "A"
# [score >= 80?]
# |
# No โ Yes โ "B"
# [score >= 70?]
# |
# No โ Yes โ "C"
# [score >= 60?]
# |
# No โ Yes โ "D"
# โ
# "F"
โ ๏ธ Order Matters Critically!
Python checks conditions from top to bottom and runs the FIRST matching block.
# WRONG ORDER - Everyone gets D!
score = 95
if score >= 60: # 95 >= 60? Yes! Gets D
grade = "D"
elif score >= 70: # Never reached
grade = "C"
elif score >= 80: # Never reached
grade = "B"
elif score >= 90: # Never reached
grade = "A"
# Always order from most restrictive to least!
elif vs Multiple ifs
# ==================== ELIF - MUTUALLY EXCLUSIVE ====================
# Use elif when only ONE condition should match:
age = 25
if age < 13:
category = "child"
elif age < 20:
category = "teenager"
elif age < 65:
category = "adult"
else:
category = "senior"
print(category) # "adult"
# Only ONE category is printed
# ==================== MULTIPLE IFS - INDEPENDENT CHECKS ====================
# Use separate ifs when conditions are independent:
score = 85
achievements = []
if score >= 50:
achievements.append("Passed")
if score >= 70:
achievements.append("Good student")
if score >= 90:
achievements.append("Honor roll")
print(achievements) # ['Passed', 'Good student']
# Multiple can be true!
# ==================== THE KEY DIFFERENCE ====================
# elif: "Check this only if previous conditions were False"
# if: "Check this regardless of previous conditions"
# Wrong use of elif when you want all matches:
score = 95
if score >= 50:
print("Passed")
elif score >= 70: # This won't print!
print("Good student") # Because first condition was True
elif score >= 90: # This won't print either!
print("Honor roll")
# Correct - use separate ifs:
score = 95
if score >= 50:
print("Passed") # Prints
if score >= 70:
print("Good student") # Prints
if score >= 90:
print("Honor roll") # Prints
Real-World Example: Menu System
# ==================== CALCULATOR MENU ====================
print("=" * 40)
print(" ๐งฎ PYTHON CALCULATOR")
print("=" * 40)
print("1. โ Add")
print("2. โ Subtract")
print("3. โ๏ธ Multiply")
print("4. โ Divide")
print("5. ๐ข Modulo (Remainder)")
print("6. โฌ๏ธ Power")
print("=" * 40)
choice = input("Choose operation (1-6): ")
if choice in ["1", "2", "3", "4", "5", "6"]:
a = float(input("First number: "))
b = float(input("Second number: "))
if choice == "1":
result = a + b
operation = "+"
elif choice == "2":
result = a - b
operation = "-"
elif choice == "3":
result = a * b
operation = "ร"
elif choice == "4":
if b != 0:
result = a / b
operation = "รท"
else:
print("โ Error: Cannot divide by zero!")
result = None
operation = None
elif choice == "5":
if b != 0:
result = a % b
operation = "mod"
else:
print("โ Error: Cannot modulo by zero!")
result = None
operation = None
elif choice == "6":
result = a ** b
operation = "^"
if result is not None:
print(f"\n๐ Result: {a} {operation} {b} = {result}")
else:
print("โ Invalid choice! Please enter 1-6.")
Ternary Operator (Conditional Expression)
# ==================== ONE-LINE IF-ELSE ====================
# Sometimes you just need a simple if-else to assign a value
# Python has a shorthand for this:
# value_if_true if condition else value_if_false
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # "adult"
# This is equivalent to:
if age >= 18:
status = "adult"
else:
status = "minor"
# ==================== PRACTICAL EXAMPLES ====================
# Absolute value:
num = -5
absolute = num if num >= 0 else -num
print(absolute) # 5
# Min/max:
a, b = 10, 25
maximum = a if a > b else b
minimum = a if a < b else b
# Pluralization:
count = 1
message = f"{count} item" if count == 1 else f"{count} items"
print(message) # "1 item"
count = 5
message = f"{count} item" if count == 1 else f"{count} items"
print(message) # "5 items"
# Default values:
username = ""
display_name = username if username else "Anonymous"
print(display_name) # "Anonymous"
# ==================== NESTED TERNARY (AVOID!) ====================
# You CAN nest them, but it gets ugly fast:
score = 75
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
# This is hard to read! Use if-elif-else instead for complex conditions.
๐ก When to Use What
- if-else: Two possible paths
- if-elif-else: Multiple mutually exclusive paths
- Multiple ifs: Independent conditions that can all be true
- Ternary: Simple value assignment based on condition
Nested Conditions
You can put if statements inside other if statements. This is called nesting. It's useful when decisions depend on previous decisions, but too much nesting makes code hard to read.
Basic Nested If
# ==================== NESTED IF STRUCTURE ====================
age = int(input("Enter age: "))
has_id = input("Do you have ID? (yes/no): ").lower() == "yes"
if age >= 18:
# Only check ID if they're old enough
if has_id:
print("โ Welcome to the club!")
else:
print("โ Adult but no ID - cannot enter")
else:
print("โ Too young to enter")
# ==================== HOW IT FLOWS ====================
# [age >= 18?]
# / \
# Yes No
# | |
# [has_id?] "Too young"
# / \
# Yes No
# | |
# "Welcome" "No ID"
# ==================== MULTIPLE LEVELS ====================
user_type = "admin"
is_logged_in = True
has_2fa = True
if is_logged_in:
print("You are logged in")
if user_type == "admin":
print("You have admin privileges")
if has_2fa:
print("Full access granted")
else:
print("Please enable 2FA for full access")
else:
print("Standard user access")
else:
print("Please log in first")
When Nesting is Appropriate
# ==================== GOOD USE: DEPENDENT CONDITIONS ====================
# Checking a file before processing it
import os
filename = "data.txt"
if os.path.exists(filename):
print(f"File {filename} exists")
if os.path.isfile(filename):
print("It's a file (not a directory)")
# Now safe to read the file
with open(filename) as f:
content = f.read()
if content:
print(f"File has {len(content)} characters")
else:
print("File is empty")
else:
print("It's a directory, not a file")
else:
print(f"File {filename} does not exist")
# ==================== GOOD USE: VALIDATION CHAIN ====================
# Form validation - each check depends on previous passing
email = input("Email: ")
password = input("Password: ")
confirm = input("Confirm password: ")
if email: # Not empty
if "@" in email and "." in email: # Basic format check
if password: # Not empty
if len(password) >= 8: # Long enough
if password == confirm: # Matches confirmation
print("โ Account created successfully!")
else:
print("โ Passwords don't match")
else:
print("โ Password must be 8+ characters")
else:
print("โ Password is required")
else:
print("โ Invalid email format")
else:
print("โ Email is required")
Flattening Nested Conditions
# ==================== TOO MUCH NESTING (PYRAMID OF DOOM) ====================
# This is hard to read and maintain:
if condition1:
if condition2:
if condition3:
if condition4:
do_something() # Deeply nested!
# ==================== TECHNIQUE 1: USE AND ====================
# Instead of:
if age >= 18:
if has_id:
print("Welcome")
# Use:
if age >= 18 and has_id:
print("Welcome")
# ==================== TECHNIQUE 2: EARLY RETURNS ====================
# Instead of deep nesting, return/exit early on failures:
# (This works best in functions)
def check_access(age, has_id, has_pass):
if age < 18:
return "Too young"
if not has_id:
return "No ID"
if not has_pass:
return "No pass"
return "Welcome!" # Only reached if all checks pass
# ==================== TECHNIQUE 3: GUARD CLAUSES ====================
# Check for invalid cases first, then proceed:
email = "test@example.com"
password = "secretpassword"
# Guard clauses (check failures first):
if not email:
print("Email required")
elif "@" not in email:
print("Invalid email")
elif not password:
print("Password required")
elif len(password) < 8:
print("Password too short")
else:
# All validations passed - proceed with the main logic
print("Creating account...")
# Much flatter than nested ifs!
# ==================== TECHNIQUE 4: INTERMEDIATE VARIABLES ====================
# Break complex conditions into named pieces:
user = {"age": 25, "verified": True, "subscription": "premium"}
# Hard to read:
if user["age"] >= 18 and user["verified"] and user["subscription"] in ["premium", "enterprise"]:
print("Full access")
# Better with variables:
is_adult = user["age"] >= 18
is_verified = user["verified"]
has_premium = user["subscription"] in ["premium", "enterprise"]
if is_adult and is_verified and has_premium:
print("Full access")
๐ก Nesting Best Practices
- Max 3 levels: If you're nesting deeper, refactor
- Use
and: Combine simple conditions instead of nesting
- Guard clauses: Handle error cases first, then proceed
- Extract functions: Move nested logic into separate functions
- Meaningful names: Use intermediate variables for complex conditions
While Loops: Repeat While True
Loops repeat code. A while loop keeps running as long as its condition is True. Use while loops when you don't know how many times you'll need to repeat - you just know when to stop.
The Anatomy of a While Loop
# ==================== BASIC STRUCTURE ====================
# while condition:
# code to repeat
# (something should eventually make condition False!)
# ==================== SIMPLE COUNTING EXAMPLE ====================
count = 1
while count <= 5:
print(count)
count += 1 # CRUCIAL: Update the variable!
print("Done!")
# Output:
# 1
# 2
# 3
# 4
# 5
# Done!
# ==================== STEP BY STEP ====================
# Iteration 1: count=1, 1<=5? Yes โ print 1, count=2
# Iteration 2: count=2, 2<=5? Yes โ print 2, count=3
# Iteration 3: count=3, 3<=5? Yes โ print 3, count=4
# Iteration 4: count=4, 4<=5? Yes โ print 4, count=5
# Iteration 5: count=5, 5<=5? Yes โ print 5, count=6
# Iteration 6: count=6, 6<=5? No โ EXIT LOOP
# Print "Done!"
# ==================== THE THREE PARTS OF A WHILE LOOP ====================
# 1. INITIALIZATION: Set up the variable(s) before the loop
count = 1
# 2. CONDITION: Check if we should continue
while count <= 5:
print(count)
# 3. UPDATE: Change something so the condition eventually becomes False
count += 1
# Missing any of these three causes problems!
โ ๏ธ Infinite Loop Warning!
If the condition never becomes False, the loop runs FOREVER! This freezes your program.
# INFINITE LOOP - DON'T DO THIS:
count = 1
while count <= 5:
print(count)
# Forgot to increment! count stays 1 forever
# Another infinite loop:
while True:
print("Forever...") # Never stops
# To stop an infinite loop: Ctrl+C in terminal
Always make sure something in your loop eventually makes the condition False!
Common While Loop Patterns
# ==================== PATTERN 1: INPUT VALIDATION ====================
# Keep asking until valid input
password = ""
while password != "secret":
password = input("Enter password: ")
if password != "secret":
print("โ Wrong! Try again.")
print("โ Access granted!")
# ==================== PATTERN 2: SENTINEL VALUE ====================
# Keep going until a special "stop" value
print("Enter numbers to add (type 'done' to finish):")
total = 0
while True:
user_input = input("> ")
if user_input.lower() == "done":
break # Exit the loop
total += float(user_input)
print(f"Total: {total}")
# ==================== PATTERN 3: COUNTDOWN ====================
print("Launching in...")
countdown = 5
while countdown > 0:
print(countdown)
countdown -= 1
# In real code: import time; time.sleep(1)
print("๐ LIFTOFF!")
# ==================== PATTERN 4: PROCESSING UNTIL EMPTY ====================
tasks = ["Email", "Meeting", "Code review", "Lunch"]
while tasks: # While list is not empty
current = tasks.pop(0) # Remove and get first item
print(f"Working on: {current}")
print(f" Remaining: {len(tasks)} tasks")
print("All done!")
# ==================== PATTERN 5: RETRY WITH LIMIT ====================
max_attempts = 3
attempts = 0
success = False
while attempts < max_attempts and not success:
password = input(f"Password (attempt {attempts + 1}/{max_attempts}): ")
attempts += 1
if password == "secret":
success = True
print("โ Login successful!")
else:
remaining = max_attempts - attempts
if remaining > 0:
print(f"โ Wrong. {remaining} attempts left.")
if not success:
print("๐ Account locked!")
Practical Examples
# ==================== NUMBER GUESSING GAME ====================
import random
secret = random.randint(1, 100)
guess = 0
attempts = 0
print("=" * 40)
print(" ๐ฏ GUESS THE NUMBER GAME")
print("=" * 40)
print("I'm thinking of a number between 1-100.")
print()
while guess != secret:
guess = int(input("Your guess: "))
attempts += 1
if guess < secret:
print("๐ Too low!")
elif guess > secret:
print("๐ Too high!")
else:
print()
print("๐ CORRECT!")
print(f"You got it in {attempts} attempts!")
# ==================== DICE GAME ====================
import random
money = 100
print("๐ฒ DICE BETTING GAME ๐ฒ")
print(f"Starting money: ${money}")
while money > 0:
print(f"\nBalance: ${money}")
bet = input("Bet amount (or 'quit'): ")
if bet.lower() == 'quit':
break
bet = int(bet)
if bet > money or bet <= 0:
print("Invalid bet!")
continue
player = random.randint(1, 6)
computer = random.randint(1, 6)
print(f"You rolled: {player}")
print(f"Computer rolled: {computer}")
if player > computer:
money += bet
print(f"You win ${bet}!")
elif player < computer:
money -= bet
print(f"You lose ${bet}!")
else:
print("Tie! No change.")
if money <= 0:
print("\n๐ธ You're broke! Game over.")
else:
print(f"\n๐ฐ You're leaving with ${money}!")
While with Else
# ==================== WHILE-ELSE STRUCTURE ====================
# Python has a unique feature: else clause on loops
# The else runs if the loop completes normally (no break)
attempts = 0
max_attempts = 3
while attempts < max_attempts:
password = input("Password: ")
attempts += 1
if password == "secret":
print("โ Access granted!")
break
else:
# This runs if while condition became False (not if break)
print("โ Too many attempts! Account locked.")
# ==================== HOW IT WORKS ====================
# If user enters correct password:
# โ break is executed
# โ else block is SKIPPED
# โ "Access granted!" is printed
# If user fails 3 times:
# โ attempts becomes 3, then 4
# โ 4 < 3 is False, loop ends normally
# โ else block RUNS
# โ "Account locked" is printed
# The else is like saying: "If we got through the whole loop without breaking..."
๐ก While vs For: When to Use Which?
- Use while when: You don't know how many iterations you need
- Use while when: Looping until some condition changes
- Use while True when: You'll break out based on complex conditions
- Use for when: You know the number of iterations
- Use for when: Iterating over a collection
For Loops: Iterate Over Collections
For loops are used when you know what you're iterating over - a range of numbers, characters in a string, items in a list. They're the most commonly used loop in Python because most real-world tasks involve processing collections.
The range() Function
# ==================== UNDERSTANDING RANGE() ====================
# range() generates a sequence of numbers
# It's the most common way to loop a specific number of times
# range(stop) - from 0 to stop-1
for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4 (5 numbers, starting at 0)
# range(start, stop) - from start to stop-1
for i in range(1, 6):
print(i)
# Output: 1, 2, 3, 4, 5 (from 1 up to but not including 6)
# range(start, stop, step) - count by step
for i in range(0, 10, 2):
print(i)
# Output: 0, 2, 4, 6, 8 (every other number)
for i in range(5, 0, -1):
print(i)
# Output: 5, 4, 3, 2, 1 (counting backwards)
# ==================== WHY RANGE EXCLUDES THE END ====================
# This makes the length match the count:
for i in range(5): # Loops 5 times (0,1,2,3,4)
pass
# And makes ranges easy to chain:
for i in range(0, 3): # 0, 1, 2
print(i)
for i in range(3, 6): # 3, 4, 5
print(i)
# Covers 0-5 without overlap or gap
# ==================== COMMON PATTERNS ====================
# Count from 1 to n:
n = 10
for i in range(1, n + 1): # Add 1 to include n
print(i)
# Loop n times (when you don't need i):
for _ in range(3):
print("Hello!") # Prints 3 times
# Generate list of numbers:
numbers = list(range(1, 11)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Iterating Over Strings
# ==================== CHARACTER BY CHARACTER ====================
word = "Python"
for letter in word:
print(letter)
# Output:
# P
# y
# t
# h
# o
# n
# ==================== WITH INDEX (ENUMERATE) ====================
for index, letter in enumerate(word):
print(f"Position {index}: {letter}")
# Output:
# Position 0: P
# Position 1: y
# Position 2: t
# Position 3: h
# Position 4: o
# Position 5: n
# Start counting from 1:
for index, letter in enumerate(word, start=1):
print(f"Letter #{index}: {letter}")
# Letter #1: P
# Letter #2: y
# ...
# ==================== PRACTICAL: COUNT VOWELS ====================
text = "Hello, World!"
vowels = "aeiouAEIOU"
vowel_count = 0
for char in text:
if char in vowels:
vowel_count += 1
print(f"'{text}' has {vowel_count} vowels") # 3 vowels
# ==================== PRACTICAL: REVERSE A STRING ====================
original = "Python"
reversed_str = ""
for char in original:
reversed_str = char + reversed_str # Add to front
print(reversed_str) # "nohtyP"
# (Python has easier ways: original[::-1])
Iterating Over Lists
# ==================== BASIC ITERATION ====================
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
print(f"I like {fruit}")
# ==================== WITH INDEX ====================
for i, fruit in enumerate(fruits):
print(f"{i + 1}. {fruit}")
# 1. apple
# 2. banana
# ...
# ==================== MODIFYING WHILE ITERATING (CAREFUL!) ====================
# DON'T modify a list while iterating over it:
numbers = [1, 2, 3, 4, 5]
# for num in numbers:
# if num % 2 == 0:
# numbers.remove(num) # DANGEROUS! Skips elements
# INSTEAD, iterate over a copy or use list comprehension:
numbers = [1, 2, 3, 4, 5]
for num in numbers[:]: # [:] creates a copy
if num % 2 == 0:
numbers.remove(num) # Safe
# OR better - filter to new list:
numbers = [1, 2, 3, 4, 5]
odd_numbers = [n for n in numbers if n % 2 != 0]
# ==================== COMMON LIST OPERATIONS ====================
numbers = [10, 20, 30, 40, 50]
# Sum
total = 0
for n in numbers:
total += n
print(f"Sum: {total}") # 150 (or just use sum(numbers))
# Find maximum
maximum = numbers[0]
for n in numbers:
if n > maximum:
maximum = n
print(f"Max: {maximum}") # 50 (or just use max(numbers))
# Filter
even = []
for n in numbers:
if n % 2 == 0:
even.append(n)
print(f"Even: {even}") # All of them in this case
# Transform
doubled = []
for n in numbers:
doubled.append(n * 2)
print(f"Doubled: {doubled}") # [20, 40, 60, 80, 100]
Nested Loops
# ==================== MULTIPLICATION TABLE ====================
print("Multiplication Table:")
print("-" * 40)
for i in range(1, 11):
for j in range(1, 11):
print(f"{i * j:4}", end="") # :4 means 4 character width
print() # New line after each row
# ==================== PATTERN PRINTING ====================
# Right triangle:
for i in range(1, 6):
print("*" * i)
# *
# **
# ***
# ****
# *****
# Inverted triangle:
for i in range(5, 0, -1):
print("*" * i)
# Square:
size = 5
for row in range(size):
for col in range(size):
print("*", end=" ")
print()
# ==================== PROCESSING 2D DATA ====================
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for cell in row:
print(cell, end=" ")
print()
# With indices:
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(f"matrix[{i}][{j}] = {matrix[i][j]}")
Practical Examples
# ==================== FACTORIAL ====================
n = 5
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"{n}! = {factorial}") # 5! = 120
# ==================== FIBONACCI SEQUENCE ====================
n_terms = 10
a, b = 0, 1
print(f"First {n_terms} Fibonacci numbers:")
for _ in range(n_terms):
print(a, end=" ")
a, b = b, a + b
print() # 0 1 1 2 3 5 8 13 21 34
# ==================== PRIME NUMBER CHECKER ====================
num = 29
is_prime = True
if num < 2:
is_prime = False
else:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is prime")
else:
print(f"{num} is not prime")
# ==================== FIND ALL PRIMES UP TO N ====================
limit = 50
primes = []
for num in range(2, limit + 1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)
print(f"Primes up to {limit}: {primes}")
๐ก For Loop Pro Tips
- Use
_ as the variable name when you don't need the value
- Use
enumerate() when you need both index and value
- Use
zip() to iterate over multiple lists simultaneously
- Built-in functions like
sum(), min(), max() often replace manual loops
- List comprehensions (next chapter) are often cleaner than loops
Break and Continue: Loop Control
Sometimes you need to exit a loop early or skip certain iterations. That's what break and continue are for. They give you fine-grained control over loop execution.
Break - Exit Loop Immediately
# ==================== BASIC BREAK ====================
# break immediately exits the entire loop
for i in range(10):
if i == 5:
break # Exit when i is 5
print(i)
# Output: 0, 1, 2, 3, 4 (stops before printing 5)
# ==================== SEARCH AND FIND ====================
# Find first even number
for num in [1, 3, 5, 8, 9, 10]:
if num % 2 == 0:
print(f"First even number: {num}") # 8
break
# Find item in list
items = ["apple", "banana", "cherry", "date"]
search = "cherry"
for i, item in enumerate(items):
if item == search:
print(f"Found '{search}' at index {i}")
break
else:
# This else belongs to the for loop!
# It runs ONLY if the loop completed without break
print(f"'{search}' not found")
# ==================== BREAK IN NESTED LOOPS ====================
# break only exits the INNERMOST loop!
for i in range(3):
print(f"Outer loop i = {i}")
for j in range(3):
if j == 1:
break # Only breaks inner loop
print(f" Inner loop j = {j}")
# Output:
# Outer loop i = 0
# Inner loop j = 0 (j=1 breaks, inner loop restarts for i=1)
# Outer loop i = 1
# Inner loop j = 0
# Outer loop i = 2
# Inner loop j = 0
# ==================== EARLY EXIT ON ERROR ====================
data = [10, 20, "error", 30]
total = 0
for item in data:
if not isinstance(item, (int, float)):
print(f"Error: Non-numeric value '{item}' found!")
break
total += item
print(f"Sum of valid items: {total}") # 30
Continue - Skip to Next Iteration
# ==================== BASIC CONTINUE ====================
# continue skips the rest of THIS iteration and goes to the next
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
# Output: 1, 3, 5, 7, 9 (only odd numbers)
# ==================== SKIP INVALID DATA ====================
data = [10, -5, 20, -3, 15, 0, 25]
total = 0
for value in data:
if value <= 0:
continue # Skip non-positive numbers
total += value
print(f"Sum of positive numbers: {total}") # 70
# ==================== SKIP WITH MESSAGE ====================
numbers = [1, 2, "three", 4, None, 6]
for num in numbers:
if not isinstance(num, (int, float)):
print(f"Skipping invalid value: {num}")
continue
# This code only runs for valid numbers
print(f"Processing: {num}, squared = {num ** 2}")
# ==================== FILTERING PATTERN ====================
# Process only items meeting criteria
users = [
{"name": "Alice", "active": True, "age": 25},
{"name": "Bob", "active": False, "age": 30},
{"name": "Charlie", "active": True, "age": 17},
{"name": "Diana", "active": True, "age": 22},
]
print("Active adult users:")
for user in users:
# Skip inactive users
if not user["active"]:
continue
# Skip minors
if user["age"] < 18:
continue
# Only active adults reach here
print(f" {user['name']}, age {user['age']}")
Break vs Continue Comparison
# ==================== SIDE BY SIDE COMPARISON ====================
print("=== With break ===")
for i in range(1, 6):
if i == 3:
break
print(i)
# Output: 1, 2 (stops at 3)
print("\n=== With continue ===")
for i in range(1, 6):
if i == 3:
continue
print(i)
# Output: 1, 2, 4, 5 (skips 3, continues loop)
# ==================== WHEN TO USE WHICH ====================
# BREAK when:
# - You found what you were searching for
# - An error occurred and you can't continue
# - A condition means remaining iterations are useless
# - You want to exit a while True loop
# CONTINUE when:
# - This specific item should be skipped
# - You're filtering within a loop
# - You want to avoid deep nesting in the loop body
# ==================== AVOID DEEP NESTING WITH CONTINUE ====================
# Without continue (deep nesting):
for user in users:
if user["active"]:
if user["age"] >= 18:
if user["name"]:
# Finally, the actual logic
process(user)
# With continue (flat structure):
for user in users:
if not user["active"]:
continue
if user["age"] < 18:
continue
if not user["name"]:
continue
# Clean, readable - only the happy path here
process(user)
Complete Example: Interactive Menu
# ==================== MENU WITH LOOP CONTROL ====================
print("=" * 50)
print(" ๐ฎ INTERACTIVE MENU SYSTEM")
print("=" * 50)
while True:
print("\n๐ MENU:")
print("1. Say Hello")
print("2. Calculate Sum")
print("3. Count to 10")
print("4. Check Prime")
print("5. Quit")
print("-" * 30)
choice = input("Choose (1-5): ").strip()
# Skip if empty input
if not choice:
print("โ ๏ธ Please enter a choice!")
continue
# Exit condition
if choice == "5":
print("\n๐ Goodbye!")
break # Exit the while True loop
# Handle each option
if choice == "1":
name = input("What's your name? ")
print(f"๐ Hello, {name}!")
elif choice == "2":
try:
nums = input("Enter numbers (space-separated): ")
total = sum(int(n) for n in nums.split())
print(f"๐ Sum: {total}")
except ValueError:
print("โ Invalid numbers!")
continue
elif choice == "3":
print("๐ข Counting: ", end="")
for i in range(1, 11):
print(i, end=" ")
print()
elif choice == "4":
try:
num = int(input("Enter a number: "))
if num < 2:
print(f"โ {num} is not prime")
else:
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"โ {num} is prime!")
else:
print(f"โ {num} is not prime")
except ValueError:
print("โ Please enter a valid number!")
continue
else:
print("โ Invalid choice! Please enter 1-5.")
continue
input("\nPress Enter to continue...")
๐ก Loop Control Best Practices
- Use break sparingly: Too many breaks make flow hard to follow
- Use continue for filtering: It's cleaner than nested ifs
- Document why: Add a comment explaining why you're breaking/continuing
- Consider functions: return can replace break in many cases
- Use for-else: The else clause with loops is powerful for search patterns
Chapter Project: Tic-Tac-Toe Game
# ==================== TIC-TAC-TOE ====================
# Uses everything from Chapter 1 and 2!
def print_board(board):
print()
for i in range(3):
for j in range(3):
print(f" {board[i][j]} ", end="")
if j < 2:
print("|", end="")
print()
if i < 2:
print("-----------")
print()
def check_winner(board, player):
# Check rows
for row in board:
if all(cell == player for cell in row):
return True
# Check columns
for col in range(3):
if all(board[row][col] == player for row in range(3)):
return True
# Check diagonals
if all(board[i][i] == player for i in range(3)):
return True
if all(board[i][2-i] == player for i in range(3)):
return True
return False
def is_full(board):
return all(cell != " " for row in board for cell in row)
# Main game
print("๐ฎ TIC-TAC-TOE")
print("Positions are 1-9:")
print(" 1 | 2 | 3 ")
print("-----------")
print(" 4 | 5 | 6 ")
print("-----------")
print(" 7 | 8 | 9 ")
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"
while True:
print_board(board)
# Get move
while True:
try:
move = int(input(f"Player {current_player}, enter position (1-9): "))
if 1 <= move <= 9:
row = (move - 1) // 3
col = (move - 1) % 3
if board[row][col] == " ":
break
print("That spot is taken!")
else:
print("Enter 1-9!")
except ValueError:
print("Enter a number!")
continue
# Make move
board[row][col] = current_player
# Check win
if check_winner(board, current_player):
print_board(board)
print(f"๐ Player {current_player} wins!")
break
# Check draw
if is_full(board):
print_board(board)
print("๐ค It's a draw!")
break
# Switch player
current_player = "O" if current_player == "X" else "X"