为什么“total”值在多次运行时不会更新?

2024-05-17 18:17:21 发布

您现在位置:Python中文网/ 问答频道 /正文

“total”会在我第一次运行函数时更改,但不会返回total的新值,所以当我再次运行它时,它的值与我第一次运行它之前的值相同?你知道吗

total = card[1].value

def hit(total):
    #print (str(hit.counter))
    print("You draw the " + string(card[hit.counter]))
    total = total + card[hit.counter].value
    print(str(total))
    hit.counter += 1
    return hit.counter
    return total

函数在此处调用:

choice = raw_input("\n1. Hit\n2. Stay\n")
    if (choice == "1"):
        hit(total)

这是同样的问题

x = 1
def call(x):
    x = x + 1
    print x
    return x
call(x)

每次运行时,它都会输出2,并且不会更新“x=x+1”的新值


Tags: 函数youreturnvaluedefcountercallcard
3条回答

This is the same problem simplified

x = 1
def call(x):
    x = x + 1
    print x
    return x
call(x)

然后呢?你期望什么?全局x将在最后一行之后自动更新吗?抱歉,事情不是这样的。在call()中,x是一个局部名称,与外部全局x完全无关。当您调用call(x)时。如果要更新全局x,必须明确地重新绑定它:

def call(x):
    x = x + 1
    print x
    return x

x = 1
x = call(x)

我强烈建议你读一下:https://nedbatchelder.com/text/names.html

编辑:

"I want it so when I run the hit() function a second time, the total is the total of the last time I used it"

你的责任(我是说调用这个函数的代码的责任)是把总数存储在某个地方,然后在下一次调用时传回:

# Q&D py2 / py3 compat:
try: 
    # py2
    input = raw_input
except NameError:
    # py3
    pass 

def call(x):
    x = x + 1
    print(x)
    return x


x = 1
while True:
    print("before call, x = {}".format(x))
    x = call(x)
    print("after call, x = {}".format(x))
    if input("play again ? (y/n)").strip().lower() != "y":
        break

您有一个名为total的全局变量。还有一个名为total的局部变量。你知道吗

在函数中,局部total阴影外部全局变量,因此更新到函数中的total只会更新局部变量。你知道吗

total = card[1].value

def hit(total):
    print("You draw the " + string(card[hit.counter]))
    total += card[hit.counter].value
    hit.counter += 1
    return hit.counter, total

hit_counter, total = hit(total)

正如巴辛加所说,你没有达到总回报。如果希望返回多个值,可以如上所述执行,并在赋值中如上所示使用它们。你知道吗

相关问题 更多 >