avatarSevdimali

Summary

The article explains the use of the else statement in Python loops and try-except blocks, emphasizing its execution under specific conditions when no break or exceptions occur.

Abstract

The article delves into the less commonly known usage of the else statement in Python, beyond its typical pairing with if. It illustrates how else can be applied following while and for loops, where it executes only if the loop completes its iteration without encountering a break statement. Similarly, in try-except blocks, the else block runs if the try block executes without raising an exception. The author shares personal experience from a job interview that prompted this exploration and provides code examples to demonstrate the practical application of else in these contexts. Additionally, the article distinguishes the else block from the finally block in exception handling, noting that finally is used for resource cleanup regardless of whether an exception was raised.

Opinions

  • The author initially underestimated the complexity of the else statement during a job interview, indicating a common gap in understanding among Python programmers.
  • The author expresses a commitment to continuous learning and sharing knowledge, as evidenced by the decision to research and write about the topic after the interview.
  • The article suggests that mastering these nuances of Python can improve code robustness and readability.
  • By sharing their #7/52 story in 2023, the author conveys dedication to consistent content creation and personal development goals.
  • The author encourages reader engagement by asking for claps and follows if the article is found useful, showing appreciation for community support and feedback.

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 else block is executed when the loop completes all its iterations without a break statement.
  • In try-except blocks, the else block is executed when the try block 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..!

Some other related articles you should go check out!

Python
Else
Python Programming
Web Development
Python3
Recommended from ReadMedium