Search⌘ K
AI Features

Make Decisions

Explore how to write Python programs that make decisions using if, else, and elif statements. Learn about the importance of indentation and how to use comparison operators to control program flow.

Now it’s time to teach Python how to make decisions like you do every day.


In this lesson, we’ll learn how to write programs that react to different conditions using if, else, and elif.


Try this:

Python
age = 18
if age >= 18:
print("You're an adult!")

Python checked the condition and ran the code only if it was true.

Note: In Python, a colon (:) starts a block of code—like after an if statement. The indentationIndentation means adding spaces at the beginning of a line of code. Most often, we use 4 spaces for indentation. (the space before the next line) tells Python which lines belong to that block

Unlike some other languages, Python uses indentation to group code—it’s how it knows what belongs together.

Without the colon or correct indentation, Python will show an error.


Your turn: Make a choice

Try changing the value of age to something below 18. What happens?

Add an else to handle both cases:

Python
age = 16
if age >= 18:
print("You're an adult!")
else:
print("You're a minor!")

Now the program makes a decision based on the condition.


How it works?

  • if checks a condition.

  • If it’s True, it runs the code inside the block (indented lines).

  • else runs if the condition is False.

Execution of code depends on the condition being met
1 / 12
Execution of code depends on the condition being met

You can also check multiple conditions using elif (short for "else if"):

Python
hour = 14
if hour < 12:
print("Good morning!")
elif hour < 18:
print("Good afternoon!")
else:
print("Good evening!")

Try changing hour to see different messages.


Common comparison operators

Use these in your if conditions:

  • ==—equal to

  • !=—not equal to

  • >—greater than

  • <—less than

  • >=—greater than or equal to

  • <=—less than or equal to

Let’s look at the example below:

Python
temperature = 30
if temperature > 25:
print("It’s hot today!")

Note: In Python, = is used to assign a value to a variable.
For example, temperature = 18 means “store the value 18 in the variable called temperature.”

But == is used to check if two things are equal.
For example, temperature == 18 asks “Is the value of temperature equal to 18?”

They may look similar, but they do very different jobs!