← all tracks/Intro to Python

Making Decisions: If & Else

Making Decisions: If & Else 🚦

So far your code always does the same thing every time. But real programs need to make decisions — do one thing if something is true, and something else if it isn't.

if age >= 18:
    print("You can vote!")
else:
    print("Not yet!")

The line with if checks a condition. If it's True, Python runs the indented lines right under it. If it's False, Python skips down to else and runs those lines instead.

Got more than two options? Use elif ("else if") to check more conditions, in order, top to bottom:

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"

Python checks each condition in order and stops at the first one that's True — so put your most specific conditions first!

You can also combine conditions with these boolean operators:

  • and — both sides must be True
  • or — at least one side must be True
  • not — flips True to False, and False to True

Careful with indentation — the lines inside an if/elif/else block must line up with the same spacing, or Python won't know they belong together!

# problems