【发布时间】: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 循环而不是继续调用函数