Home > Software engineering >  How do I break out of a While loop when either the variable becomes True/False or a certain amount o
How do I break out of a While loop when either the variable becomes True/False or a certain amount o

Time:10-29

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.

CodePudding user response:

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.

CodePudding user response:

I would recommend a slightly expanded version of michaels solution, that takes advantage of the while/else mechanism to determine when no good input was provided

count = 0
while count < 3:
    try:
        a = int(input("What is a? Put number pls "))
        break
    except ValueError:
        print("no u")
        count = count   1
else: # is triggered if the loop completes without a break
   print("No Break... used up all tries with bad inputs")
   sys.exit(-1)

print(f"You entered a number {a}")
  • Related