【问题标题】:Where exactly does a python function's return value go?python函数的返回值到底去哪里了?
【发布时间】: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


【解决方案1】:

返回值不会自动存储在任何地方。您需要手动存储:

result = results(player1, player2)

if result == 1:
    ...

如果您查看代码的顶部,您会发现您已经使用 input 函数做了正确的事情:

player1 = input ("Player 1: Please enter either Rock, Paper or Scissors:")

您自己定义的函数应该以同样的方式处理。


响应编辑:在 results 内创建局部变量将无济于事。调用函数的代码需要存储返回值。 (人们设计的语言按照你试图让它工作的方式工作。结果是程序的不相关部分会相互影响对方的数据,这让人非常头疼。)

【讨论】:

  • 如何让本地返回变量通用?
  • @Keith:查看扩展答案。
  • 谢谢我知道了winner = results (player1, player2)
猜你喜欢
  • 2014-06-30
  • 2011-05-28
  • 1970-01-01
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
相关资源
最近更新 更多