5. Control Flow
Teaching your program to make decisions
A program that runs the same code every time isn't very useful. Real programs need to make decisions. Control flow is how you make that happen.
The if statement is the most fundamental decision-maker in all of programming:
temperature = 35 if temperature > 30: print('It is hot outside.') print('Drink water!') elif temperature > 20: print('Nice weather today.') elif temperature > 10: print('A bit cool — bring a jacket.') else: print('It is cold. Stay warm!')
Notice the indentation. In Python, indentation is not optional — it's how Python knows which code belongs inside the if block. Most other languages use curly braces {} instead.
Always use 4 spaces for each level of indentation. Never mix tabs and spaces. VS Code will handle this for you if you configure it correctly.
Nested Conditions
You can place if statements inside other if statements. This is called nesting, and it's useful when you need to check multiple layers of conditions:
is_member = True account_balance = 500 requested_amount = 200 if is_member: if account_balance >= requested_amount: print('Withdrawal approved.') account_balance -= requested_amount else: print('Insufficient funds.') else: print('Please create a membership first.')
Be careful with deep nesting — more than 2 or 3 levels becomes hard to read. Often, deeply nested code can be rewritten using logical operators (and, or) or by returning early from functions.
Switch Statements
Python 3.10 introduced match/case (equivalent to switch in other languages). It's cleaner than a long chain of elif when you're checking one variable against many specific values:
# Python match/case (3.10+) day = 'Monday' match day: case 'Monday' | 'Tuesday' | 'Wednesday' | 'Thursday' | 'Friday': print('It is a weekday.') case 'Saturday' | 'Sunday': print('It is the weekend!') case _: print('Unknown day.')
In JavaScript, the switch statement is more common:
// JavaScript switch const status = 'active'; switch(status) { case 'active': console.log('User is active.'); break; case 'suspended': console.log('Account suspended.'); break; default: console.log('Unknown status.'); }
Ternary Operators
A ternary operator is a compact way to write a simple if/else on one line. It's called ternary because it takes three parts:
# Python ternary age = 20 status = 'adult' if age >= 18 else 'minor' print(status) # adult # JavaScript ternary # const status = age >= 18 ? 'adult' : 'minor';
Use ternary operators for simple yes/no assignments. If your logic is more complex, a regular if/else is clearer and more readable — don't sacrifice clarity for cleverness.
Real-World Logic Implementation
Let's put it all together with a real scenario — a basic login system:
username = input('Enter username: ') password = input('Enter password: ') # Stored credentials (in real apps, never store passwords as plain text!) VALID_USER = 'admin' VALID_PASS = 'secret123' is_locked = False failed_attempts = 0 if is_locked: print('Account is locked. Contact support.') elif username == VALID_USER and password == VALID_PASS: print(f'Welcome back, {username}!') elif username == VALID_USER: failed_attempts += 1 print(f'Wrong password. Attempt {failed_attempts} of 3.') else: print('Username not found.')
Knowledge Check
Ready to test your understanding of 5. Control Flow?