Python:如何在不捕获任何值的情况下重新启动方法?

时间:2016-06-21 17:06:14

标签: python methods nonetype

我用Python创建了一个Rock,Paper,Scissors游戏,但是如果玩家输入了无效命令,我就无法重新启动该方法。如果用户在第一次询问时键入除“r”,“p”或“s”以外的任何内容,则在输入正确值时将始终返回值None。我发现我可以重新启动这一轮,但是当我在游戏中加入赌注时,这会给您带来不便。

def get_input():
    choice = input("[R]ock, [P]aper, or [S]cissors? ").lower()
    if choice == 'r':
        return 'rock'
    elif choice == 'p':
        return 'paper'
    elif choice == 's':
        return 'scissors'
    else:
        print("That is not a valid command. Try again.")
        get_input()

choice = get_input()
print(choice)

用户输入'a'后跟'p'时的输出:

[R] ock,[P] aper还是[S] cissors?一个
这不是一个有效的命令。再试一次。
[R] ock,[P] aper还是[S] cissors? p
没有

2 个答案:

答案 0 :(得分:3)

验证来自交互式shell的文本输入时,我建议使用循环:

def get_input():
    while True:
        choice = input("[R]ock, [P]aper, or [S]cissors? ").lower()
        if choice == 'r':
            return 'rock'
        elif choice == 'p':
            return 'paper'
        elif choice == 's':
            return 'scissors'
        else:
            print("That is not a valid command. Try again.")

请注意,在Python中使用while True是可以的,因为没有do ... while。如果只应进行有限次数的重试,则可以使用for _ in range(num_retries)

答案 1 :(得分:1)

要修复当前代码,您应该mySkscene.view 值。

return

但是,如果用户提供的输入错误太多,则堆栈最终会变得过大。你想要的是一个循环:

def get_input():
    choice = input("[R]ock, [P]aper, or [S]cissors? ").lower()
    if choice == 'r':
        return 'rock'
    elif choice == 'p':
        return 'paper'
    elif choice == 's':
        return 'scissors'
    else:
        print("That is not a valid command. Try again.")
        return get_input()
#       ^^^^^^

choice = get_input()
print(choice)