“else” Keyword in Python: When to Use It and How

"else" Keyword in Python: When to Use It and How

When working with conditional statements in Python, programmers often use the “if” statement to execute a block of code based on a specific condition. However, sometimes we may also want to execute a different block of code if the condition evaluates to False. This is where the “else” keyword comes into play.

The “else” keyword is used in conjunction with the “if” statement to provide an alternative block of code to execute if the initial condition is not met. In this article, we will explore various use cases for the “else” keyword in Python and understand how it can make our code more efficient and concise.

Basic Use of else Statement

The most basic use case for the “else” statement is to execute a block of code if the initial “if” condition is not met. Consider the following example:

num = 10

if num > 15:
    print("Number greater than 15")
else:
    print("Number less than or equal to 15")

In the above example, since the value of the variable “num” is less than 15, the “if” condition is not met and the program moves on to the “else” block, which prints “Number less than or equal to 15”. If the value of “num” had been greater than 15, the “if” block would have executed instead.

Output:
Number less than or equal to 15

Using Multiple elif Statements

While the “if-else” block can cover the basic use cases of using the “else” keyword, sometimes we may need to include multiple conditions in our program. In such cases, we can use the “elif” keyword to add additional conditions. Consider the following example:

num = 25

if num  0 and num  10 and num <= 20:
    print("Number is between 11 and 20")
else:
    print("Number is greater than 20")

In the above example, we have used multiple “elif” blocks to cover all possible numbers between 1 and 20, followed by the “else” block to cover any number greater than 20. Based on the value of “num”, the corresponding block of code will be executed.

Output:
Number is greater than 20

Using else with Loops

The “else” keyword can also be used in conjunction with loops in Python. When used with a “for” loop, the “else” statement is executed after the loop completes normally. Consider the following example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)
else:
    print("No more fruits to display")

In the above example, the loop will iterate over the list of fruits and print each fruit’s name. Once the loop has iterated over all the items in the list, the “else” block will execute, and the message “No more fruits to display” will be displayed.

Output:
apple
banana
cherry
No more fruits to display

When used with a “while” loop, the “else” statement is executed after the loop completes, and the condition becomes False. Consider the following example:

num = 1

while num < 5:
    print(num)
    num += 1
else:
    print("Loop completed; num is now greater than or equal to 5")

In the above example, the “while” loop will continue iterating and printing the value of “num” until it becomes greater than or equal to 5. Once the condition becomes False, the “else” block will execute, which displays the message “Loop completed; num is now greater than or equal to 5”.

Output:
1
2
3
4
Loop completed; num is now greater than or equal to 5

Using else with Try-Except Blocks

Another use case for the “else” keyword is to use it in conjunction with “try-except” blocks to handle exceptions gracefully in our code. Consider the following example:

num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")

try:
    result = int(num1) / int(num2)
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Result of division: ", result)

In the above example, we are prompting the user to enter two numbers and then attempting to divide them. However, if the second number entered by the user is zero, it will result in a ZeroDivisionError. To handle this exception, we have used a “try-except” block. If any exception occurs within the “try” block, the corresponding “except” block will execute. If no exception occurs, the “else” block will execute, which displays the result of the division operation.

Output:
Enter the first number: 10
Enter the second number: 0
Cannot divide by zero

Conclusion

The “else” keyword in Python provides a flexible and powerful tool for executing code based on specific conditions. From handling exceptions gracefully to adding multiple conditions to our programs, the “else” statement can help us write more efficient and concise code. By understanding the various use cases for “else” in Python, we can become better programmers and write better and more effective code.

Leave a Reply

Your email address will not be published. Required fields are marked *