Applying the else Clause
The else
clause in Python's if-else
statements can be applied in a variety of situations to handle different scenarios. Let's explore some common use cases:
When working with user input, the else
clause can be used to handle cases where the user's input does not meet the expected criteria.
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
In this example, if the user enters a value that is greater than or equal to 18, the message "You are eligible to vote." will be printed. Otherwise, the message "You are not eligible to vote." will be printed.
Implementing Error Handling
The else
clause can be used in conjunction with exception handling to provide alternative actions when an error occurs.
try:
result = 10 / int(input("Enter a number: "))
print("The result is:", result)
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Error: Division by zero.")
else:
print("No exceptions occurred.")
In this example, if the user enters a valid number, the division operation is performed, and the result is printed. If the user enters a non-numeric value, the ValueError
exception is caught, and the message "Invalid input. Please enter a number." is printed. If the user enters zero, the ZeroDivisionError
exception is caught, and the message "Error: Division by zero." is printed. The else
clause is executed when no exceptions are raised.
Implementing Nested if-else Statements
The else
clause can be used in nested if-else
statements to handle multiple conditions and scenarios.
score = 85
if score >= 90:
print("Grade: A")
else:
if score >= 80:
print("Grade: B")
else:
if score >= 70:
print("Grade: C")
else:
print("Grade: D")
In this example, the outer if-else
statement checks if the score
is greater than or equal to 90. If it is, the message "Grade: A" is printed. If not, the inner if-else
statements check if the score is greater than or equal to 80 and 70, respectively, and print the corresponding grade.
By applying the else
clause in these scenarios, you can create more comprehensive and robust decision-making processes in your Python programs.