The else
statement in Python provides a way to execute an alternate block of code when the condition in an if
statement evaluates to False. Adding an else
clause to an if
statement ensures your code accounts for multiple scenarios and provides a fallback option for when the condition is not met.
In this comprehensive guide, we will cover the syntax, usage, and examples of the else
statement in Python. We will examine how to use else
with if
, elif
, for
and while
loops. We will also discuss some common pitfalls and best practices when using else
clauses to handle fallback logic in your Python programs.
Table of Contents
Open Table of Contents
Syntax of the else Statement
The syntax of the else
clause in Python is straightforward:
if condition:
# execute this block if condition is True
else:
# execute this block if condition is False
The else
statement always goes after the if
statement and corresponding indented block. It provides an alternate path of execution when the condition in the if
statement evaluates to False.
Here are some key points about Python’s else
syntax:
- The
else
clause must align with theif
statement, with theelse
keyword lined up with theif
keyword. - The code block under the
else
clause is indented to the right, just like theif
block. - There can only be one
else
clause perif
statement. - The
else
block will execute only when theif
condition is False. - The
else
clause is optional and not required with everyif
statement.
So in summary, the else
allows you to specify what should happen if the condition being evaluated is False, providing a fallback path for your code.
Simple If/Else Example
Let’s look at a simple example to illustrate how if/else
works:
age = 15
if age >= 18:
print("You are eligible to vote")
else:
print("You are not eligible to vote yet")
Here we check if the value of age
meets the condition age >= 18
. If so, we print a message that the person is eligible to vote. Otherwise, we inform them they are not eligible yet using the else
clause.
The output would be:
You are not eligible to vote yet
Since 15 is less than 18, the if
condition evaluates to False. So the else
block is executed instead, printing the fallback message.
Else Clause Order
It’s important to note the order of if
, elif
, and else
clauses in conditional logic:
if condition1:
# do something
elif condition2:
# do something else
else:
# fallback
The if
is checked first, then elif
, and else
is always last. The conditions are evaluated in order, and the first one that evaluates to True triggers that code block to run. Once one block executes, the rest are skipped.
So the else
clause will run if and only if all previous conditions were False. This provides a final fallback to handle all other cases.
Indentation
As with all Python code blocks, proper indentation is crucial when using if
, elif
, else
. The colon (:) starts the indented code blocks, with consistent indentation levels for each section:
if x > 0:
print("Positive number")
else:
print("Negative number") # this line is indented to match if statement
Mixing indentation levels or using inconsistent tabs/spaces will cause errors:
if x > 0:
print("Positive number") # INCORRECT: not indented
else:
print("Negative number") # INCORRECT: inconsistent indentation
So take care to indent your if/else
blocks correctly to avoid problems.
Multi-way if/elif/else
The if
statement allows chaining together multiple conditions using elif
(short for else if) clauses. Here is an example:
age = 12
if age < 4:
ticket_price = 0
elif age < 18:
ticket_price = 10
elif age < 65:
ticket_price = 20
else:
ticket_price = 15
This sets the ticket_price
variable based on different age ranges. We check each elif
condition until one evaluates to True. When that happens, the code under that block runs and the rest of the elif/else
sections are skipped.
The else
at the end provides a final fallback value for any other age supplied. This is a complete conditional chain that accounts for all possibilities.
Else with Loops
The else
clause can also be used with for
and while
loops in Python. It executes after the loop finishes normally without hitting a break
statement.
Here is an example with for
:
for i in range(5):
if i == 3:
break
else:
print("Loop finished normally")
This else
block after the for
loop will run only if the loop exits normally without hitting the break
. This can be useful for code that should execute at the end of a loop as long as it wasn’t stopped prematurely.
And here is an example with while
:
count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop finished")
The else
block here will execute after the while
loop finishes normally. But if we put a break
inside the loop, it would not run.
Using else
with loops like this provides a way to take final action after iteration without needing extra conditional logic.
Handling Exceptions
A common use case for else
clauses is when handling exceptions in Python. Using a try/except
block, you can have an else
that executes only if no exceptions were caught:
try:
num = int(input("Please enter a number: "))
except ValueError:
print("That was not a valid number!")
else:
print(f"You entered the number {num}")
Here the code inside try
will be checked for exceptions, and except
will catch any ValueError
raised. But if no exceptions occur, the else
block after it will run to print the valid input.
This provides a way to take action for the “happy path” scenario where no exceptions occur, while still accounting for and handling possible exceptions in the except
block.
Else vs Additional If
A common question is when to use else
versus just adding an additional if
condition.
For example:
if x > 0:
print("Positive number")
if x < 0:
print("Negative number")
Versus:
if x > 0:
print("Positive number")
else:
print("Negative number")
In this case, the else
clause makes the intention more clear and concise. We are covering the two mutually exclusive cases - either x is positive or negative. The single if/else
chain communicates this effectively.
In general, use else
when:
- You want only one of two code paths to execute
- You have a condition with mutually exclusive cases
- Your fallback condition is the inverse of the initial check
- You have a code block that should run if no exceptions occur
And use separate if
statements when:
- Checking unrelated, independent conditions
- Evaluating non-mutually exclusive cases
- Handling complex conditional logic that merits separate checks
Consider which strategy makes your code clearest in each unique situation.
Common Pitfalls
There are some common pitfalls and bad practices to avoid when using else
clauses:
Forgetting the Colon
It’s easy to forget the colon (:) after the else
, which will result in an indentation error:
if x > 0
print("Positive")
else # Colon missing
print("Negative")
Always include that colon after else
!
Using Else Without If
Don’t use an else
without a corresponding if
statement. This will not work:
print("Start")
else: # Can't have else here without if
print("In else block")
The else
needs an if
before it for the conditions to be valid.
Dangling Else
Because Python uses indentation rather than brackets, it has issues with the “dangling else” problem.
This can happen if you intend an else
to apply to one if
statement, but because it’s aligned incorrectly, it attaches to an outer one instead.
For example:
if x > 0:
if y > 0:
print("Both positive")
else:
print("Only x is positive") # Bug: associates with wrong if
The else
here is accidentally aligned with the outer if
rather than the inner one. So it behaves incorrectly.
Careful indentation is key to avoiding this issue!
Unnecessary Else
There are times when an else
clause is redundant and unnecessary:
if x > 0:
print("Positive")
else:
# Doesn't do anything
pass
If the else
block doesn’t contain meaningful code, it’s often clearer to omit it entirely:
if x > 0:
print("Positive")
Like all aspects of coding, keep your conditional logic as simple and clear as possible. Don’t use else
just out of habit!
Best Practices
To use Python’s else
statement most effectively, keep these best practices in mind:
-
Use else to handle mutual exclusivity - Reserve
else
for cases where only one block or the other can execute. -
Keep conditions simple - Overly complex
if/else
chains are hard to understand. Refactor conditions when needed. -
Include useful else blocks - The
else
block should contain meaningful code, not just be a no-op. -
Watch indentation levels - Accidental indentation is a major source of else bugs. Double check alignment.
-
Write descriptively - Use variable names and comments to describe the logic and make conditionals self-documenting.
-
Limit nested ifs - Too many nested
if
statements can be confusing. Extract helper functions when logic is complex.
Following these tips will help you write clean Python code using else
clauses effectively!
Conclusion
The else
statement in Python provides an important fallback execution path in your code. Using else
with if
, elif
, for
, while
, and try/except
blocks gives you greater control over conditional logic.
Key takeaways:
- The
else
clause runs when theif
condition is False. else
comes afterif/elif
blocks and is the final catch-all condition.- Indent
else
blocks consistently to match theif
statement. - Use
else
with loops to take action after clean iteration. - Handle exceptions with
else
in atry/except
block. - Favor
else
for mutually exclusive cases vs chains ofif
statements. - Watch out for dangling
else
clauses and indentation errors.
With proper usage, else
allows you to account for all eventualities in your Python programs. You can provide fallback values, handle errors, and write clean conditional logic using if..else
chains.
So remember to leverage else
to make your Python code more robust, readable, and bug-free!