If...Elif...Else...

Introduction:

  • Python supports logical conditions from mathematics:
    • Equals: a == b
    • Not Equals: a != b
    • Less than: a < b
    • Less than or equal to: a <= b
    • Greater than: a > b
    • Greater than or equal to: a >= b

Elif Statement:

  • The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition."

Syntax of Elif:

python
if boolean_expression_1:
    statement(s)
elif boolean_expression_2:
    statement(s)
elif boolean_expression_3:
    statement(s)
else:
    statement(s)
  • You can have as many elif statements as required.

Examples:

  1. Simple Elif Example:
    • Checking two conditions: a < b in if-condition and a > b in elif-condition.

      python
      a = 6
      b = 4
      
      if a < b:
          print(a, 'is less than', b)
      elif a > b:
          print(a, 'is greater than', b)
      else:
          print(a, 'equals', b)
      
    • Output: 6 is greater than 4
       
  2. Multiple Elif Blocks:
    • Writing multiple elif blocks in the if-elif ladder.

      python
      a = 2
      
      if a < 0:
          print(a, 'is negative')
      elif a == 0:
          print('its a 0')
      elif a > 0 and a < 5:
          print(a, 'is in (0.5)')
      else:
          print(a, 'equals or greater than 5')
      
    • Output: 2 is in (0.5)
       

Exercises:

  1. Elif Statement:
    • Write a program to check the grade of a student based on marks entered by the user.

      python
      marks = int(input("Enter marks: "))
      
      if marks >= 90:
          print("Grade: A")
      elif marks >= 80:
          print("Grade: B")
      elif marks >= 70:
          print("Grade: C")
      elif marks >= 60:
          print("Grade: D")
      else:
          print("Grade: F")
      
  2. Nested Elif:
    • Write a program to check if a number is positive, negative, or zero, and if positive, check if it is even or odd.

      python
      number = int(input("Enter a number: "))
      
      if number > 0:
          print("The number is positive.")
          if number % 2 == 0:
              print("The number is even.")
          else:
              print("The number is odd.")
      elif number == 0:
          print("The number is zero.")
      else:
          print("The number is negative.")
      

Summary:

  • Python elif statements are used to execute a continuous chain of conditional logic ladder. Practice writing elif statements to become proficient in using conditional logic in your programs