When we want to execute a code block when the condition is true, decision making comes to the rescue. The if...elif...else statement is used in Python for decision making.
Decision making
Python if statement syntax
The following is the syntax for the if statement:
if test_expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the text expression is true. If the text expression is false, statement(s) isn't executed.
In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end. Let's look at an example:
a = 10
if a > 0:
print(a, "is a positive number.")
print("This statement is always printed.")
a = -10
if a > 0:
print(a, "is a positive number.")
Output:
10 is a positive number.
This statement is always printed.
Python if...else statement syntax
In this section, we are going to learn about the if..else statement. The else block will get executed only when the if condition is false. Refer to the following syntax:
if test expression:
if block
else:
else block
The if..else statement evaluates the test expression and will execute the body of if only when the test condition is true. If the condition is false, the body of else is executed. Indentation is used to separate the blocks. Refer to the following example:
a = 10
if a > 0:
print("Positive number")
else:
print("Negative number")
Output:
Positive number
Python if...elif...else statement
The elif statement checks multiple statements for a true value. Whenever the value evaluates to true, that code block gets executed. Refer to the following syntax:
if test expression:
if block statements
elif test expression:
elif block statements
else:
else block statements
elif is short for else if. It allows us to check for multiple expressions. If the condition written in the if statement is false, then it will check the condition of the next elif block, and so on. If all of the conditions are false, the body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the condition. The if block can have only one else block. But it can have multiple elif blocks. Let's take a look at an example:
a = 10
if a > 50:
print("a is greater than 50")
elif a == 10:
print("a is equal to 10")
else:
print("a is negative")
Output:
a is equal to 10