×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python elif Keyword

By IncludeHelp Last updated : December 07, 2024

Description and Usage

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

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.

Sample Input/Output

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

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.