Check if input is positive integer
本问题已经有最佳答案,请猛点这里访问。
我需要检查用户输入的内容是否为正数。如果不是,我需要以msgbox的形式打印一个错误。
1 2 3 4 5 6 7 | number = input("Enter a number:") ################################### try: val = int(number) except ValueError: print("That's not an int!") |
上面的代码似乎不起作用。
有什么想法吗?
1 2 3 4 5 6 7 8 9 10 11 12 | 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 2 3 4 5 6 7 8 9 10 11 | 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循环,使代码继续重复,直到给出有效的答案,并测试其中的正确输入。