5  Conditions and Flow

In This Chapter

Control flow, indentation, evaluating Boolean logic.

So far, our programs have been predictable. The computer starts at line 1, executes it, moves to line 2, and goes straight down to the bottom. Sure we can input something, but the computer will always do the same thing. But games and other software usually need to react. A video game doesn’t play the exact same way every time; it reacts to what the player does.

In this chapter, we are going to learn how to make the computer make decisions. We will cover:

  • Control Flow: Breaking the top-to-bottom rule.
  • Conditional Statements: Using if to skip lines of code.
  • Code Blocks & Indentation: Python’s strict formatting rules.
  • Branching Paths: Using else and elif to create multiple choices.
  • Nested Logic: Putting if statements inside of if statements.
  • Game State: Using variables to remember the past.
  • The Project: Building a branching Choose Your Own Adventure game.

5.1 Changing the Flow

If you are playing a game and you walk up to a locked door, the game has to make a decision:

  • Does the player have the key?
  • If True, open the door.
  • If False, the door stays shut.

This is called Control Flow. We are controlling which lines of code the computer is allowed to read based on the current situation. We do this using Conditional Statements.

5.2 Making Decisions with if

The most basic conditional statement is the if statement.

An if statement tells the computer: “Evaluate this expression. If it is True, run the next block of code. If it is False, skip it completely.”

Open a new File Editor window and type this script:

player_health = 0

if player_health == 0:
    print("You have died!")
    print("GAME OVER")

If you run this code, the computer sees that player_health == 0 evaluates to True, so it runs the two print statements inside the if statement.

But what if you change the top line to player_health = 100 and run it again? The computer evaluates 100 == 0, gets False, and completely skips the “GAME OVER” messages!

5.3 Code Blocks and Strict Indentation

Notice two extremely important things about the if statement above:

  1. The if statement ends with a colon (:).
  2. The print statements underneath it are pushed to the right.

In Python, pushing code to the right is called Indentation. An indented chunk of code is called a Block. Python uses indentation to know exactly which lines belong to the if statement, and which lines belong to the main program.

Here are the strict rules of indentation:

  • The Colon: Whenever you end a line with a colon (:), the next line must be indented.
  • Four Spaces: The official rule for Python is to indent using exactly four spaces. (You can also press the Tab key, but never mix tabs and spaces in the same file or Python will get confused). When you press Tab in IDLE, it will automatically substitute 4 spaces for you.
  • Ending the Block: To tell Python that the if statement is over, you simply stop indenting. The next line of code that is aligned to the far left margin is no longer controlled by the if statement.

The IndentationError

If you forget to indent after a colon, or if you indent the wrong number of spaces, your program will instantly crash.

if player_health == 0:
print("GAME OVER")

Crash! IndentationError: expected an indented block. Python saw the colon, looked at the next line, and panicked because it wasn’t pushed to the right.

Tip: IDLE is actually very smart. If you type a colon and hit ENTER, IDLE will automatically indent the next line for you!

Multiline Statements in the Shell

If you try to write an if statement in the IDLE Interactive Shell (the REPL), you will notice something different. When you type the colon and hit ENTER, the >>> prompt changes to ... (three dots).

The ... means the shell recognizes you are writing a block of code and is waiting for you to finish. To execute the block, you must hit ENTER on a completely blank line to tell the shell you are done.

5.4 The Default Choice: else

What if we want one thing to happen if a condition is True, but a completely different thing to happen if it is False? We use an else statement.

An else statement acts as a default catch-all. It does not ask a question, and it does not use a comparison operator. It simply says, “If the if statement above me was False, run this code instead.”

has_key = False

if has_key == True:
    print("You unlock the door and escape!")
else:
    print("The door is locked. You are trapped.")

Because has_key is False, the computer skips the if block, hits the else block, and prints “The door is locked.”

5.5 Multiple Paths: elif

Sometimes there are more than two possibilities. If we ask the user to type a direction, they might type “left”, “right”, or “forward”. To handle multiple specific choices, we use elif (which stands for “else if”).

choice = input("Do you go left, right, or forward? ")

if choice == "left":
    print("You found a treasure chest!")
elif choice == "right":
    print("You fell in a pit!")
elif choice == "forward":
    print("You ran into a wall.")
else:
    print("I do not understand that direction.")

When you chain if, elif, and else together, they act as a single, connected structure.

  1. The computer checks the if statement. If it is True, it runs the code and skips the rest of the chain completely.
  2. If it is False, it moves down and checks the first elif.
  3. If it hits an elif statement that is True it will run that code block and then skip the rest completely.
  4. If all the if and elif statements are False, it defaults to the else block at the bottom.

When to Use Elif

Why do we need elif? Couldn’t we just write a bunch of if statements?”

Look at this grading script that uses two if statements:

score = 90

if score > 50:
    print("You passed the test!")
    
if score > 80:
    print("You got an A!")

If you run this, it prints both messages! That is because they are two completely independent if statements. The computer checks the first one (True), prints the message, and then moves on to check the second one (also True), and prints the second message.

If you only want one outcome to happen, you must chain them together using elif. Once an if/elif chain finds a True condition, it safely ignores all the others.

score = 90

if score > 90:
    print("You got an A!")
elif score > 80:
    print("You got a B!")
elif score > 65:
    print("You passed!")
else:
    print("You failed!")

This works because as soon as one of the if or elif statements is True, the rest is skipped over. If none of them are True, then the else statement’s block will execute.

5.6 Nested if Statements

You are not limited to basic blocks. You can actually put an if statement inside another if statement! This is called Nesting.

To do this, you just follow the indentation rules. If the first block is indented four spaces, the nested block is indented eight spaces!

Let’s look at a step-by-step breakdown of a player trying to unlock a secret treasure in a video game:

player_level = 12
has_boss_key = True

# Level 1 check
if player_level >= 10:
    print("You are high enough level to enter the secret castle.")
    
    # Level 2 check
    if has_boss_key == True:
        print("You use the boss key to open the golden treasure chest!")
    else:
        print("You are in the castle, but the chest remains locked.")
        
else:
    print("You are too low level. Come back when you are stronger.")

What is happening here?

  1. The computer checks player_level >= 10. Because 12 is greater than 10, this is True.
  2. The computer enters the first block (4 spaces in) and prints “You are high enough level…”.
  3. Inside that block, it encounters a second if statement. It checks has_boss_key == True.
  4. Because this is also True, it enters the nested block (8 spaces in) and prints “You use the boss key to open the golden treasure chest!”.

If player_level was 5, the very first check would be False. The computer would skip the entire inner block and jump straight to the else statement at the bottom!

Try changing the variables and seeing what the outcome is.

5.7 Game State: Remembering the Past

In a real game, choices you make in level 1 should affect what happens in level 5. We manage this using Game State.

Game State simply means using variables at the very top of your script to keep track of the player’s inventory, health, or accomplishments. Usually, these are Booleans.

For example, we might start a game with has_sword = False. If the player finds the sword in a tunnel, we change the variable to has_sword = True. Later on, when they fight a monster, we can check that exact variable to see if they survive!

5.8 The Project: The Dark Cave

We are going to build a text-based “Choose Your Own Adventure” game. This project will combine input(), print(), if/elif/else statements, and Game State into a real, playable narrative.

Notice how we use code comments (#) to divide our script into clean, readable sections.

Type this into a new file and run it!

# THE DARK CAVE 

# 1. Setup the Game State
has_sword = False

print("Welcome to the Dark Cave.")
print("You stand in a damp stone room. Two tunnels lead deeper into the earth.")

# 2. The First Choice
choice1 = input("Do you go 'left' or 'right'? ").strip().lower()

if choice1 == "left":
    print("\nYou walk down the left tunnel. It is a dead end.")
    print("But you find a shiny steel sword on the ground!")
    # Update the game state!
    has_sword = True
elif choice1 == "right":
    print("\nYou walk down the right tunnel. It is very dark.")
    print("You step carefully to avoid tripping.")
else:
    print("\nYou stand around confused. Finally, you just walk left.")
    print("You find a shiny steel sword on the ground!")
    has_sword = True

# 3. The Second Room
print("\nYou move forward into the next cavern.")
print("A giant spider drops from the ceiling!")

# 4. Checking the Game State
if has_sword == True:
    print("You swing your shiny steel sword!")
    print("The spider flees into the shadows. You survive!")
else:
    print("You have no weapon to defend yourself!")
    print("The spider wraps you in a web. GAME OVER.")

When you run this game, play it twice. Type left the first time, and right the second time. Notice how the computer skips entire sections of code depending on the state of your Boolean variables!

Challenge: Expand the Caves

Your assignment is to take the “Dark Cave” code you just wrote and make the game longer and more dangerous.

The Goal: Add a third room, a new item, and a deadly trap that kills the player if they don’t have the new item.

  • Step 1: Add a new Game State variable at the top (like has_key = False).
  • Step 2: Modify the existing choices so the player can find this new item.
  • Step 3: At the bottom of the script, create a “Third Room” that asks the player another question (input), and uses a nested if/else statement to check if they have the item to survive!