The if statement in Python is the simplest building block for decision-making, running a block of code only when a condition holds true.
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.
The condition after if doesn’t have to be an explicit comparison like a > 100. Python can place practically any value directly after if, because every value in the language carries an inherent truth value even when it isn’t written as a Boolean expression at all. The number 0, in any numeric form (0, 0.0), counts as false, and so do an empty string (""), an empty list ([]), and None; virtually everything else – a non-zero number, a non-empty string, a non-empty list – counts as true. This is why experienced Python code often reads if not name: to check whether a string is empty, rather than the more explicit if name == "":. Both do exactly the same thing, but the first is considered more idiomatic Python once you’re comfortable with how the language evaluates truthiness on its own.
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.
No Comments