python函数不会返回值

时间:2015-02-01 21:43:55

标签: python function python-3.x

我是python的新手,正在尝试制作简单的纸张,摇滚,剪刀游戏。无论我在我的内心做什么" lame"函数局部变量" y"不会被分配给全局变量" var1"或" var2"。我尝试过使用return但无法使用任何东西。

#get input (paper, rock scissors from players)
play1 = input("player 1:")
play2 = input("player 2:")

#set value of players score to 0
val1 = 0
val2 = 0

def lame(x, y):
#set value of p, r, s choice, to 1, 2 or 3 
    if x in("p","P"):
        y = y + 1
    elif x in("r","R"):
        y = y + 2
    elif x in("s","S"):
        y = y + 3
    else:
        print("your value was not p, r or s")

#run function "lame" and pass in "play1" choice and 
#retrieve "val1" for that choice
lame(play1, val1)
lame(play2, val2)

def win(x, y):
#subtracts value of players choices to find winner
    dif = x - y
    if dif == 0:
        print("tie game")
    elif dif % 3 == 1:
        print("player 2 wins")
    elif dif % 3 == 2:
        print("player 1 wins")
    else:
        print("logic error")

#call function "win" and pass in results of their choices
win(val1, val2)

2 个答案:

答案 0 :(得分:5)

错误的 执行此操作的方式:

val1 = 0

...

def lame(x):
    global val1
    val1 = result_of_some_calculations_to_do_with(x)

正确 的方式:

def lame(x):
    return result_of_some_calculations_to_do_with(x)

val1 = lame(x)

与L3viathan在评论中所说的相反,Python DOES通过引用传递变量,但不通过引用来分配变量。换句话说:

x = 3 # x is 3
y = x # x is 3, y is 3, x is y
y = 4 # x is 3, y is 4, y is REASSIGNED so y is not x

这基本上就是你要做的事情,将val1传递给你的lame函数并将其重新绑定为y

val1 = 0 # val1 is 0

def lame(x, y):
    # y is val1
    y = some_calculations_to_do_with(x)
    # y has been REASSIGNED so y is not val1

当你传递像可变列表这样的对象时这很重要(例如,它们可以更改,而不是Python中的不可变对象行intstr)。

val1 = list() # val1 is an empty list

def lame(x,y):
    y.append(x) # append x to y, DO NOT REASSIGN y TO ANYTHING ELSE

lame(1, val1) # val1 is [1]

答案 1 :(得分:0)

在我发布这个问题之后,我发现了这个问题,并且可以确认亚当史密斯所说的话。

以下是为了让它正常工作而更改的代码:

def lame(x): 
    #set value of p, r, s choice to 1, 2 or 3 
    if x in("p","P"):
        return 1
    elif x in("r","R"):
        return 2
    elif x in("s","S"):
        return 3
    else:
        print("your value was not p, r or s")

#run function "lame" and pass in play1 choice and 
#retrive val1 for that choice
val1 = lame(play1)
val2 = lame(play2)