If, else & decisions · About 8 minutes

Choose your own adventure

The big little idea

An if statement lets a program choose. If its condition is True, it runs the indented instructions. Otherwise, an else block can do something different.

weather = "rainy"
if weather == "rainy":
    print("Pack a raincoat!")
else:
    print("Grab your sun hat!")

Use == to compare values and = to assign them. Other comparisons include > (greater than), < (less than), and >= (at least). The colon and indentation tell Python which instructions belong to each choice.

Predict, then try: read the example from top to bottom. What do you think it will print? Copy it into the editor below to test your prediction.

Your turn, code explorer.

The treasure door needs at least 3 keys. Fix the condition so 3 keys prints Door unlocked! Try changing keys to 2 afterward to explore the other path.

Door unlocked!
my_adventure.pyPython · in your browser

Edit the code. Then run it. Ctrl / ⌘ + Enter also works.

OutputYOUR IDEAS, ALIVE
Your program’s output will appear here.

Ready when you are. ✦

The first run loads Python. This can take a moment.

Program input For programs that use input()

Add answers before you run. Each input() reads the next line. Use made-up names and details.

Real Python, powered by Pyodide. Standard-library programs work here; desktop windows, turtle graphics, and package installation are not supported by this editor. Programs stop after 10 seconds of execution.

Back to the starting code?

This replaces your edits for this activity. Download your code first if you want to keep it.

A little hint, please

At least 3 includes 3 itself. Use >= instead of >.

Show one possible solution

There can be more than one way. Read this version, then try writing it yourself.

keys = 3
if keys >= 3:
    print("Door unlocked!")
else:
    print("Find more keys!")
Pack this idea for later: Conditions turn one set of instructions into different possible paths.