【发布时间】:2014-02-26 10:00:04
【问题描述】:
我的石头剪刀布代码不起作用,我假设这是因为我错误地使用了返回值。我该怎么办?
编辑,所以我已经像这样存储了回报
def results (x, y):
if (x == "R" or x == "rock" or x == "r" or x == "Rock" or x == "ROCK") and (y == "S" or y == "s" or y == "Scissors" or y == "SCISSORS" or y == "scissors"):
winner = 1
return winner
但是如何让“赢家”在函数之外打印?
旧
player1 = input ("Player 1: Please enter either Rock, Paper or Scissors:")
player2 = input ("Player 2: Please enter either Rock, Paper or Scissors:")
def results (x, y):
if (x == "R" or x == "rock" or x == "r" or x == "Rock" or x == "ROCK") and (y == "S" or y == "s" or y == "Scissors" or y == "SCISSORS" or y == "scissors"):
return 1
else:
if (x == "rock" or x == "r" or x =="R" or x == "Rock" or x == "ROCK") and (y == "P" or y == "p" or y == "paper" or y == "Paper" or y == "PAPER"):
return 2
else:
if (x == "rock" or x =="R" or x == "r" or x == "Rock" or x == "ROCK") and (y == "rock" or y =="R" or y == "r" or y =="Rock" or y == "ROCK"):
return 0
else:
print ("Sorry, I didn't understand your input")
results (player1, player2)
if results == 1:
print ("Player 1 wins!")
else:
if results == 2:
print("Player 2 wins!")
else:
if results == 0:
print("It was a tie!")
【问题讨论】:
-
复习 Python 函数教程可能会让您受益——尤其是如何调用它们。这是官方的,还有其他的:docs.python.org/2/tutorial/controlflow.html#defining-functions
-
另外,请不要过多地扩展 if 语句。试试
rock_list = ["rock","R","r"]和if x in rock_list:之类的东西,这看起来更好,但它只是一种风格,所以你仍然可以选择是否使用它。
标签: python function return conditional