If...Elif...Else...
Introduction:
- Python supports logical conditions from mathematics:
- Equals:
a == b - Not Equals:
a != b - Less than:
a < b - Less than or equal to:
a <= b - Greater than:
a > b - Greater than or equal to:
a >= b
- Equals:
Elif Statement:
- The
elifkeyword is Python's way of saying "if the previous conditions were not true, then try this condition."
Syntax of Elif:
python
if boolean_expression_1:
statement(s)
elif boolean_expression_2:
statement(s)
elif boolean_expression_3:
statement(s)
else:
statement(s)
- You can have as many
elifstatements as required.
Examples:
- Simple Elif Example:
Checking two conditions:
a < bin if-condition anda > bin elif-condition.pythona = 6 b = 4 if a < b: print(a, 'is less than', b) elif a > b: print(a, 'is greater than', b) else: print(a, 'equals', b)- Output:
6 is greater than 4
- Multiple Elif Blocks:
Writing multiple
elifblocks in the if-elif ladder.pythona = 2 if a < 0: print(a, 'is negative') elif a == 0: print('its a 0') elif a > 0 and a < 5: print(a, 'is in (0.5)') else: print(a, 'equals or greater than 5')- Output:
2 is in (0.5)
Exercises:
- Elif Statement:
Write a program to check the grade of a student based on marks entered by the user.
pythonmarks = int(input("Enter marks: ")) if marks >= 90: print("Grade: A") elif marks >= 80: print("Grade: B") elif marks >= 70: print("Grade: C") elif marks >= 60: print("Grade: D") else: print("Grade: F")
- Nested Elif:
Write a program to check if a number is positive, negative, or zero, and if positive, check if it is even or odd.
pythonnumber = int(input("Enter a number: ")) if number > 0: print("The number is positive.") if number % 2 == 0: print("The number is even.") else: print("The number is odd.") elif number == 0: print("The number is zero.") else: print("The number is negative.")
Summary:
- Python
elifstatements are used to execute a continuous chain of conditional logic ladder. Practice writingelifstatements to become proficient in using conditional logic in your programs