← Zero to Python Chapter 3: Flow Control
0% Complete

Conditionals: Making Decisions

Programs need to make decisions. Should we show an error message? Grant access? Display a discount? This is where conditional statements come in - they let your code choose different paths based on conditions.

The if Statement

The simplest conditional - do something IF a condition is true:

if_basic.py Python
age = 21 if age >= 18: print("You are an adult!") print("Welcome to the club.") print("This always runs.")
You are an adult! Welcome to the club. This always runs.

Indentation Matters!

Python uses indentation (typically 4 spaces) to define code blocks. Everything indented after the if statement runs only when the condition is true. The non-indented line runs regardless.

The if-else Statement

What if the condition is false? Use else to handle that case:

if_else.py Python
temperature = 35 if temperature > 30: print("It's hot outside! ") else: print("It's not too hot.")

The if-elif-else Chain

For multiple conditions, use elif (short for "else if"):

if_elif_else.py Python
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 is: {grade}")
Your grade is: B

Order Matters!

Python checks conditions top to bottom and stops at the first match. If we checked score >= 60 first, a score of 95 would get a "D"! Always order from most specific to least specific.

Lab Exercise 1: Access Control

Beginner

Instructions

Create a simple access control system. Check if a user has the right credentials!

Your Task

Given user_role = "admin", print:
- "Full access granted" if role is "admin"
- "Limited access granted" if role is "user"
- "Access denied" for anything else

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Conditionals Complete!

You can make decisions in code! Let's learn about comparison operators.

Comparison Operators

Conditions use comparison operators to compare values. These operators always return True or False.

Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 10 > 5 True
< Less than 3 < 7 True
>= Greater than or equal 5 >= 5 True
<= Less than or equal 4 <= 4 True

== vs = (Critical!)

= is assignment (puts a value in a variable)
== is comparison (checks if two values are equal)
This is one of the most common beginner mistakes!

Comparing Strings

Strings are compared alphabetically (lexicographically):

string_compare.py Python
print("apple" < "banana") # True (a comes before b) print("Apple" < "apple") # True (uppercase comes first!) print("hello" == "Hello") # False (case-sensitive) # Case-insensitive comparison: name1 = "Alice" name2 = "alice" print(name1.lower() == name2.lower()) # True

Chained Comparisons

Python allows elegant chained comparisons:

chained.py Python
age = 25 # Instead of: age >= 18 and age <= 65 if 18 <= age <= 65: print("Working age") # Check if a value is in range score = 75 if 0 <= score <= 100: print("Valid score!")

Lab Exercise 2: Number Classifier

Beginner

Instructions

Use comparison operators to classify a number.

Your Task

Given num = 0, print:
- "Positive" if num > 0
- "Negative" if num < 0
- "Zero" if num == 0

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Comparison Mastered!

You can compare values. Now let's combine conditions with logical operators!

Logical Operators

What if you need to check multiple conditions? Logical operators combine boolean expressions!

Operator Meaning Example Result
and Both must be True True and False False
or At least one must be True True or False True
not Inverts the boolean not True False
logical.py Python
age = 25 has_license = True is_suspended = False # AND: Both conditions must be True if age >= 18 and has_license: print("Can drive!") # OR: At least one condition must be True if age < 18 or is_suspended: print("Cannot drive.") else: print("Eligible to drive.") # NOT: Inverts the condition if not is_suspended: print("License is valid!")

Truthy and Falsy Values

In Python, values can be evaluated as boolean even if they're not True/False:

truthy_falsy.py Python
# Falsy values (evaluate to False): # False, None, 0, 0.0, "", [], {}, set() # Truthy values (evaluate to True): # Everything else! name = "" # Empty string is falsy if name: print(f"Hello, {name}!") else: print("Name is empty!") items = [1, 2, 3] # Non-empty list is truthy if items: print(f"List has {len(items)} items")

Short-Circuit Evaluation

Python is smart! With and, if the first condition is False, it doesn't check the second (result is already False). With or, if the first is True, it doesn't check the second. This can prevent errors!

Lab Exercise 3: Login Validator

Intermediate

Instructions

Create a login validator using logical operators!

Your Task

Given username = "admin" and password = "secret123":
- Print "Login successful!" if BOTH are correct
- Print "Invalid credentials!" otherwise
(Correct: username="admin", password="secret123")

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Logical Operators Complete!

You can combine conditions. Now let's learn about loops!

Loops: Repeating Actions

Loops let you execute code multiple times. Python has two main loop types: while and for.

The while Loop

Repeats while a condition is True - useful when you don't know how many times to repeat:

while_loop.py Python
count = 1 while count <= 5: print(f"Count: {count}") count += 1 # Don't forget to update! print("Done!")
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Done!

Infinite Loop Danger!

If the condition never becomes False, the loop runs forever! Always make sure your loop has a way to end (like incrementing a counter).

The for Loop

Iterates over a sequence (list, string, range) - perfect when you know what to iterate:

for_loop.py Python
# Loop through a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"I like {fruit}!") # Loop through a string for char in "Python": print(char) # Loop through numbers with range() for i in range(5): print(i) # 0, 1, 2, 3, 4

The range() Function

Generates a sequence of numbers - perfect for loops!

range_examples.py Python
# range(stop) - 0 to stop-1 print(list(range(5))) # [0, 1, 2, 3, 4] # range(start, stop) print(list(range(2, 6))) # [2, 3, 4, 5] # range(start, stop, step) print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8] (evens) print(list(range(10, 0, -1))) # [10, 9, 8, ...] (countdown)

for vs while

for: Use when you know the items/count (iterate through a list, run 10 times)
while: Use when you don't know when to stop (keep asking until valid input)

Lab Exercise 4: Multiplication Table

Intermediate

Instructions

Use a for loop to generate a multiplication table!

Your Task

Given num = 5, print the multiplication table from 1 to 5:
5 x 1 = 5
5 x 2 = 10
... and so on

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Loops Mastered!

You can repeat actions! Let's learn to control loop flow.

Loop Control: break, continue, else

Sometimes you need more control over loops - exit early, skip iterations, or do something when the loop completes normally.

break - Exit the Loop

Immediately exits the loop, even if the condition is still True:

break_example.py Python
# Search for a number numbers = [4, 7, 2, 9, 1, 5] target = 9 for num in numbers: print(f"Checking {num}...") if num == target: print(f"Found {target}!") break # Stop searching print("Search complete.")
Checking 4... Checking 7... Checking 2... Checking 9... Found 9! Search complete.

continue - Skip to Next Iteration

Skips the rest of the current iteration and goes to the next:

continue_example.py Python
# Print only odd numbers for i in range(1, 11): if i % 2 == 0: # If even continue # Skip this number print(i)
1 3 5 7 9

Loop else Clause

The else block runs only if the loop completes without hitting break:

loop_else.py Python
# Search with else (for "not found" case) numbers = [1, 3, 5, 7] target = 4 for num in numbers: if num == target: print(f"Found {target}!") break else: # Only runs if break was NOT hit print(f"{target} not found in list.")
4 not found in list.

Nested Loops

You can put loops inside loops! break only exits the innermost loop. For complex nested loop control, consider using functions with return.

Lab Exercise 5: Prime Checker

Intermediate

Instructions

Use a loop with break to check if a number is prime!

Your Task

Given num = 17, check if it's prime (divisible only by 1 and itself).
Print "Prime!" or "Not prime!"

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Loop Control Complete!

You have full control over loops! Time for the summary.

Chapter 3 Summary

Congratulations! You've completed Chapter 3 and mastered Python flow control. Let's recap:

What You Learned

  • Conditionals: if, elif, else - making decisions in code
  • Comparison Operators: ==, !=, >, <, >=, <= - comparing values
  • Logical Operators: and, or, not - combining conditions
  • while Loops: Repeat while condition is True
  • for Loops: Iterate over sequences
  • range(): Generate number sequences
  • Loop Control: break (exit), continue (skip), else (no-break)

Key Takeaways

Conditionals

Order matters! Check most specific conditions first.

Comparison

== compares, = assigns. Never confuse them!

Loops

for when you know iterations, while when you don't.

Control

break exits, continue skips, else runs if no break.

Chapter 3 Complete!

You've mastered Python flow control. Ready to prove your skills?

Take the Chapter 3 Practical Exam