zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python语言学习之变量那些事:局部变量、全局变量的使用方法之详细攻略

Python方法学习语言变量 详细 攻略 那些
2023-09-14 09:04:48 时间

Python语言学习之变量那些事:局部变量、全局变量的使用方法之详细攻略

 

 

 

 

目录

变量那些事

1、判断变量test,是否已经被定义

2、全局变量和局部变量


 

 

 

 

 

变量那些事

1、判断变量test,是否已经被定义

#判断变量test,是否已经被定义
res1 = 'test' in locals().keys()
res2 = 'test' in dir()
res3 = 'test' in vars().keys()
print(res1,res2,res3)  # 变量test暂时还没有定义,返回False
test = ""  # 定义变量test
res4 = 'test' in locals().keys()
res5 = 'test' in dir()
res6 = 'test' in vars().keys()
print(res4,res5,res6)  # 变量test已经被定义了,返回True

False False False
True True True

 

2、全局变量和局部变量

(1)、定义内部函数修改外部的全局变量

def Change_global(): #WeChat_sign02变量更改WeChat_sign01变量
    WeChat_sign02=0
    global WeChat_sign01
    if WeChat_sign02==0:
        WeChat_sign01=1

WeChat_sign01=0
Change_global()
print(WeChat_sign01)