常量、局部变量、全局变量

局部变量:函数里面定义的变量。
全局变量:公共变量,都可以使用的变量。
常  量:不变的值
PS:有好多重复的代码就要考虑定义成函数来使用

脑筋急转弯1:

money = 500

def test(consume):
return money - consume

def test1(money):
return test(money) + money

money = test1(money)
print(money)
# PS:500-500+500
test1传入500,又去调用test结果就是又把500传参给了consume

脑筋急转弯2:

def test():  

    global a
a = 5

def test1():
c = a + 5
return c
res = test1()
print(res)
#PS结果会报错,因为没有调用test()(函数调用才会执行)

全局变量案例:
name='泄洪'       #全局变量
def syzName():
global name #改全局变量:要先声明
name='刘雯' #局部变量
print('name1:',name )
syzName()
print('name2:',name)
PS:全局变量不安全(谁都可以改),它会一直占着内存直到整个程序结束


案例二:(连接数据库方式)
def op_mysql(host,prot,sername,password,db,sql):
print('连接数据库')
op_mysql(sql='celect*from user',
prot='xxx',
password='123456',
db='sdf',
host='127.0.0.1'
)
PS:不用按顺序填写参数想到啥写啥
 

猜你喜欢

转载自www.cnblogs.com/cwl-bj/p/9615216.html