所谓双鱼

导航

 

1、常量

money=500 #常量,一个不变的值
def test(consume):
    return money-consume
money=test(200)
print(money)

在其他函数中使用原来的函数

money=500 #常量,一个不变的值
def test(consume):
    return money-consume
def test1(moeny):
    return test(money)+money
money=test1(money)
print(money)

2、全局变量

name='测试'    #全局变量
def sayname():
    print(name)

在函数外定义的变量,在函数中使用

全局变量不安全,所有人都可以去改,并且会一直占用内存

3、局部变量

name='测试'    #全局变量
def sayname():
    name='刘佳'   #局部变量
    print('name1',name)
sayname()
print('name2',name)

输入结果为:

name1 刘佳
name2 测试

在函数体内有name变量,所以函数体内变量就进行了变化,且这个变化只是在函数有用,所以是局部变量,出了该函数,name变量还是在函数外定义的

4、函数体内修改全局变量

name='测试'
def sayname():
    global name   #函数内修改全局变量
    name='刘佳'
    print('name1',name)
sayname()
print('name2',name)

在函数体内使用global将全局变量改为了新的值

5、函数内未定义使用的变量会报错

def test():
    global a
    a=5
def test1():
    c=a+5
    return c
res=test1()
print(res)  #并没有调用函数test,所以会报错,没有定义a

test函数使用了变量a和c,但是a变量没有定义,test函数定义了a函数,可是test1函数并没有调用test,所以会报错

6、多个参数传参

def op_mysql(host,port,username,password,db,charset,sql):
    print('连接数据库')
op_mysql('192.168.1.23',
        3306,'root','123456','jzx','utf-8','select') #多个参数的时候,传参位置要对应

多个参数传参,位置需要对应,也可以使用以下方法,就不用对应位置

def op_mysql(host,port,username,password,db,charset,sql):
    print('连接数据库')
op_mysql('192.168.1.23',
             port=3306,
             username='root',
             password='123456',
             db='jx',
             charset='utf-8',
             sql='select'
             )  #多个参数使用这种方式传参就可以不管顺序

 

posted on 2018-04-19 16:24  所谓双鱼  阅读(168)  评论(0编辑  收藏  举报