只接受一种输入

时间:2017-03-05 21:16:12

标签: python python-3.x

我正在建造一个可以玩AI的摇滚,纸张和剪刀模拟器。

print('1.Rock 2.Scissors 3.Paper')
choice = int(input('Input your choice:\n')) 

代码的一部分要求用户输入他想要显示的内容。如果玩家想玩摇滚,纸张,剪刀。因此,例如,如果有人想使用摇滚,他会输入1。 我不想让用户输入任何其他数字或字母,或者如果他输入以显示错误并再次询问问题。

我应该使用什么?我正在考虑使用 if ,但我认为存在更好的方式。

2 个答案:

答案 0 :(得分:1)

这是一种方式:

while True:
    try:
        selection = int(input("Input your choice:\n"))
        if selection < 1 or selection > 3: #Valid number but outside range, don't let through
            raise ValueError
        else: #Valid number within range, quit loop and the variable selection contains the input.
            break
    except ValueError: #Invalid input
        print("Enter a number from 1 to 3.")

答案 1 :(得分:0)

使用if不是问题。

看起来像这样:

if not (1 <= choice <= 3):
    raise ValueError()

您还可以使用正则表达式来检查输入。