In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body(即便没用到), it’s assumed to be a local unless explicitly declared as global.
https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python
>>> from math import pi
>>> pi
3.141592653589793
>>> def s():
if pi:
print('if pi')
else:
print('in else')
>>> s()
if pi
>>> def s():
if pi:
print('if pi')
pi=3
elif pi<3:
print('elif pi<3')
>>> s()
Traceback (most recent call last):
File "", line 1, in
s()
File "", line 2, in s
if pi:
UnboundLocalError: local variable 'pi' referenced before assignment
Python变量作用域解析
本文详细解释了Python中局部变量与全局变量的区别及使用规则,包括变量声明为global的情况以及未声明时默认行为的说明,并通过示例展示了如何正确处理变量的作用域。
983

被折叠的 条评论
为什么被折叠?



