Check if input is positive integer [duplicate]
I need to check whether what the user entered is positive. If it is not I need to print an error in the form of a msgbox.
number = input("Enter a number: ")
###################################
try:
val = int(number)
except ValueError:
print("That's not an int!")
The above code doesn't seem to be working.
Any ideas?
Solution 1:
while True:
number = input("Enter a number: ")
try:
val = int(number)
if val < 0: # if not a positive int print message and ask for input again
print("Sorry, input must be a positive integer, try again")
continue
break
except ValueError:
print("That's not an int!")
# else all is good, val is >= 0 and an integer
print(val)
Solution 2:
what you need is something like this:
goodinput = False
while not goodinput:
try:
number = int(input('Enter a number: '))
if number > 0:
goodinput = True
print("that's a good number. Well done!")
else:
print("that's not a positive number. Try again: ")
except ValueError:
print("that's not an integer. Try again: ")
a while loop so code continues repeating until valid answer is given, and tests for the right input inside it.