Behavior of the for-else construct

Chris Angelico rosuav at gmail.com
Fri Mar 4 12:47:37 EST 2022


On Sat, 5 Mar 2022 at 03:44, Avi Gross via Python-list
<python-list at python.org> wrote:
>
> Dieter,
>
> Your use is creative albeit it is not "needed" since all it does is make sure your variable is initialized to something, specifically None.
>
> So would this not do the same thing?
>
>   eye = None
>
>   for eye in range(0):
>       print(eye)
>
>   eye
>
> If I understand it, your example depends on a variable that is not yet initialized to be used in a loop and retain the last value after the loop. You then set it to None if it is not used as the loop is skipped. Others have shown an example similar to the above of using a sentinel that lets you know if the loop is skipped.
>
> Of course, there are some advantages in making it clear by doing it you way that the loop (for example if copied and used elsewhere) needs to include the else statement as an integral part.
>
> I would like to suggest a slight modification to the above as in if you are searching for something in either seq1 and if not found in seq2. Call it looking for your green shirt in the closet and if not found, looking in the attic. Would this code make sense as such a use in several ways? In English, look here first and if there is NOTHING there, look in the second place?
>
> closet = []
>
> attic = ["Costumes", "Sheets", "Shirts" ]
>
> for item in closet:
>     print(item)
>     if item == "Shirts" : print("FOUND in closet!!")
> else:
>     for item in attic:
>         print(item)
>         if item == "Shirts" : print("FOUND in attic!!")
>
> Yes, as discussed, you could do an IF statement to check if closet is empty but for iterators, it gets ...
>

Make sure you 'break' after finding it. Otherwise, you'll keep
searching the rest of your closet, and then still go on to search your
attic. The "else:" clause doesn't help you here unless that break is
present.

ChrisA


More information about the Python-list mailing list