Python - Conditional Statements

Conditional statements helps you to make a decision based on certain conditions. If a certain condition is true, then a particular result happens. If the condition is false, then a different result happens.

In this tutorial, we will discuss the below conditional statements.

  • IF
  • ELSE
  • ELIF
  • Nested IF

IF Statement

We can use Python IF statement to justify one condition.
If the condition is true, then it runs the body of code in IF statement.

Example:

a = 100;
b = 50; 
if a > b:
    print(“a is greater than b”)

In the above example, the condition a > b is true; because we know that 100 ( a is 100) is greater than 50 (b is 50). So, it execute the content of the body and prints “a is greater than b”.

ELSE Statement

We can use Python ELSE statement to execute the statements when one condition is not true.
If the condition is true, then it runs the body of code in IF statement.
If the condition is false, then it runs the optional else part of the code.

Example:

a = 50;
b = 70; 
if a > b:
    print(“a is greater than b”)
else:
    print(“b is greater than a”)

In the above example, the condition a > b is not true then it goes to the else condition and execute the content of else body. So, it prints “b is greater than a”.

ELIF Statement


We can use Python ELIf statement to justify one or more conditions.
If the IF condition is true, then it runs the body of code in IF statement.
If the IF condition is false, then it goes to ELIF condition to check whether the condition is true or not.
If the ELIF condition is true, then it execute the body of the code in ELIF condition.
If the ELIF condition is false, the it execute the body of the code in ELSE condition.

Example:

a = 20;
b= 100;
c = 90;
if a > b:
    print(“a is greater than b”)
elif b > c:
    print(“b is greater than c”)
else:
    print(“c is greater than a and b)

In the above example, if a > b is not true then python checks ELIF condition to check wether it is true or not. If it is true, then it prints the content of the body in ELIF condition. If the condition is false, then it goes to ELSE condition and prints the “c is greater than a and b”.

Nested IF


We can use Python nested if statements when you need to check the condition inside another condition.

Example:

a = 10;
if( a > 5):
    if( a > 18):
        print(a, “is greater than 18”
    if(a < 18):
        print(a, “is lesser than 18”)

In the above example, outer IF condition (a > 5 ) is true the it go to check the inner IF conditions (a >18) and (a < 18). Here the condition (a < 18) is true, so it prints “ 10 is lesser than 18”.



Related Tutorials