gpt4 book ai didi

Python函数问题

转载 作者:太空宇宙 更新时间:2023-11-03 19:17:12 24 4
gpt4 key购买 nike

嗨,我是一名正在学习 Python 的初学者,我在一本书中偶然发现了这个示例,由于某种原因,当我自己尝试相同的代码时,我没有收到相同的输出?请帮忙...

def tester(start):
state = start
def nested(label):
nonlocal state
print(label, state)
state += 1
return nested

>>> F = tester(0)
>>> F('spam')
spam 0
>>> F('ham')
ham 1
>>> F('eggs')
eggs 2

每次运行该函数时,我的结果都不会增加 + 1,这本书有问题吗?

最佳答案

Works for me 。你确定你使用的是Python 3吗? nonlocal 是 python 3 的一项功能,在 python 2.x 中无法工作。

关于Python函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10978576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com