10xdev Book: Programming from Zero to Pro with Python

Chapter 5: Control Flow in Python 3.14: Conditionals (`if`/`else`) and Loops (`for`/`while`)

Chapter 5: Control Flow in Python 3.14: Conditionals (if/else) and Loops (for/while) 🤔

Chapter Introduction

So far, our Python scripts have been like a straight road – executing one line after another. But real power comes when your program can make choices and repeat actions, like navigating city streets with turns and roundabouts.

This chapter is all about control flow – directing how your program runs. We’ll learn the two fundamental tools in Python 3.14 for this:

  • Conditionals (if, elif, else): Letting your program choose different paths based on whether something is True or False. 🚦
  • Loops (while, for): Making your program repeat a block of code efficiently, without you having to copy and paste. 🔄

Mastering these will let you build much more dynamic and intelligent applications.


1. Conditionals: Making Decisions

Just like you decide whether to take an umbrella based on the weather, your program can make decisions using if statements.

A. The Basic if: Plan A

The if statement checks a condition. If that condition evaluates to True, the indented code block underneath it runs.

age: int = 20

# The condition: Is age greater than or equal to 18?
if age >= 18:
    # This block runs only if the condition is True
    print("You are old enough to vote.")
    print("Make sure you're registered!")

🚨 Indentation is Crucial! Python uses whitespace (usually 4 spaces) to define code blocks. The lines indented under if belong to it. If you mess this up, Python 3.14 will give you an IndentationError (often with helpful suggestions these days!).


B. Adding else: Plan B

What if the if condition is False? Use else to provide an alternative block of code that runs only when the if fails.

temperature: float = 15.0

if temperature > 25.0:
    print("It's a hot day!")
else:
    # This runs if temperature is NOT > 25.0
    print("The weather is mild or cool.")

else doesn’t need its own condition; it’s the catch-all for when the if isn’t met.


C. Multiple Choices with elif

Need more than two options? Use elif (short for “else if”) to add more conditions. Python checks them in order and runs the code block for the first one that is True.

score: int = 75

if score >= 90:
    grade: str = "A"
elif score >= 80: # Checked only if score < 90
    grade: str = "B"
elif score >= 70: # Checked only if score < 80
    grade: str = "C"
else:             # Runs only if score < 70
    grade: str = "F"

print(f"Your grade is: {grade}") # Output: Your grade is: C

D. Comparison and Logical Operators

These are the tools you use to build your conditions:

  • Comparison: == (equal), != (not equal), > (greater than), < (less than), >= (greater or equal), <= (less or equal)
  • Logical:
    • and: Both sides must be True. (age >= 18 and has_id)
    • or: At least one side must be True. (is_weekend or is_holiday)
    • not: Reverses the boolean value. (not is_raining)

E. “Truthy” and “Falsy” Values (A Neat Shortcut)

Python treats certain values as inherently “false” in conditional contexts. Everything else is “true”.

Falsy Values:

  • None
  • False
  • Zero of any numeric type (0, 0.0)
  • Empty sequences and collections ("", [], {})

This allows for concise checks:

user_input: str = input("Enter your name (optional): ")

# Instead of: if user_input != "":
if user_input: # Checks if the string is NOT empty (i.e., Truthy)
    print(f"Hello, {user_input}!")
else:
    print("Hello, anonymous user!")

2. Loops: Repeating Actions

Why write the same code 100 times? Loops let you automate repetition.

A. while Loops: Repeat While True

A while loop keeps executing its code block as long as its condition remains True.

count: int = 1
while count <= 5:
    print(f"Count is: {count}")
    count += 1 # CRUCIAL: Update the condition variable! (+= 1 is short for count = count + 1)

print("Loop finished!")

Warning: If you forget to update the variable in the condition (like count += 1), the condition might stay True forever, causing an infinite loop! 🥶


B. for Loops: Repeat For Each Item

A for loop iterates over a sequence (like a string, a list, or results from range()), running its code block once for each item in the sequence.

  • Looping over a string:

    for character in "Python":
        print(character)
    
  • Looping with range(): Generates a sequence of numbers.

    • range(5) -> 0, 1, 2, 3, 4
    • range(1, 6) -> 1, 2, 3, 4, 5
    • range(0, 10, 2) -> 0, 2, 4, 6, 8 (start, stop-before, step)
    print("Countdown:")
    for i in range(3, 0, -1): # From 3 down to 1
        print(i)
    print("Blast off!")
    

C. Controlling Loops: break and continue

  • break: Exits the current loop immediately. 🛑
  • continue: Skips the rest of the current iteration and jumps to the beginning of the next one. ⏭️
# Find the first multiple of 7
print("Finding first multiple of 7:")
for num in range(1, 20):
    if num % 7 == 0:
        print(f"Found it: {num}")
        break # Stop searching

# Print odd numbers only
print("\nOdd numbers from 1 to 10:")
for num in range(1, 11):
    if num % 2 == 0: # If it's even...
        continue     # ...skip the print and go to the next number
    print(num)

3. A Note on Exceptions vs. Control Flow

You might see code (or be tempted to write code) that uses try...except to handle expected situations, like checking if a key exists in a dictionary before accessing it. While Python’s philosophy is sometimes “Easier to Ask for Forgiveness than Permission” (EAFP), using exceptions for normal program flow is generally considered an anti-pattern.

  • Exceptions are slow compared to regular checks.
  • Overusing them makes code harder to read and debug.

Bad (using exception for flow):

my_dict = {"a": 1}
try:
    value = my_dict["b"]
    print(value)
except KeyError:
    print("Key 'b' not found.")

Good (using conditional check):

my_dict = {"a": 1}
if "b" in my_dict:
    value = my_dict["b"]
    print(value)
else:
    # Or use .get() for a default
    value = my_dict.get("b", "Default Value")
    print(f"Key 'b' not found, using: {value}")

Use try...except for unexpected errors (like file not found, network issues), not for predictable checks. Python 3.14 even simplifies catching multiple exceptions: you no longer need parentheses except (ValueError, TypeError) – you can just write except ValueError, TypeError.


4. Applied Project: Simple Password Checker

Let’s combine loops and conditionals. This program gives the user 3 tries to guess a password.

SECRET_PASSWORD: str = "python314"
MAX_ATTEMPTS: int = 3

print(f"You have {MAX_ATTEMPTS} attempts to enter the password.")

for attempt in range(MAX_ATTEMPTS):
    guess: str = input(f"Attempt #{attempt + 1}: Enter password: ")

    if guess == SECRET_PASSWORD:
        print("Access granted!")
        break # Exit the loop on success
    else:
        print("Incorrect password.")
        remaining_attempts = MAX_ATTEMPTS - (attempt + 1)
        if remaining_attempts > 0:
            print(f"You have {remaining_attempts} attempts left.")

# This 'else' block is attached to the 'for' loop!
# It runs ONLY if the loop completed WITHOUT hitting 'break'.
else:
    print("Access denied. Too many incorrect attempts.")

This for...else structure is a neat Python feature, perfect for situations like this where you need to know if a loop finished normally or was exited early.


5. Chapter Summary

You’ve now learned how to control the flow of your Python 3.14 programs!

  • if/elif/else let your code make decisions.
  • Truthy/Falsy values provide convenient shortcuts in conditions.
  • while loops repeat as long as a condition is True.
  • for loops iterate over items in a sequence (like strings or range()).
  • break exits a loop; continue skips to the next iteration.
  • Avoid using exceptions for normal control flow; use conditional checks instead.

Your programs can now make decisions and repeat tasks! But as they get bigger, just having one long script becomes messy. To keep your code organized and avoid repetition, the next step is learning how to bundle logic into reusable blocks called functions.