防止字符串int(input())出错,并防止负数输入



这是一个非常简单的问题,我已经忘记了,但对于我列出的代码,我如何确保在输入字符串时不会弹出错误,以及如果输入负数,我如何再次返回问题。

roomChoice = int(input("Which room would you like to book?: "))

希望得到一个清晰简洁的回复,因为我必须在文档中对此进行解释。

您可以使用tryexcept:

while True:
try: # the block of code below 'try' is being tested
roomChoice = int(input("Which room would you like to book?: "))
if isinstance(roomChoice, int) and roomChoice >= 0:  # if roomChoice is an positive int exit the loop
break
except ValueError as e: # following is what happens if there's a ValueError
print(f'An {e} error occured! Input an integer!')

关于tryexcept:w3schools 的文档

您可以使用pyinputplus模块:

import pyinputplus as pyip
roomChoice = pyip.inputInt(prompt="Which room would you like to book?: ", min=0)

相关内容

  • 没有找到相关文章

最新更新