我需要检查用户输入的内容是否为正数。如果不是,我需要以msgbox的形式打印错误。
number = input("Enter a number: ")
###################################
try:
val = int(number)
except ValueError:
print("That's not an int!")
上面的代码似乎没有用。
有什么想法吗?
答案 0 :(得分:7)
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)
答案 1 :(得分:0)
你需要的是这样的:
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: ")
while循环,所以代码会继续重复,直到给出有效的答案,并测试其中的正确输入。