A technique from a chatbot

Pieter van Oostrum pieter-l at vanoostrum.org
Wed Apr 3 17:15:18 EDT 2024


ram at zedat.fu-berlin.de (Stefan Ram) writes:

>   It can lead to errors:
>
> def first_word_beginning_with_e( list_ ):
>     for word in list_:
>         if word[ 0 ]== 'e': return word
>     something_to_be_done_at_the_end_of_this_function()
>     
>   The call sometimes will not be executed here!
>   So, "return" is similar to "break" in that regard.

That can be solved with finally:

def first_word_beginning_with_e( list_ ):
    try:
        for word in list_:
            if word[ 0 ]== 'e': return word
    finally:
        print("something_to_be_done_at_the_end_of_this_function()")

-- 
Pieter van Oostrum <pieter at vanoostrum.org>
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]


More information about the Python-list mailing list