Conditionals (if, elif, else)

Lesson 5 of 16 • 10 XP

Keep your place in this quest

Log in or sign up for free to subscribe, follow lesson progress, and access more learning content.

Up until now, our programs have been like recipes — they always run the same way from top to bottom. But what if we want them to choose what to do based on certain conditions? That’s where conditionals come in.

Conditionals let your program make decisions.
Think of them as traffic lights for your code: if the light is green, go this way; if it’s red, go that way.


The Basic Structure

Here’s the simplest possible conditional:

if condition:
    # run this if condition is true

You put a condition (something that can be true or false) after the if keyword, followed by a colon. Then you indent the block of code that should run when the condition is true.

Example:

age = int(input("Your age: "))

if age >= 18:
    print("You are an adult.")

In this case:

  1. We ask the user’s age.
  2. We check if age is greater than or equal to 18.
  3. If it is, we print “You are an adult.”
  4. If it’s not, nothing happens (yet).
TIP: Conditions can use comparison operators like ==, !=, >, <, >=, and <=.

Adding More Conditions With elif and else

Sometimes you want to check multiple possibilities, not just one.

That’s what elif (short for “else if”) and else are for:

age = 20

if age < 18:
    print("You are a minor")
elif age < 60:
    print("You are an adult")
else:
    print("You are a senior")

Here’s the flow:

  • If the first if condition is true, run it and skip the rest.
  • If it’s false, check the elif condition.
  • If that is also false, run the else block (which is the “catch-all” for any other case).
Note: You can have multiple `elif` statements, but only one `if` and one `else` in the same chain.

Quick Exercise: Even or Odd?

Let’s make a tiny program that checks if a number is even or odd:

number = int(input("Enter a number: "))

if number % 2 == 0:
    print("Even number")
else:
    print("Odd number")

The magic here is in number % 2. The % operator gives us the remainder after division. Even numbers divide by 2 with no remainder (0), odd numbers leave 1.

Common Beginner Mistakes

Troubleshooting: • “IndentationError” → You didn’t indent the code under if, elif, or else properly. Use 4 spaces. • “SyntaxError: expected ':'” → You forgot the colon at the end of your if/elif/else line. • “NameError” → You used a variable in your condition before creating it.


By learning conditionals, you’ve unlocked the power of decision-making in your programs. Next, we’ll explore functions — a way to group and reuse code so you can build bigger, cleaner programs without repeating yourself.