Python provides the if..elif
statement in order to check multiple conditions. We can specify the first condition with the if statement and other conditions with the elif statement. Also, we can add extra elif statements in order to check more conditions.
if Only Statement,
We can use only the if statement like below. We only check a single condition and if this condition is true the related code block is executed. The syntax of the single if statement is like below.
if CONDITION
CODE_BLOCK
In the following example, we check if the age is over 18.
age = 21
if age>18
print("Age is over 18")
if..elif Statement
We can use the if..elif
statement in order to check two conditions. The first condition is checked with the if statement. The second condition is checked with the elif statement. The syntax of the if..elif statement is like below.
if CONDITION1
CODE_BLOCK1
elif CONDITION2
CODE_BLOCK2
In the following example, we check the first condition with the if statement. We check if the age is over 18. With the elif statement, we check if the age is lower than 65.
age = 21
if age>18
print("Age is over 18")
elif age>65
print("Age is between 18 and 65")
if..elif..elif Multiple Statements
We can use multiple elif statements with the if statement. The syntax is like below.
if CONDITION1
CODE_BLOCK1
elif CONDITION2
CODE_BLOCK2
elif CONDITION3
CODE_BLOCK3
In the following example, we check 3 conditions for the age variable by using if..else statement.
age = 21
if age>18
print("Age is over 18")
elif age>65
print("Age is between 18 and 65")
elif age>80
print("Age is over 80")