【问题标题】:Return only working first time in function仅返回函数中第一次工作
【发布时间】:2015-02-28 19:52:22
【问题描述】:

当我在 python 中运行我的石头剪刀布游戏时,故意将'rock''paper''scissors' 中的一个拼写错误,正如预期的那样,它再次运行Player_num 函数。但是,当我输入正确拼写的选项时,它会返回数字,它会以NoneType 的形式返回;而如果我第一次拼写正确,它会将变量号返回为int 而不是NoneType

我不知道如何解决这个问题,我尝试跟踪变量,但没有运气。

#Part of rock paper scissors game
def Player_num():
    #Player chooses one of rock paper or scissors
    print("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
    guess = input()
    #The if statement is to decide whether the user's input is right or not
    if Valid_guess(guess):
        #if it is right, it continues with the game
        #the user's choice will be converted to a number 1,2 or 3
        if guess == 'rock':
            number = 1
        elif guess == 'paper':
            number = 2
        elif guess == 'scissors':
            number = 3
        return number
        #if the input is invalid, the system prompts the user to try it again
    else:
        print('That response is invalid.')
        Player_num()

#Part of rock paper scissors game
def Valid_guess(guess):
    #Validates the user's input
    if guess == 'rock' or guess == 'paper' or guess == 'scissors':
        status = True
    else:
        status = False
    #Returns the boolean value status
    return status

【问题讨论】:

  • return guess in {'rock','paper', 'scissors'} 将执行您在函数中执行的所有代码,您还应该使用 while 循环而不是继续调用函数

标签: python function return


【解决方案1】:

在函数的最后,在else 块中,你写了:

Player_num()

我假设你的意思是:

return Player_num()

否则,您会得到正确的输入,但不要将其返回给调用者。该函数反而运行结束,并返回默认返回值None

【讨论】:

    【解决方案2】:

    尝试使用以下方法:

    def Player_num():
        print("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
        guess = input()
        if Valid_guess(guess):
            if guess == 'rock':
                number = 1
            elif guess == 'paper':
                number = 2
            elif guess == 'scissors':
                number = 3
            return number
        else:
            print('That response is invalid.')
            return Player_num()
    
    def Valid_guess(guess):
        if guess in ['rock', 'paper', 'scissors']:
            return True
        return False
    

    Valid_guess 也被简化为一条语句。

    【讨论】:

    • 如果您要尝试改进代码,最好只返回 ,return guess in {'rock','paper', 'scissors'} 并使用 while 循环
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 2011-09-06
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多