zoukankan      html  css  js  c++  java
  • 函数

    1.面向对象--》类

    2.面向过程--》过程--》def

    3.函数式编程--》def

     

    #函数
    def func1():
    '''this is a function'''
    print('in the func1')
    return 0
    #过程(没有return)
    def func2():
    '''this is a process'''
    print('in the func2')

    x=func1()
    y=func2()

    print('the value of x is %s'%x)
    print('the value of y is %s'%y)


    结果:

    in the func1
    in the func2
    the value of x is 0
    the value of y is None

     


     

    def test(x,y,z):
    print(x)
    print(y)
    print(z)

    test(3,4,1) #位置参数:与形参顺序一一对应
    test(y=5,z=7,x=2) #关键自参数:与形参顺序无关
    test(3,z=5,y=7) #位置参数一定要写在关键字参数的前面

    test(4,5,z=8)

    #默认参数特点:函数调用时,默认参数可传可不传
    #作用:默认安装
    def conn(host,port=3306):
    pass

    #接收的参数个数不固定
    #*args:接收n个位置参数,转成一个tuple输出

    def test(*args):
    print(args)

    test(1,2,3,4,5,6)
    test(*[1,2,3,4,5,6])
    test('Alex')

    (1, 2, 3, 4, 5, 6)
    (1, 2, 3, 4, 5, 6)
    ('Alex',)

    #一个固定参数,其余参数不固定
    def test1(x,*args):
    print(x)
    print(args)

    test1(1,2,3,4,5,6,7)

    1
    (2, 3, 4, 5, 6, 7)

    #kwargs:把n个关键字参数,转换成字典的方式
    def test2(**kwargs):
    print(kwargs)
    print(kwargs['name'])
    print(kwargs['age'])
    print(kwargs['sex'])

    test2(name='alex',age=23,sex='F')
    test2(**{'name':'alex','age':23,'sex':'f'})

    {'name': 'alex', 'age': 23, 'sex': 'F'}
    alex
    23
    F


    def test3(name,**kwargs):
    print(name)
    print(kwargs)

    test3('alex')

    alex
    {}

     

    def test4(name,age=23,*args,**kwargs):
    print(name)
    print(age)
    print(args) #args:位置参数
    print(kwargs) #kwargs:关键字参数

    test4('alex',3,23,36,sex='m',hobby='shopping')


    alex
    3
    (23, 36)
    {'sex': 'm', 'hobby': 'shopping'}


    school='bupt'      #全局变量
    def change_name(name):
    school='cnn of bupt' #局部变量
    print("before change:",name,school)
    name='Alex' #局部变量
    print("after change:",name)

    name='alex'
    change_name(name)
    print(name)
    print('school:',school)

    before change: alex cnn of bupt
    after change: Alex
    alex
    school: bupt

    局部变量不能使全局变量的值发生改变的情况:1.字符串 2.单独的整数

    而定义为全局变量的列表和字典,可以通过局部变量更改它们的值。

    name=['alex','xuhang','mengmeng']

    def change_name(name):
    name[0]='ALEX'
    print('in the function',name)

    change_name(name)
    print(name)

    in the function ['ALEX', 'xuhang', 'mengmeng']
    ['ALEX', 'xuhang', 'mengmeng']

  • 相关阅读:
    书面采访时表示,小东西(数据库知识)
    UBuntu经常使用的操作(网络资源)
    hdu 5030 Rabbit's String(后缀数组&二分法)
    Chapter 2 User Authentication, Authorization, and Security(4):限制SA帐户管理权限
    编程算法
    iOS:WebKit内核框架的应用与解析
    协议森林03 IP接力赛 (IP, ARP, RIP和BGP协议)
    以太网,IP,TCP,UDP数据包分析
    tcp 面向连接
    TCP传输层协议的流程
  • 原文地址:https://www.cnblogs.com/ceceliahappycoding/p/8340834.html
Copyright © 2011-2022 走看看