How do i use the finally and else conditions in python?



  • Also see: https://www.lightnetics.com/post/9888

    finally: and else: conditions are used in python to execute alternative statements using else: and finally: always runs.

    Start off with this code.

    def eh():
        try:
          value = "Hello World!" + 5
        except TypeError:
          print("This is a TypeError, you cannot add a string and int without first converting")
        else:
            print("Great minds think alike")
    eh()
    

    We see the output:
    This is a TypeError, you cannot add a string and int without first converting

    If we correct the TypeError, value = "Hello World!" + 5 into value = "Hello World!" and run it again, the output is:

    Great minds think alike

    Now let's add the finally: condition: finally: code always gets executed.

    def eh():
        try:
          value = "Hello World!"
        except TypeError:
          print("This is an TypeError, you cannot add a string and int without first converting")
        else:
            print("Great minds think alike")
        finally:
            print("Let's get this show on the road")
    eh()
    

    The output is:
    Great minds think alike
    Let's get this show on the road


Log in to reply
 

© Lightnetics 2024