Introduction: Guiding Your Code’s Choices

Welcome back, future Pythonista! In our previous chapters, you learned about Python’s fundamental building blocks: variables, different data types, and how to perform basic operations. You can store information, manipulate numbers, and even work with text. That’s fantastic! But so far, your programs have been a bit like a train on a single, straight track – they just run from start to finish, executing every line in order.

What if your program needs to make a choice? What if it should do one thing if a condition is met, and something else if it’s not? Imagine a game where a character only moves if the player presses a certain key, or an app that displays a “Good Morning” message before noon and “Good Afternoon” after. This is where control flow comes in!

In this chapter, we’re going to dive into the exciting world of conditional statements. You’ll learn how to empower your Python programs to make decisions, respond dynamically to different situations, and follow various “paths” based on specific conditions. Get ready to add a whole new level of intelligence and interactivity to your code! You’ll be using concepts like variables and basic operations from our earlier chapters, so you’re already well-prepared.

Core Concepts: The Logic of Decision-Making

At its heart, making decisions in programming is all about evaluating whether something is True or False. Based on that evaluation, your program will then choose which block of code to execute. Python gives us powerful tools to define these conditions and guide our program’s flow.

Conditional Statements: if, elif, and else

These three keywords are your primary tools for creating decision-making structures. Think of them as a flowchart for your code!

The if Statement: “If this is true, do this!”

The if statement is the simplest form of a conditional check. It asks a question, and if the answer is “yes” (meaning the condition is True), it executes a specific block of code. If the answer is “no” (False), it simply skips that block and moves on.

Key Idea: The code inside the if block will only run if the condition is True.

The else Statement: “Otherwise, do this!”

Often, when a condition isn’t met, you don’t just want to skip doing anything; you want to do something different. That’s where else comes in. It provides an alternative block of code to execute only if the if condition (or any preceding elif conditions) turns out to be False.

Key Idea: The else block acts as a fallback. It runs when no other conditions above it were True.

The elif Statement: “But if this is true, do this instead!”

What if you have multiple conditions you want to check, one after another? That’s where elif (short for “else if”) shines. You can chain multiple elif statements together after an if statement. Python will check each condition in order, from top to bottom. As soon as it finds a condition that is True, it executes that block of code and then skips the rest of the elif/else chain.

Key Idea: elif allows you to check multiple, mutually exclusive conditions in a sequence. Only the first True condition’s block will execute.

Comparison Operators: Asking Questions

How do we actually define those True or False conditions? We use comparison operators to compare values. These operators always return either True or False.

Here are the most common ones:

  • == (Equal to): Is a equal to b? (Be careful not to confuse with =, which is for assignment!)
  • != (Not equal to): Is a not equal to b?
  • < (Less than): Is a less than b?
  • > (Greater than): Is a greater than b?
  • <= (Less than or equal to): Is a less than or equal to b?
  • >= (Greater than or equal to): Is a greater than or equal to b?

Logical Operators: Combining Conditions

Sometimes, a single comparison isn’t enough. You might need to check if multiple things are true, or if at least one of several things is true. That’s where logical operators come in handy.

  • and: Returns True if both conditions are True.
    • Example: (age > 18) and (has_license == True)
  • or: Returns True if at least one of the conditions is True.
    • Example: (is_weekend == True) or (is_holiday == True)
  • not: Reverses the truth value of a condition. not True is False, and not False is True.
    • Example: not is_raining (means “it is not raining”)

Step-by-Step Implementation: Building Your First Decision-Maker

Let’s put these concepts into practice! We’ll start simple and gradually build up to more complex decision-making.

Open your preferred Python editor (like VS Code, which we set up in Chapter 1) or an online Python interpreter.

Step 1: The Simple if Statement

Let’s write a program that checks if a number is positive.

First, create a new Python file, say decisions.py.

# decisions.py

# Define a variable
number = 10

# Check if the number is positive using an if statement
if number > 0:
    print("The number is positive.")

print("This line always runs.")

Explanation:

  • number = 10: We start by assigning the value 10 to our number variable.
  • if number > 0:: This is our if statement.
    • number > 0 is the condition. Python evaluates this. Is 10 greater than 0? Yes, it’s True.
    • The colon : at the end of the if line is crucial! It tells Python that a new indented block of code is about to follow.
  • print("The number is positive."): This line is indented (usually by 4 spaces). This indentation is how Python knows this line belongs to the if block. Because number > 0 was True, this line will be executed.
  • print("This line always runs."): This line is not indented. It’s outside the if block and will run regardless of whether the condition was True or False.

Now, run this code. You should see:

The number is positive.
This line always runs.

Try changing number to -5 and run it again. What happens? Only “This line always runs.” should appear, because the if condition (-5 > 0) is False, and the indented print statement is skipped.

Step 2: Adding an else Clause

Now, let’s make our program tell us if the number is not positive.

Modify your decisions.py file:

# decisions.py

number = -5 # Let's try a negative number this time

if number > 0:
    print("The number is positive.")
else: # If the condition above (number > 0) is False, do this instead
    print("The number is not positive.")

print("This line still always runs.")

Explanation:

  • number = -5: We set number to a negative value.
  • if number > 0:: This condition (-5 > 0) is False. So, the print("The number is positive.") line is skipped.
  • else:: Because the if condition was False, Python looks for an else block. The colon : here also signifies an indented block.
  • print("The number is not positive."): This indented line will be executed because the if condition was False.

Run this code. You should see:

The number is not positive.
This line still always runs.

Step 3: Introducing elif for Multiple Conditions

What if we want to distinguish between positive, negative, and zero? This is a perfect job for elif.

Modify your decisions.py file again:

# decisions.py

number = 0 # Let's test with zero

if number > 0:
    print("The number is positive.")
elif number < 0: # If the first condition was False, check this one
    print("The number is negative.")
else: # If neither of the above conditions were True, then it must be zero
    print("The number is zero.")

print("This program has finished checking the number.")

Explanation:

  • number = 0: We initialize number to 0.
  • if number > 0:: Is 0 > 0? No, that’s False. Python moves on.
  • elif number < 0:: Is 0 < 0? No, that’s also False. Python moves on.
  • else:: Since neither the if nor the elif condition was True, the else block is executed.
  • print("The number is zero."): This line prints.

Try running the code with number = 10, then number = -10, then number = 0. Observe how the output changes based on the value of number.

Step 4: Using Comparison and Logical Operators

Let’s create a program that checks eligibility for a discount based on age and whether it’s a special event day.

# decisions.py - (overwrite or start a new file)

age = 25
is_special_event = True # Assume it's a special event day

# Check discount eligibility
if age >= 18 and is_special_event:
    print("You are eligible for a special event discount!")
elif age >= 18:
    print("You are eligible for a regular discount.")
else:
    print("Sorry, you are not eligible for any discount.")

# Let's try another scenario
print("\n--- Another Scenario ---")
age = 16
is_special_event = False

if age >= 18 and is_special_event:
    print("You are eligible for a special event discount!")
elif age >= 18:
    print("You are eligible for a regular discount.")
else:
    print("Sorry, you are not eligible for any discount.")

Explanation:

  • age = 25 and is_special_event = True: We set up our initial scenario.
  • if age >= 18 and is_special_event::
    • age >= 18 (25 >= 18) is True.
    • is_special_event (True) is True.
    • Since both parts of the and condition are True, the entire condition is True.
    • The first print statement executes. The rest of the elif/else chain is skipped.
  • In the “Another Scenario”:
    • age = 16 and is_special_event = False.
    • if age >= 18 and is_special_event::
      • age >= 18 (16 >= 18) is False.
      • Since the first part of the and is False, the whole and condition is False. Python doesn’t even need to check is_special_event.
    • elif age >= 18:: (16 >= 18) is False.
    • else:: Since all previous conditions were False, the else block executes.
    • print("Sorry, you are not eligible for any discount.") prints.

Feel free to play around with the age and is_special_event values to see how the output changes. This is how your programs can become truly dynamic!

Mini-Challenge: The Weather Advisor

It’s your turn to put these skills to the test!

Challenge: Write a Python program that takes a temperature (as an integer) and advises on what to wear.

  • If the temperature is 30 or above, print: “It’s scorching hot! Stay hydrated!”
  • If the temperature is between 20 (inclusive) and 29 (inclusive), print: “It’s a lovely warm day. Light clothing is perfect.”
  • If the temperature is between 10 (inclusive) and 19 (inclusive), print: “It’s a bit cool. A light jacket might be nice.”
  • If the temperature is below 10, print: “Brrr! It’s cold. Bundle up!”

Hint: You’ll need to use input() to get the temperature from the user, convert it to an integer, and then use if, elif, and else with comparison operators. Remember how to convert input strings to numbers from Chapter 2!

What to observe/learn: How to chain multiple elif statements to handle different ranges, and how to combine input with control flow.

# Your code for the Mini-Challenge goes here!
Need a little nudge? Click for a hint!

Remember that `input()` gives you a string. You'll want to use `int()` to convert it to a number before you can compare it. For ranges like "between 20 and 29", you'll need to use the `and` logical operator, e.g., `temperature >= 20 and temperature <= 29`.

Common Pitfalls & Troubleshooting

Even experienced programmers make mistakes, especially with new concepts! Here are a few common traps to watch out for:

  1. Indentation Errors: Python is very strict about indentation. If your code blocks aren’t correctly indented (usually 4 spaces), you’ll get an IndentationError.

    # BAD CODE - will cause IndentationError
    temperature = 5
    if temperature > 0:
    print("Positive") # This line is not indented!
    

    Always make sure lines belonging to an if, elif, or else block are indented at the same level.

  2. Assignment vs. Comparison (= vs. ==): This is a classic!

    • = is used for assigning a value to a variable (e.g., x = 5).
    • == is used for comparing if two values are equal (e.g., if x == 5:). If you accidentally use = in an if condition, Python will often interpret it as a truthy or falsy value and not give you the comparison you intended, leading to subtle bugs.
  3. Forgetting Colons: Every if, elif, and else line must end with a colon :. If you forget it, you’ll get a SyntaxError.

    # BAD CODE - will cause SyntaxError
    if temperature > 0
        print("Positive")
    

If you encounter an error, don’t panic! Read the error message carefully. Python tries its best to tell you what went wrong and where. Look for the line number mentioned in the traceback.

Summary: Your Program, Now a Decision-Maker!

Congratulations! You’ve just unlocked one of the most fundamental and powerful concepts in programming: control flow. Your programs are no longer just straight lines; they can now branch, adapt, and respond intelligently to different conditions.

Here’s a quick recap of what we covered:

  • if statements execute a block of code only if a condition is True.
  • else statements provide an alternative block to execute if the if (and any elif) conditions are False.
  • elif statements allow you to check multiple conditions sequentially, executing the first one that is True.
  • Comparison operators (==, !=, <, >, <=, >=) are used to create conditions that evaluate to True or False.
  • Logical operators (and, or, not) help you combine or negate conditions for more complex decision-making.
  • Indentation is critical in Python to define code blocks.

You’re well on your way to building truly interactive and smart applications. In the next chapter, we’ll continue to explore how to make your programs even more dynamic by learning about loops, which allow your code to repeat actions multiple times. Get ready to automate!