gpt4 book ai didi

Python 全局变量/范围混淆

转载 作者:行者123 更新时间:2023-11-28 19:48:45 26 4
gpt4 key购买 nike

<分区>

我已经开始自学 Python,并注意到与全局变量和范围有关的一些奇怪的事情。当我运行这个时:

x = 2 
y = 3
z=17
def add_nums():
y = 6
return z+y

23 的结果被打印...但是,当我将返回值扩展为:

x = 2 
y = 3
z=17
def add_nums():
y = 6
z = z + y
return z

我在第 6 行收到以下错误:

Local name referenced but not bound to a value.
A local name was used before it was created. You need to define the
method or variable before you try to use it.

我很困惑为什么我会在这里收到错误,因为 z 是全局可访问的。

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