Python Control Flow: if...else Statements
- Pulkit Sahu
- Jul 31
- 2 min read
The if... else statement is a powerful feature in Python that allows the computer to make decisions based on conditions.
Observe:
If I am 25 years old, I will purchase a car.
Else, I will keep studying.

There is a condition involved: if I am 25 or older, then I’ll buy a car. This condition is often referred to as a Boolean expression in Python. You can represent it as:
age >= 25
Here, we defined age as a variable whose value is 25 or more. >= (greater than or equal to) is called a comparison operator. Boolean expressions evaluate to either True or False. In Python, we use if...else statements to check whether a condition is true. Based on that, we can perform the action we want. Let us go through them one by one.
#1: Python if Statement
In Python, we can make an if statement or clause like this:
if boolean_expression:
do something
We start with the if keyword, then write the condition (boolean_expression) we want to check. After that, we add a colon :. The next line should be indented (usually 4 spaces) and contains what we want the program to do—like printing something. This indented part is called a block.
Let us try:
age = 25
if age >= 25:
print("I would purchase a car.")
Try in this notebook! Click on Python (Pyodide) to start. Use Ctrl + Enter in Windows or Shift + Return on Mac to run the codes.
#2: Python else Statement
If the prior conditions are not true, we can simply use else. No Boolean expression is needed.
age = 25
if age >= 25:
print("I would purchase a car.")
else:
print("I will keep studying.")
Indentation is highly important in Python. In practice, we usually use 4 spaces or a single tab. A group of indented lines is called a block.
#3: Python elif Statement
We can add another Boolean expression using elif (else if) to check an additional condition. The syntax is:
if bool1:
do first thing
elif bool2:
do second thing
Example:
x = 1
y = -2
if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x is equal to y")
For example, if the first Boolean expression x < y is True, the first print statement runs.
If not, Python checks if x > y is True. If so, it runs the second print statement. If neither is true, the else clause executes, meaning x == y.
Other Boolean operators:
> greater than
< less than
== equal to
>= greater than or equal to
<= less than or equal to
!= not equal to.
We just learned how powerful if...else statements are in Python, as they help us or computers make decisions. Think of a large number of conditions to be checked and actions to be taken based on the correct or true condition. In this case, if...else plays an important role. In the next post, we will learn more about loops—or automatic things—in Python.
Comments