当我在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
答案 0 :(得分:2)
在您的函数结束时,在else
块中,您已写入:
Player_num()
我认为你的意思是:
return Player_num()
否则,您将获得正确的输入,但不要将其返回给调用者。该函数反而运行,并返回None
,默认返回值。
答案 1 :(得分:0)
尝试使用以下内容:
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
也被简化为一个陈述。