python函数的返回值到底在哪里?

时间:2014-02-03 01:28:59

标签: python function return conditional

My Rock Paper 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"):
    winner = 1
    return winner

但是如何在功能之外打印“胜利者”?

OLD

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!")

1 个答案:

答案 0 :(得分:5)

返回值不会自动存储在任何位置。您需要手动存储它:

result = results(player1, player2)

if result == 1:
    ...

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

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

您自己定义的功能应该以相同的方式处理。


响应编辑:在results中创建局部变量无济于事。调用该函数的代码需要存储返回值。 (人们设计的语言就像你试图让它工作一样。结果是令人头疼的问题,程序中不相关的部分会踩在彼此的数据上。)