Melanie432k Melanie432k - 1 month ago 15
Python Question

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

Confusion about how to use finally statement!

So the first time, the first time through the loop there is an error because of an attempted division by zero. However, Istill 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

wwl wwl
Answer

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