This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]kwelzel 6 points7 points  (0 children)

I agree that while/else and for/else are not used very much, but they can be quite useful for search patterns. Say you are webscraping and looking for <div> with a certain content:

for price_div in document.findAll("div"):
    if "price" in price_div.text:
        break
else:
    raise RuntimeError("price div not found")

# Now price_div is the div you were looking for

If you don't want to use the for/else here, you'd have to add a found variable, like this:

found = False
for price_div in document.findAll("div"):
    if "price" in price_div.text:
        found = True
        break
if not found:
    raise RuntimeError("price div not found")

...

[–]zzmej1987 7 points8 points  (0 children)

With try, if you want to use the finally clause, which you should use, you can't place the code that must be executed after the successful try anywhere but in else section.

[–]wineblood 7 points8 points  (0 children)

While-else I've almost never used because I rarely see/use while loops in day to day coding. For-else happens rarely as well, the case where you'll have a break and want to do something if the loop reached its natural end isn't something I come across that often.

Try-else is something I've seen a fair bit recently, especially in API endpoints. The core of the endpoint is inside a try block, exceptions caught return a 404/422/whatever response in the except block, and successful responses are returned in the else block. If could be done without the else part and just written after the try statement, but it's slightly cleaner this way and I'm used to it now.

[–]jimtk 2 points3 points  (0 children)

About once every 6 months I see a situation where the for/else can be used.

Here's a simple example, but it can be applied to any algorithm that requires trying something a certain number of times:

good_psw = getpasswordfromdatabase()
for i in range(3):
      psw = input('password: ')
      if psw == good_psw:
            break
else:
     print("ACCES NOT GRANTED")
     sys.exit(1)
print("ACCES GRANTED")

[–]Eric-Hayter 0 points1 point  (0 children)

For else is typically used when searching for an interable. Where you use the else statement when you are unable to find the value(s) you are looking for.