Home » Python

elif keyword with example in Python

Python elif keyword: Here, we are going to learn about the elif keyword with example.
Submitted by IncludeHelp, on April 14, 2019

Python elif keyword

elif is a keyword (case-sensitive) in python, it is used in the conditional statement, if we have multiple conditions to be checked, we have to use elif keyword to check next condition.

Note: First condition is checked with if keyword and other all are checked with elif keyword and if the last/default block (if any condition is not true) is written with else keyword.

Syntax of elif keyword

    if test_condition1:
	    statement(s)-true-1
    elif test_condition2:
    statement(s)-true-2
    .
    .
    ..
    else:
	    statement(s)-false

Here, if test_condition1 is True, then statement(s)-true-1 will be executed, if the test_condition2 is True, then statement(s)-true-2 will be executed, and so on... we can test multiple conditions, if all conditions are not True, then else block (statement(s)-false) will be executed.

Example:

    Input:
    num = -21

    # condition
    if num>0:
        print(num," is a positive value")
    elif num<0:
        print(num," is a negative value")
    else:
        print(num," is a zero")

    Output:
    -21  is a negative value

Python examples of if, else, elif keywords

Example 1: Input a number and check whether it is positive, negative or zero.

# python code to demonstrate example of 
# if, else and elif keywords 

# Input a number and check whether 
# it is positive, negative or zero.

# input
num = int(input("Enter a number: "))

# conditions
if num>0:
    print(num," is a positive value")
elif num<0:
    print(num," is a negative value")
else:
    print(num," is a zero")

Output

First run:
Enter a number: -21
-21  is a negative value

Second run:
Enter a number: 2
2  is a positive value

Third run:
Enter a number: 0
0  is a zero

Example 2: Input three numbers and find largest number.

# python code to demonstrate example of 
# if, else and elif keywords 

# Input three numbers and find largest number.
a = int(input("Enter first number :"))
b = int(input("Enter second number:"))
c = int(input("Enter third number :"))

large =0

# conditions
if a>b and a<c:
    large = a;
elif b>a and b>c:
    large = b;
else:
    large = c;

# printing largest number 
print("largest number is: ", large)

Output

Enter first number :10
Enter second number:30
Enter third number :20
largest number is:  30


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.