Usage of 'else' in Python
The else
keyword in Python has a few different applications, but it primarily functions within conditional statements:
Conditions
if...else
statements: This is the most common use ofelse
.- It allows you to define an alternate block of code to execute if the condition in the
if
statement is False.
= 12
else
with ternary operator
= 12
# You are not eligible to vote.
else
with comprehension
# Even/Odd Marker
=
# ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
Loops
for...else
andwhile...else
loops: In Python, you can optionally use anelse
block withfor
andwhile
loops.- This code block will only execute if the loop terminates normally (i.e., it completes all iterations without a
break
statement being called).
for else loop
- Imagine you have a list of groceries and want to check if a specific item is present. Traditionally, you might use a flag variable to track if the item is found:
= False
=
=
= True
break # Exit the loop after finding the item
With for...else
, you can achieve the same functionality without needing a flag:
=
=
break # Exit the loop after finding the item
- The
else
block here executes only if the loop finishes iterating through the entire list without finding a match. - `break` statement needs to be added once the condition inside the loop is satisfied to come out of the loop. Otherwise the else statement will execute.
- This keeps the code cleaner and avoids the need for an extra variable.
while else loop
- Suppose you want a valid integer input from the user within a specific range. Here’s how you might do it with a
while
loop:
= 5
= 10
=
break # Exit the loop on valid input
With while...else
, you can express the validation process more clearly:
= 5
= 10
=
break # Exit the loop on valid input
# Print input only if valid
- The
else
block here executes only if thewhile
loop completes all iterations without finding a valid input. - This provides a clear message to the user if their input doesn’t meet the criteria.
Exception Handling
try...except...else
blocks: Theelse
block in atry...except
statement handles exceptions.- If no exceptions occur while executing the code in the
try
block, the code within theelse
block will be executed.= 10 / 0 # This will cause a ZeroDivisionError # This won't execute because of the exception
- Remember that the
else
block is always optional and only executes under specific conditions depending on the context (i.e., if theif
condition is False, the loop completes normally, or no exceptions occur in thetry
block).
Summary
We have gone through various ways we can use `else` keyword in Python programming language.