import sys
ok = True
count = 0
while ok == True:
try:
a = int(input("What is a? Put number pls "))
ok = False
count = count + 1
except ValueError:
print("no u")
if (count >= 3):
sys.exit()
What I’m trying to do here is get the user to input an integer. If the user inputted an integer or the loop has ran 3 times, the program stops. I have tried putting the if statement both in the try and except statements, it still keeps on looping.
I have also tried this:
ok = True
count = 0
while ok == True:
try:
a = int(input("What is a? Put number pls "))
ok = False
count = count + 1
except ValueError:
print("no u")
if (count >= 3):
break
It still doesn’t break out of the loop.
I have inputted numbers, breaks out of the loop as what I expected. I then tried to input random letters and hoped that the loop stops after 3 times, it still continues to loop until I have inputted a number. Happens to both versions.
>Solution :
Here’s an approach which you might not have thought of:
count = 0
while count < 3:
try:
a = int(input("What is a? Put number pls "))
break
except ValueError:
print("no u")
count = count + 1
There is no need for ok because you can just use a break statement if you want to end the loop. What you really want to be testing for is if count is less than three, and incrementing count every time the user gets it wrong.
There is no reason to increment count if the loop is about to end, so you want to increment count whenever there is a ValueError (in the except-block) and the loop is about to start again.