Making Decisions with If Statements

Learn how to make your programs act differently based on different conditions using if, elif, and else.

~22 min Beginner

What is an if statement?

Most programs need to make decisions. If the user entered the right password, let them in. If the score is above 90, print "Excellent". If the temperature is above 30, say it is hot. The if statement is how you tell Python: check this condition, and only do something when it is true.

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

The condition is age >= 18. A condition is a question that has only two possible answers, True or False. If the answer is true, the indented code below it runs. If it is false, Python skips that code and nothing happens.

age = 12
if age >= 18:
    print("You are an adult.")
print("This line always runs.")
This line always runs.

The last line is not indented, so it does not belong to the if. It runs no matter what. Notice also the colon : at the end of the if line. It is required, and forgetting it is a very common mistake.

Indentation is not optional

In many languages, indentation (the spaces at the start of a line) is only for looks. In Python it is part of the language. It tells Python which lines belong to the if statement. Use 4 spaces. If you forget, Python gives an error.

# Correct
if age >= 18:
    print("Adult")   # 4 spaces before print

# Wrong: causes IndentationError
if age >= 18:
print("Adult")       # no indentation

A group of indented lines is called a block. Every line in a block must use the same number of spaces. Mixing different amounts causes an error as well.

if age >= 18:
    print("Adult")
    print("You can vote.")     # same block, same indentation
print("Done")                  # back to the left, outside the block

Good editors insert 4 spaces when you press the Tab key, so you rarely have to count. Pick spaces and stick with them. Do not mix tabs and spaces in one file.

else and elif

Add an else block to handle the case when the condition is false:

age = 15
if age >= 18:
    print("You can vote.")
else:
    print("You cannot vote yet.")
You cannot vote yet.

Think of else as "in every other case". Exactly one of the two blocks will run. It has no condition of its own.

When you have more than two possibilities, use elif, which means "else if". You can have as many elif blocks as you need:

score = 72

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Your grade is {grade}.")
Your grade is C.

Python checks each condition from top to bottom. As soon as one condition is true, it runs that block and skips all the rest. That is why the order matters. A score of 95 is also above 80, but the first test, >= 90, catches it first.

Comparison operators

These operators compare two values and give back True or False:

x = 10

print(x == 10)  # Equal to:                 True
print(x != 5)   # Not equal to:             True
print(x > 5)    # Greater than:             True
print(x >= 10)  # Greater than or equal to: True
print(x <= 9)   # Less than or equal to:    False

Notice that checking equality uses two equals signs ==, not one. One equals sign = assigns a value. Two equals signs == compare two values. Mixing these up is one of the most common mistakes in programming.

x = 5       # put 5 into x
x == 5      # ask: is x equal to 5? gives True

You can compare text too. "apple" == "apple" is True, but capitals count, so "Apple" == "apple" is False. And Python lets you chain comparisons the way you would write them in math:

age = 25
print(18 <= age <= 30)   # True, age is between 18 and 30

Combining with and, or, not

Often one test is not enough. Use and, or and not to combine conditions:

age = 25
has_ticket = True

# Both conditions must be true
if age >= 18 and has_ticket:
    print("You can enter.")

# At least one condition must be true
if age < 12 or age > 65:
    print("You get a discount.")

# Reverse a condition
if not has_ticket:
    print("You need a ticket.")

Here is how each one behaves:

  • and: true only when both sides are true
  • or: true when at least one side is true
  • not: flips true to false and false to true
print(True and False)   # False
print(True or False)    # True
print(not True)         # False

When you mix them, not is checked first, then and, then or. Use brackets when it looks confusing, for example if (a or b) and c:.

Nested ifs and a real example

You can put an if inside another if. This is called nesting. Be careful not to nest too deeply, because it makes code hard to read:

is_logged_in = True
is_admin = False

if is_logged_in:
    print("Welcome back!")
    if is_admin:
        print("You have admin access.")
    else:
        print("You have regular user access.")
else:
    print("Please log in.")

Now a practical example that reads input and picks a message:

temperature = float(input("What is the temperature outside? "))

if temperature >= 35:
    print("It is very hot. Stay hydrated.")
elif temperature >= 25:
    print("It is warm and nice.")
elif temperature >= 15:
    print("It is mild. A light jacket might help.")
elif temperature >= 5:
    print("It is cold. Wear a coat.")
else:
    print("It is freezing. Stay warm!")

If the user types 20, the first two tests fail and the third one passes, so the program prints the mild message. The remaining branches are skipped.

True and false values

A condition does not have to be a comparison. Python can treat any value as true or false. Empty or zero values count as false, and almost everything else counts as true.

  • False values: 0, 0.0, "" (empty text), [] (empty list), {} (empty dictionary), None
  • True values: any other number, any text with at least one character, any list with items
name = ""
if name:
    print("Hello,", name)
else:
    print("You did not type a name.")
You did not type a name.

This is a short way to check if the user typed anything. It is also how you test whether a list has items: if items:.

The keyword in also makes a clean condition:

vowels = "aeiou"
letter = "e"
if letter in vowels:
    print("It is a vowel.")

And for a simple two way choice, Python has a one line form called a conditional expression:

age = 20
status = "adult" if age >= 18 else "minor"
print(status)   # adult

Common mistakes

  • Using = instead of ==. if x = 5: is a syntax error. Use == to compare.
  • Forgetting the colon. Every if, elif and else line ends with :.
  • Wrong indentation. The body must be indented and consistent.
  • Wrong order of elif. Put the most specific test first, or an earlier broad test may catch everything.
  • Comparing text and numbers. "5" == 5 is False. Convert input first with int().
score = 95
if score >= 60:
    print("Pass")        # this catches 95 first
elif score >= 90:
    print("Excellent")   # never reached

Fix that by testing >= 90 first. Whenever your branches seem to be ignored, look at the order.

Key takeaways

  • if runs a block only when its condition is True
  • Indent the block with 4 spaces and end the if line with a colon
  • else handles everything else, and elif adds more choices. Only the first matching branch runs
  • Compare with ==, !=, >, >=, <, <=. One = assigns, two == compare
  • Combine tests with and, or and not
  • Empty values like "", 0 and [] count as false
Sign up to track your progress Mark lessons as read and pick up where you left off Sign up free to unlock this practice Your first practice lesson is free to try. Create an account to unlock the rest and save your progress