Python · March 29, 2025
Before diving into the world of Python if statement, let us understand conditional statements like if statement are important. If we want to write useful applications, we need to control how the program executes based on different conditions. To achieve this, we need instructions that check conditions and adjust the program’s behavior accordingly.
The simplest conditional statement is the if statement. The if statement is made up of a header line and and a body. The header starts with the keyword if. It is followed by a Boolean expression called condition. It always end with a colon (:). Not adding colon at the end will give an error.
a = 150
if (a > 100):
print("a is greater then 100")
The first line assigns the value 150 to the variable a.
So far, nothing new. When you reach the second line, Python behaves differently. The if statement checks whether the condition is true. If condition is true, the code after the colon (:) will execute. If the condition is false, nothing happens.
Note: You must have noticed indentation (or empty spaces) before print statement, when it is written after if statement’s header line which end which ends with a colon. To read more about indentation and blocks in python, click here.
Note: The parentheses around the condition in if (a > 100) are optional in Python, though they improve readability.
Execute the program and it will display:
a is greater then 100
Now, repeat the same process but set a = 20 in the first line. This time, Python will not display anything.
In the next statement, we will learn about if statement.
In the next article, we will learn about Indentation and Blocks in Python.