Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I break out of a While loop when either the variable becomes True/False or a certain amount of times?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading