Conditional Statements in Python

Conditional statements allow you to run your program on certain conditions. They are compound statements which may contain one or more comparison statements.

Conditional Statements in Python are as follows:

  1. if statement
  2. if-else statement
  3. elif statement
  4. Nested if statement

 The conditions in the comparison statements are evaluated as true or false, which regulates the execution of the upcoming statements in the program.

While execution of the program, you can jump a statement(s) using conditional statements. The conditional statements contain a condition and a block of instructions associated with that condition.

This block of instructions is executed only if the condition turns out to be true, else it is skipped by the interpreter. The conditions to be evaluated may be arithmetic, logical or boolean.

1. if statement

The if statement in python works the same way as in any other language. It consists of the if keyword followed by a condition and the executable block of instructions associated with the condition.

If the condition evaluates to be true, the block of instructions will get executed and an output will be generated, otherwise, the interpreter will jump to the instruction next to the if-block.

Syntax:
if (condition) :
     if-block instructions

The syntax of if-statement in Python is quite different from other languages.

  • A colon is used after the condition of if-statement, which indicates the beginning of the if-block.
  • To create the block of instructions associated with if-statement, indentation(blank space) is used instead of curly braces.
  • Parentheses around the condition are optional.

Flow the control:

Example:

strength = int(input("Please enter the number of students: "))
if (strength < 50):
    print("The strength of the class is too short for the seminar.")
print("Thankyou!")

Output:

Please enter the number of students: 32
The strength of the class is too short for the seminar.
Thankyou!

Please enter the number of students: 90
Thankyou!

Explanation:

  • In the above program, a variable strength is defined which takes an integer value from the user. As the user enters the value, the variable strength starts referring to the value.
  • In the next line, if-statement evaluates the condition ie 'strength < 50'. Since the condition becomes true, the if-block is executed.
  • After the complete execution of if-block statements, the interpreter executes the instruction next to the if-block.

2. if-else statement

if-else statement is just like if-statement. In addition, it provides one more block of code which is executed when the if-condition becomes false.

Syntax:
if (condition) :
       if-block instructions
else :
       else-block instructions

Flow of control:

Example:

strength = int(input("Please enter the number of students:"))
if (strength < 50):
    print("The strength of the class is too short for the seminar.")
else :
    print("The strength is good. Get ready for the seminar tomorrow.")
print("Thankyou!")

Output:

Please enter the number of students: 90
The strength is good. Get ready for the seminar tomorrow.
Thankyou!

Explanation:

In this example, we have modified the previous program and added the else block.
When the user enters 90, the condition becomes false and the interpreter jumps to the else-block statement and executes it and finally exits the if-else statement.

3. elif statement

With elif-statement, you can pass a value through multiple evaluations. By multiple evaluation, it means that if one condition becomes false, another condition will be evaluated and so on. At last, if no condition evaluates to true, the else-block statements get executed.

In Python, switch-case statement is not available. Instead, you can use elif-statement where else-block acts as the default case of the switch statement.

Syntax:
if (condition) :
    if-block instructions
elif (condition) :
    elif-block instructions
.
.
else :
    else-block instructions

Flow of control:

Example:

print("--Menu--")
print("1. Coffee")
print("2. Tea")
print("3. Juice")
print("4. Sandwich")
item=int(input("Please enter the number of the item you want:"))
if (item==1):
   print("Please pay Rs. 50/- for Coffee.")
elif(item==2):
   print("Please pay Rs. 40/- for Tea.")
elif(item==3):
   print("Please pay Rs. 70/- for Juice.")
elif(item==4):
   print("Please pay Rs. 80/- for Sandwich.")
else:
   print("Incorrect input.")

Output:

--Menu--
1. Coffee
2. Tea
3. Juice
4. Sandwich
Please enter the number of the item you want:3
Please pay Rs. 70/- for Juice.

--Menu--
1. Coffee
2. Tea
3. Juice
4. Sandwich
Please enter the number of the item you want:5
Incorrect input.

--Menu--
1. Coffee
2. Tea
3. Juice
4. Sandwich
Please enter the number of the item you want:1
Please pay Rs. 50/- for Coffee.

Explanation:
This program displays the payable amount of different products from the menu.

  • A menu is printed using print() function. A variable item is defined which takes an integer value from the user.
  • In the next line, the if-statement tests the value of the variable item for 1 (item==1). If the condition evaluates to true, the if-block is executed, otherwise the control jumps to elif block.
  • Again, the elif statement tests the value for 2. If the result of the test is true, elif-block is executed, otherwise, the control goes to the next elif statement and so on.
  • At last, if no if/elif condition is satisfied by the value of the variable item, the else-block is executed.

4. Nested if statement

Python allows you to use nested if statements i.e an if statement in the body of another if statement. Due to the absence of curly braces in python syntax, it becomes very complex to identify the depth of nesting of the statements which may cause you to make a syntax error.

Syntax:
if (condition) :
      if(condition) :
            instructions
      else :
            instructions
else :
      instructions

Flow of control:

Example:

stu1=int(input("Enter the age of student 1= "))
stu2=int(input("Enter the age of student 2= "))
stu3=int(input("Enter the age of student 3= "))
if (stu1>stu2): #outer if-statement
    if(stu1>stu3): 
        print("Student 1 is eldest.")
    else: 
        print("Student 3 is eldest.")
else: #outer else-statement
    if(stu2>stu3):
        print("Student 2 is eldest.")
    else:
        print("Student 3 is eldest.")

Output:

Enter the age of student 1= 16
Enter the age of student 2= 18
Enter the age of student 3= 14
Student 2 is eldest.

Explanation:

  • In the above program, three variables are defined which take input from the user.
  • You can clearly see the nesting of if-statement from the next line.
    Here, the condition of the outer if-statement(stu1>stu2) becomes false as per the input provided by the user (16>18 is false). Therefore the control skips the if-block and goes to the else-block.
  • Again, in the else-block, a nested if-statement is encountered with condition (stu2>stu3) which evaluates to true (18>14). Thus, the control enters the inner if-block and executes the instruction which prints a message on the output terminal saying 'Student 2 is eldest.'