Python 仅返回函数中第一次工作的时间

Python 仅返回函数中第一次工作的时间,python,function,return,Python,Function,Return,当我用python运行我的石头剪刀游戏,并故意将'rock'、'paper'或'scissors'中的一个拼写错误时,正如预期的那样,它会再次运行Player_num函数。但是,当我输入拼写正确的选项时,它将返回数字,并将其作为NoneType返回;然而,如果我第一次拼写正确,它将变量号返回为int而不是NoneType 我不知道如何解决这个问题,我已经尝试过跟踪变量,但我没有运气 #Part of rock paper scissors game def Player_num(): #

当我用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

在函数结束时,在
else
块中,您已写入:

Player_num()
我想你的意思是:

return Player_num()

否则,您将获得正确的输入,但不要将其返回给调用者。相反,该函数从末尾运行,并返回默认返回值
None

尝试使用以下方法:

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\u guess
也被简化为一条语句。

在{'rock'、'paper'、'scissors'中返回guess
将完成所有代码在函数中所做的工作,您还应该使用while循环,而不是继续调用函数如果您要改进代码,最好只返回,
返回guess in{'rock'、'paper'、'剪刀'}
并使用while循环