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:
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)