Search code examples
pythonpython-3.xexceptiontry-catch-finally

Using a finally statement in python to print out how many times Ive have been through the loop


I'm confused about about how to use the "finally" statement!

So the first time through the loop there is an error because of an attempted division by zero. However, I still want to print to the user that the loop executed.

The except clause should print a message to the user informing them that a division by zero was attempted.

The finally clause should print out how many times we have been through the loop.

This is what I have so far

for i in range(10):
    try:
        print(7/i)
    except ValueError:
        print("Value contents invalid.")
    finally:
        Finally message

Solution

  • Let's divide your question into parts:

    Part 1: print to the user that the loop executed. The except clause should print a message to the user informing them that a division by zero was attempted.

    Part 2: The finally clause should print out how many times we have been through the loop.

    Below is the answer. Note that additional indentation is required. Also, it should be ZeroDivisionError, not ValueError.

    for i in range(10):        
        try:
            print(7/i)
        except ZeroDivisionError: # part 1
            print("Division by zero error.")
        finally:
            print("We've been through the loop ", i + 1, " times.") # part 2