# Infinte while loop using try/except

hey y’all!

I’m taking an online class called Cs50P, I thought I practiced using while loops + try/exceptions to the point of being confident using this structure.

I’m running into an infinite loop when the exceptions are raised in the convert() function.

I just don’t understand why. In both exceptions the “continue” statement after the print should restart the loop back the the beginning (at least that’s my logic)…but it’s not happening.

Why?

Any ideas / suggestions to improve my code are appreciated.
Where is my logic flawed?

``````import string

def main():

fraction=input("Fraction: ")

percentage=convert(fraction)
print(f"% {percentage}")

zz=gauge(percentage)

print(zz)

def convert(fraction):

while True:

try:
x,y=fraction.split("/")

x=int(x)
y=int(y)

if y==0:
raise ZeroDivisionError

elif x>y:
raise ValueError

except ValueError:
print("found ValueError")
continue

except ZeroDivisionError:
print("found Zero Division Error")
continue

else:
z=round((x/y)*100)

print(z)

return z

def gauge(percentage):

if percentage<=1:
return "E"

elif percentage >=99:
return "F"

else:
return f"{percentage}%"

if __name__=="__main__":
main()

``````

Anytime that you want to get out of a loop, use the `break` statement.

When either exception occurs, it prints the message and the `continue` restarts the loop. The `continue` isn’t needed because the loop will keep iterating anyway.

The detail you’re missing is that nothing will have changed since the first iteration, so it’ll just keep doing the same thing. `fraction` still has the same value, after all.

1 Like

Well, let’s start by considering what your logic concludes, and then seeing how that relates to the problem you describe. Maybe the problem isn’t in the logic you gave us, but in connecting it the rest of the way.

According to what you see, why do you think that isn’t happening? (Hint: where is “the beginning” of the loop?) Let’s suppose that Python goes back to the start of the loop from the `continue`, as expected. What do you suppose should happen next after that, and why?

According to your logic, why should the loop stop? (In your description, you didn’t say anything about the loop stopping, or a possible cause for the loop stopping.)

If the loop doesn’t stop, it will be infinite, right? By definition?

1 Like

thank you!

thank you!!