What is the use of else in loops and try statements?
In this article, we will explain how to use the else statement in the loops and try statements.

In one of my previous interviews, I was asked about the expression “else”. It sounded so simple, I even smiled, but after explaining its use in conjunction with the if statement, I was asked where else is used. This is the first time I’ve heard of it, despite working with python so much 🙄
Of course, I researched it immediately after the interview. I think many of us may not know about this topic, so I decided to write an article about it. The most common use of the else statement is in conjunction with the if statement. The else block runs if the “if condition” is not met — if it returns False.
For example:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")Now let’s look at the use of else with loop operators. First, let’s look at its use with the while loop. If the while loop runs without a break and ends, then the else block runs. For example, suppose we pull data from any API. If it fails more than 3 times, then we end the loop, or if we receive a successful response, then we print the data and then break.
import requests
max_attempts = 3
attempt = 1
while attempt <= max_attempts:
url = "https://domain.com/api"
response = requests.get(url)
if response.status_code == 200:
print(f"Successfully fetched data: {response.json()}")
break
else:
print(f"Attempt {attempt} failed with status code {response.status_code}. Please try again.")
attempt += 1
else:
print(f"All {max_attempts} attempts failed. Could not get data from the url.")In the above code, if the user successfully receives a response from the API, then the break will run and the else block will not run. But if all three attempts fail, then the else block will run.
Using else with for loop is similar to while. If we haven’t exited the cycle with the break, the else block is executed. Let’s give an example of it. For example, let’s assume that we have a list of data received from the sensor. And we want to save it to the database. If we’ve successfully committed all the elements to the database, we’ll return a success message and call another function.
sensor_data = [1, 2, 6, 6, "error", 3, 1, "error", 9]
for value in sensor_data:
if value == "error":
print("Invalid sensor data")
break
write_to_db(value)
else:
print("All elements inserted successfully")
another_func()The else block can be used in conjunction with try and except to specify code that should be executed if no exceptions are raised in the try block.
Now let’s look at an example. Suppose we read numbers from a file and sum them. If everything is successfully read and summed, then we print the result in the else block.
I remembered that the finally block is executed regardless of whether an exception is raised or not. It is typically used for cleaning up resources such as closing files, sockets, or database connections, and ensuring that the resources are released properly, even if an exception is raised.
try:
f = open("file.txt", "r")
lines = f.readlines()
result = sum([int(line) for line in lines])
except FileNotFoundError:
print("File not found.")
except ValueError:
print("Invalid data in file.")
else:
print(f"The sum is: {result}")
finally:
if f:
f.close()To sum up.
- In loops, the
elseblock is executed when the loop completes all its iterations without abreakstatement. - In try-except blocks, the
elseblock is executed when thetryblock completes successfully without raising an exception.
Thanks for reading. I hope you enjoyed it ❤. If you found the article useful don’t forget to clap and follow me.
This is my #7/52 story in 2023, I’m on a challenge to write 52 stories in 2023.
Keep Learning..!






