Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Python If elif else | elif Statement, Example

If elif else in Python is a multi-way decision control Statement, which is a combination of if, else if, and else statements.

When we need to choose one of several possible alternatives, we use Elif statement along with if statement.

In Python, the keyword elif represents an else-if statement and is useful to avoid excessive indentation.

It allows the programmer to check multiple conditions/expressions for true value and executes a set of code as soon as one of the conditions evaluates to true. Like else, elif statement is also an optional.

Syntax of If elif else ladder in Python


The general syntax for if elif else ladder statements in Python are as follows:

if condition-1:
     if block # It will execute if condition-1 is true.
elif condition-2:
     elif block # It will execute if condition-2 is true.
elif condition-3: 
     elif block # It will execute if condition-3 is true.
. . . . .
. . . . .
elif condition-N:
     elif block # It will execute if condition-N is true.
else:
     else block # It will execute if none of the above conditions is true.

In the above syntax, if, elif, and else are keywords. The condition-1, condition-2 . . . . . condition-N is the boolean expression that returns either true or false. It consists of any relational or logical operators.

There can be only one if statement, and one else statement, however an arbitrary Number of elif statements following if statement as per requirement.

The else statement must always come at last and take the default statement. Sometimes, it is also called if-elif-else ladder statement in Python.

Execution Process of If elif else Statement


Python interpreter evaluates a ladder of if-elif-else conditions from top to down. It executes if-elif-else decision control statement as follows:

a) In the if-elif-else structure, the interpreter first evaluates the “if condition-1” to true. If it comes true, Python executes the statements inside if block.

b) If Python “if condition-1” evaluates to false, it tests the “elif condition-2”. If the condition-2 is true, Python executes statements inside the elif block.

c) If the condition-1 and condition-2 are false, Python evaluates condition-3 to true. If it is true, then Python executes statements in the elif block. If it is false, Python checks for the next elif condition-4 and so on.

d) If none of the above conditions is true, the interpreter goes to execute statements inside the else block. If the condition of any ‘if’ or ‘elif’ returns true value, all ‘elif’ and ‘else’ will skip.

e) An if block can have as many elif blocks as needed, but it can have only one else block. However, it is not mandatory for else block to be present.

If else block is absent and none of the above conditions in the ladder are true, the interpreter goes to execute the next statement outside the ladder.

Flowchart Diagram of If-elif-else Ladder Statement


The flowchart diagram for if-elif-else ladder has shown in the below figure.

Python If elif else Example Program


Let’s take some example program based on the multi-way if-elif-else conditional control statement in Python.

Example 1:

Let’s write a Python program in which we will take a number from the user and check the number is zero, positive, or negative using if-elif-else ladder.

# This statement takes a number from the user and store it into a variable number.
number = int(input('Enter any number: '))
if number 
Output:
      Enter any number: 89
      89 is a positive number.

In the above example, we have entered a number 89 as a user. Python evaluates the if condition. Since the condition is not true, then Python does not execute statement in the if block and goes to check elif condition.

As the condition is not true, Python executes the default statement inside the else block and prints the message ’89 is a positive number’.


Example 2:

Let’s write a Python program to find the greater between the two numbers using if elif else ladder.

# These statements take two numbers from the user and store it into variables num1 and num2.
num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))

if num1 == num2:
    print('Numbers are equal.')
elif num1 > num2:
    print('First number is greater than second number.')
elif num1 
Output:
       Enter your first number: 25
       Enter your second number: 20
       First number is greater than second number.

Example 3:

Let’s write a program in Python to find the greatest among three numbers using if elif else statement.

# These statements take three numbers from the user and store it into variables n1, n2, and n3.
n1 = int(input('Enter your first number: '))
n2 = int(input('Enter your second number: '))
n3 = int(input('Enter your third number: '))

if n1 > n2 and n1 > n3:
    print(n1, 'is the greatest number among the three numbers.')
elif n2 > n1 and n2 > n3:
    print(n2, 'is the greatest number among the three numbers.')
else:
    print(n3, 'is the greatest number among the three numbers.')
Output:
      Enter your first number: 20
      Enter your second number: 15
      Enter your third number: 12
      20 is the greatest number among the three numbers.

Example 4:

Let’s write a program in Python to take the age of the user as input and find whether he is a child, adult, or senior on the basis of age. Using if-elif-else ladder statement.

age = int(input("Enter your age: "))
if age = 18 and age = 60:
    print("You are a senior")
else:
    print("You have entered an invalid age.")
Output:
      Enter your age: 68
      You are a senior

Example 5:

Let’s write the Python code to enter a character and check it is vowel or consonant.

# Take a single character as input from the user.
ch = input("Enter a single character: ")

if ch == 'a' or ch == 'A':
    print(ch, 'is a vowel.')
elif ch == 'e' or ch == 'E':
    print(ch, 'is a vowel.')
elif ch == 'i' or ch == 'I':
    print(ch, 'is a vowel.')
elif ch == 'o' or ch == 'O':
    print(ch, 'is a vowel.')
elif ch == 'u' or ch == 'U':
    print(ch, 'is a vowel.')
else:
    print(ch, 'is a consonant.')
Output:
      Enter a single character: A
      A is a vowel.

Example 6:

Let’s write the code in Python to check whether it is a Scalene triangle, Isosceles triangle, or Equilateral triangle. Note that:

  • Scalene triangle: A triangle that has no equal sides is a scalene triangle.
  • Isosceles triangle: A triangle that has two equal sides is an isosceles triangle.
  • Equilateral triangle: A triangle that has three equal sides is an equilateral triangle.
# Take the three sides of triangle as input from the user.
sideA = int(input("Enter the side A: "))
sideB = int(input("Enter the side B: "))
sideC = int(input("Enter the side C: "))

if((sideA != sideB) and (sideB !=sideC) and (sideC != sideA)):
    print('It is a scalene triangle.')
elif((sideA == sideB) and (sideB == sideC)):
    print('It is an equilateral triangle.')
else:
    print('It is an isosceles triangle.')
Output:
      Enter the side A: 5
      Enter the side B: 5
      Enter the side C: 2
      It is an isosceles triangle.

Some More Example Program for Best Practice


Example 7:

Let’s write code in Python to make a simple calculator to find addition, subtraction, multiplication, and division of two numbers. The math calculator menu is as follows:

  • Math Calculator Menu
  • – – – – – – – – – – – – – – – – – –
  • + => Addition
  • – => Subtraction
  • * => Multiplication
  • / => Division
print('Math Calculator Menu')
print(' - - - - - - - - - - ')
print('+ => Addition')
print('- => Subtraction')
print('* => Multiplication')
print('/ => Division')

opt = input('Enter an operator [+, -, *, or /]: ')
n1 = int(input("Enter your first number: "))
n2 = int(input("Enter your second number: "))

if(opt == '+'):
    sum = n1 + n2
    print('Sum of', n1, 'and', n2,'=', sum)
elif(opt == '-'):
    sub = n1 - n2
    print('Subtraction of', n1,'and', n2, '=', sub)
elif(opt == '*'):
    multiply = n1 * n2
    print('Multiplication of', n1,'and',n2,'=', multiply)
else:
    div = n1 / n2
    print('Division of', n1,'and', n2, '=', div)
Output:
      Math Calculator Menu
      - - - - - - - - - - 
      + => Addition
      - => Subtraction
      * => Multiplication
      / => Division
      Enter an operator [+, -, *, or /]: /
      Enter your first number: 50
      Enter your second number: 5
      Division of 50 and 5 = 10.0

Example 8:

Let’s create an application in Python to calculate percentage and grade according to percentage of marks of three subjects. Use Python if-elif-else ladder statement.

# Take marks of three subjects as input from the user.
eng = int(input('Enter the marks of English: '))
sci = int(input('Enter the marks of Science: '))
maths = int(input('Enter the marks of Mathematics: '))

total = eng + sci + maths
per = total / 3
print("Total marks obtained in three subjects: ",total)
print("Percentage: ", per)

if(per >= 90.0):
    print("Grade A")
elif(per >= 80.0):
    print("Grade B")
elif(per >= 70.0):
    print("Grade C")
elif(per >= 60.0):
    print("Grade D")
else:
    print("Grade F")
Output:
      Enter the marks of English: 89
      Enter the marks of Science: 90
      Enter the marks of Mathematics: 99
      Total marks obtained in three subjects:  278
      Percentage:  92.66666666666667
      Grade A

Since the percentage 92.66 is greater than 90, the first condition will be true. Therefore, Python will not go to check other conditions. As the percent 92.66 is greater than 90%, Grade A will display and the rest of the elif ladder will skip.


In this tutorial, you have learned about a multi-way decision control if elif else statement in Python with various example programs. Hope that you will have understood the basic points of if-elif-else ladder.
Thanks for reading!!!

The post Python If elif else | elif Statement, Example appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

Python If elif else | elif Statement, Example

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×