Python if-elif-else statement#

So far, we have presented a Boolean option for conditional statements, with each if statement evaluating to either True or False. In Python, the if-elif-else condition statement has an elif keyword used to chain multiple conditions one after another.

Syntax:#

if condition-1:  
     statement 1 
elif condition-2:
     stetement 2 
elif condition-3:
     stetement 3 
     ...         
else:            
     statement  
  1. The elif is short for else if. It allows us to check for multiple expressions.

  2. If the condition for if is False, it checks the condition of the next elif block and so on.

  3. If all the conditions are False, the body of else is executed.

  4. Only one block among the several if-elif-else blocks is executed according to the condition.

  5. The if block can have only one else block. But it can have multiple elif blocks.

# Example 1:

'''In this program, we check if the number is positive or negative or zero and 
display an appropriate message'''

num = 0

# Try these two variations as well:
# num = 0
# num = -4.5

if num > 0:
    print("Positive number")
elif num == 0:
    print("Zero")
else:
    print("Negative number")
Zero

Explanation:

When variable num is positive, Positive number is printed.

If num is equal to 0, Zero is printed.

If num is negative, Negative number is printed.

# Example 2:

num1, num2 = 5, 5
if(num1 > num2):
    print("num1 is greater than num2")
elif(num1 == num2):
    print("num1 is equal to num2")
else:
    print("num1 is less than num2")
num1 is equal to num2
# Example 3:

x = 10
y = 12
if x > y:
    print("x>y")
elif x < y:
    print("x<y")
else:
    print("x=y")
x<y
# Example 4:

grade = 96

if grade >= 90:
    print("A grade")
elif grade >=80:
    print("B grade")
elif grade >=70:
    print("C grade")
elif grade >= 65:
    print("D grade")
else:
    print("Failing grade")
A grade
# Example 5:

def user_check(choice):
    if choice == 1:
        print("Admin")
    elif choice == 2:
        print("Editor")
    elif choice == 3:
        print("Guest")
    else:
        print("Wrong entry")

user_check(1)  # Admin
user_check(2)  # Editor
user_check(3)  # Guest
user_check(4)  # Wrong entry
Admin
Editor
Guest
Wrong entry

if-elif-else statements with logical operators#

We can avoid writing nested condition by using logical operator and.

if-elif-else statements and Logical Operator#

Syntax:

if condition and condition:
    code
a = 0
if a > 0 and a % 2 == 0:
        print('A is an even and positive integer')
elif a > 0 and a % 2 !=  0:
     print('A is a positive integer')
elif a == 0:
    print('A is zero')
else:
    print('A is negative')
A is zero

if-elif-else statements or Logical Operator#

Syntax:

if condition or condition:
    code
user = 'Arthur'
access_level = 3
if user == 'admin' or access_level >= 4:
        print('Access granted!')
else:
    print('Access denied!')
Access denied!