这是一个非常简单的问题,我已经忘记了,但对于我列出的代码,我如何确保在输入字符串时不会弹出错误,以及如果输入负数,我如何再次返回问题。
roomChoice = int(input("Which room would you like to book?: "))
希望得到一个清晰简洁的回复,因为我必须在文档中对此进行解释。
您可以使用try
和except
:
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!')
关于try
和except
:w3schools 的文档
或
您可以使用pyinputplus
模块:
import pyinputplus as pyip
roomChoice = pyip.inputInt(prompt="Which room would you like to book?: ", min=0)