规则: 全局变量全部大写,局部变量全部小写
"""
全局变量:
1.py文件的任何位置都可以调用
局部变量:
1.子程序中定义
2.只能在子程序中调用
"""
name = "alex"
def test():
x = 1 # 局部变量
print(x)
print(name) # 全局变量, 任何位置都可以调用.
test()
# 局部变量覆盖全局变量
def test1():
name = "cql"
print(name) # 这地方name为局部变量
test1()
print(name)
# global 声明使用全局变量
def test2():
global name # 该声明表示下面对name的操作都是对全局变量name的操作.
name = "cql"
print(name) # 这地方name为局部变量
test2()
print(name)
fruit = "apple"
def get_fruit1():
fruit = "peer"
print(fruit)
def get_fruit2():
fruit = "banana"
print(fruit)
get_fruit1()
get_fruit2()
fruit = "apple"
def get_fruit1():
global fruit
print(fruit) # 打印全局变量
def get_fruit2():
global fruit
fruit = "banana" # 对全局变量进行修改
print(fruit)
get_fruit1()
get_fruit2()
print(fruit)
fruit = "apple"
def get_fruit1():
print(fruit)
# 若函数中没有global声明,优先取局部变量,没有的情况下,只能取全局变量,只能读取,不能赋值(但对可变类型,可以对内部元素进行操作)
# 若函数中有global声明,变量就是全局的变量,可读取&赋值
get_fruit1()
若函数无global变量自
- 有声明变量
- 无声明变量
fruit = ["apple", "ha"]
def get_fruit1():
global fruit
print(fruit)
def get_fruit2():
fruit.append("hah2") # ['apple', 'ha', 'hah2'] 可以修改,不可以赋值.
print(fruit)
get_fruit1()
get_fruit2()
# 有声明局部变量
fruit = ["apple", "ha"]
def get_fruit():
fruit = "banana"
print(fruit)
# 无声明局部变量
fruit = ["apple", "ha"]
def get_fruit():
fruit.append("peer")
print(fruit)
# 错误实例
"""
fruit = ["apple", "ha"]
def get_fruit():
fruit = "aa"
global fruit
print(fruit)
"""
函数和函数之间进行嵌套
# 嵌套
NAME = "peer"
def get1():
name= "head"
print(name)
def get2():
print("get2")
def get3():
print("get3")
get2()
print("tail")
get1()
# nonlocal 上一级的变量