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 to repeat the input until a special condition is meet in Python?

I have a simple problem: I need to take integer inputs from user and add them to a set. The numbers of integers are unknown, the input process will end when the user input is "Done".
Below are my code:

s = set()
print('Please type the number, when you're done please type "Done":')
while True:
    try:
        a = int(input())
        s.add(a)
    except:
        if a == "Done":
            break
        else:
            print('Integer only, please re-type:')
            continue
print(s)

But it didn’t work as intended. My idea is simple. If the user types an integer then it’s fine, just add to set s. If they type a string (which int(input() is wrong), then it will go down to except, if the string is "Done", then break the while True loop, if it isn’t then ask the user to retype and continue the loop.

below are the error if I type a String first and if I type normally:
2 kind of errors

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 try to use a simple if-else statement at the start but it causes traceback right at int(input())

>Solution :

When the exception happens, a remains unset. Try this instead.

s = set()
# Notice also correct quoting
print("Please type the number, when you're done please type 'Done':")
while True:
    a = input()
    try:
        n = int(a)
        s.add(n)
    # Avoid blanket except
    except ValueError:
        if a == "Done":
            break
        else:
            print('Integer only, please re-type:')
            continue
print(s)
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