Python - 尝试并且除了不工作

时间:2014-05-25 20:28:43

标签: python

我正在为计算机科学评估,简单的计数器游戏制作游戏。使用Try和Excpet子句仅允许用户输入1或2作为计数器选择。但只重复尝试'尝试'部分并没有去'除了'。

以下是代码:

while True:
    try:
        selected_piece = int(input("Which piece would you like to move? (1/2):  "))
        if selected_piece == 1 or selected_piece == 2:
            break
    except:
        print("Please enter either (1/2):  ")

谢谢!

3 个答案:

答案 0 :(得分:2)

您可以使用:

while True:
        selected_piece = int(input("Which piece would you like to move? (1/2):  "))
        if selected_piece not in [1,2]:
            print("Invalid input, please try again.")
            continue
        else:
            break

答案 1 :(得分:2)

如果引发异常,则只输入except块。像

这样的东西
while True:
    try:
        selected_piece = int(input("Which piece would you like to move? (1/2):  "))
        if selected_piece == 1 or selected_piece == 2:
            raise Exception("Invalid number selected")
    except:
        print("Please enter either (1/2):  ")

请注意,建议您不要使用例外来控制程序的流程。您需要执行Padraic's answer建议的操作。

答案 2 :(得分:0)

我总是尽量避免使用休息或继续他们可能有点狡猾。您可以尝试将其放入函数中,并在需要使用它时调用它:

def getInput():
    validInput = False
    while not validInput:
        usrInput = input("Which piece would you like to move? (1/2):  ")
        if usrInput in ['1','2']:
            validInput = True
            return int(usrInput)
        else:
            print("Invalid input, please try again.")