Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么Python列表没有';是否有范围限制(而integer有)?_Python_List_Scope_Int - Fatal编程技术网

为什么Python列表没有';是否有范围限制(而integer有)?

为什么Python列表没有';是否有范围限制(而integer有)?,python,list,scope,int,Python,List,Scope,Int,我的意思是,对于一个整数: >>> a = 2 >>> def b(): ... a += 1 ... >>> b() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in b UnboundLocalError: local variable 'a'

我的意思是,对于一个整数:

>>> a = 2
>>> def b():
...     a += 1
...
>>> b()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in b
UnboundLocalError: local variable 'a' referenced before assignment

在使用
int
的示例中,Python试图在函数
b()
中为
a
赋值,以便将
a
标识为函数中的“局部”变量。由于变量
a
尚未定义,解释器会抛出错误


在具有
列表的示例中,Python没有尝试将任何内容分配给
a
,因此解释器将其标识为“全局”变量。是的,它正在修改列表中的值,但是对名为
a
的列表对象的引用没有更改。

它们具有完全相同的限制,如果您执行了类似的操作,您会看到:
a+=[1]
。感谢您的回答!这是因为integer不是一个对象,所以python不能引用它,所以我们不能仅仅增加它?那么python中的整数是什么?只是称为值类型还是?@BillyChen不,这根本不是原因。整数也是对象。对于混淆,很抱歉,第一个示例不起作用的唯一原因是您正在重新定义
a
。我已经整理了我的答案,以防混淆。Python中的所有内容都是对象:加油。谢谢@jornsharpe和Xteven,我将继续学习了解更多!
>>> a = [0]
>>> def b():
...     a[0] += 1
...
>>> b()
>>> a[0]
1