变量作用域

c = 50 # 全局变量(全局变量区)

def add(x,y):
    c = 100 # 局部变量(栈区,出栈即销毁)
    c = x + y 
    print(c)

add(1,2) #3
print(c) #50
def add(x,y):
    c = x + y
    print(c)

add(1,2) #3
print(c) #50
3
Traceback (most recent call last):
  File "/Users/scottxiong/Desktop/end/python/func/f1.py", line 6, in <module>
    print(c) #50
NameError: name 'c' is not defined

理解局部变量,全局变量只是个相对的概念

def demo():
    c = 50 
    for i in range(0,9):
        c += 1
    print(c)

demo()

像c、c++、java,如果在for循环外面引用for循环内部的变量会报错,但是python却可以,为什么?

因为python函数是有作用域,但是for循环没有作用域

def demo():
    c = 50 
    for i in range(0,9):
        a = 'a'
        c += 1
    print(c)
    print(a)
demo()
59
a

results matching ""

    No results matching ""