Conditional statements are used to check and compare multiple conditions and values. Python provides different conditionals in order to make decisions in the applications and follow different execution paths, methods, and logic.
The comparison statements are used to check single or multiple conditions.
|!=||Not Equal Statement|
|<||Less Than Statement|
|<=||Less Than or Equal Statement|
|>||Greater Than Statement|
|>=||Greater Than or Equal Statement|
|or||Or Logic Statement|
|and||And Logic Statement|
if Conditional Statement
The if conditional statement is used to check single case where single or multiple conditions can be specified. If the specified case is true the if conditional statement code block will be executed, if not the if conditional statement will not executed and next lines will be executed.
age = 20 if (age>18): print("Age is over 18")
In the following example we will check if given counts are the same with the single if conditional.
a_count = 10 b_count = 10 c_count = 11 if(a_count == b_count): print("A and B count are equal") if(a_count == c_count): print("A and C count are equal")
if..else Conditional Statement
The if..else conditional statement is used to check two cases for multiple conditions. First, the if case will be checked, and if it is not true the else code block will be executed. The syntax of the if..else conditional statement is like below.
if CONDTION: IF_BLOCK else: ELSE_BLOCK
- CONDITION is the condition which will be checked single or multiple conditions.
- IF_BLOCK will be executed if CONDITION is true.
- ELSE_BLOCK executed if CONDITION if false or not true.
If the following example we will check the age if it is equal or over 18.
age = 20 if (age>=18): print("Age is over 18") else: print("Age is less than 18")
if..elif..else Conditional Statement
The most detailed and multi case conditional statement is the if..elif.else conditional statement where the elif can be repeated muıltiple times between if and else.This will create more cases if we need. The if..elif..else conditional statement syntax is like below.
if CONDITION1: CODE_BLOCK1 elif CONDITION2: CODE_BLOCK2 ... else: CODE_BLOCKn
- CONDITION1 will be checked first, if it is true the CODE_BLOCK1 will be executed if not the execution will jump into the following elif.
- CONDITION2 will be checked if it is true if it is true CODE_BLOCK2 will be executed if not the execution will jump next statement. Multiple elif can be specified for multiple cases.
- CODE_BLOCKn is executed when none of the if and elif conditions are true.
In the following example we will check if the age is greater than or equal 18, greater than or equal 12 or non of them.
age = 15 if(age>=18): print("Age is over 18") elif( age >= 12): print("Age is between 12 and 18") else: print("Age is less than 12")
The output will be like below.
Age is between 12 and 18