Saturday, July 2, 2022

What is if-elif-else statement in Python?

If there is case where we need more than two possibilities and we need more than two branches then we have to use chained conditional or if-elif-else conditional. The if and else we know and the new term here is elif which is short for else if. The general form of chained condition or if-elif-else conditional can be written as:
if condition1:
indented statement
elif condition2:
indented statement
else:
indented statement
There is no limit to the number of elif statements. The else clause goes at the end but there doesn't have to be one. If condition1 is True than the indented statement if condition1 is executed. If condition1 is False then the if condition1 is skipped and condition2 is investigated. If condition2 is True than the indented code under elif condition2 is executed. Otherwise the elif condition2 is skipped and the indented statement under else conditional is executed.
Example 1 The user will type the number and the program must give one of the following outputs: The nubmer is positive. The number is equal to zero. The number is negative.
Solution: We will utilize the "input" function that will ask the user to type in the number. This number will be converted to integer using int() and then assigend to a variable \(num\).
num = int(input("Enter a number: "))
The variable "num" will be investigated if its greater than 0 if it is equal to 0 or it is negative. If any of these conditions are true it will print one of the following messages: The number is positive. The number is equal to zero. The number is negative. This will be done using if-elif-else conditional.
if num > 0:
print("The number is positive!")
elif num == 0:
print("The number is equal to 0!")
else:
print("The number is negative!")
The entire code for this example is given below.
num = int(input("Enter a number: "))
if num > 0:
print("The number is positive!")
elif num == 0:
print("The number is equal to 0!")
else:
print("The number is negative!")
The previous code has three posible outputs. The first output is that the number is positive so when runing the code we will type the nubmer 5. The output is given below.
Enter a number: 5
The number is positive!
The second output is "The number is equal to zero." so when we run the code we will type the number 0. The output is given below.
Enter a number: 0
The number is equal to 0!
The last program output is that the number is negative so when we run the code we will type number -5. The output is given below.
Enter a number: -5
The number is negative!

No comments:

Post a Comment