• python函数


    >>> def func():
    ...         print("this is a func()")
    ...
    >>> func()
    this is a func()

    多个参数:

    >>> def add(a,b):
    ...     print(a+b)
    ...
    >>> add(3,5)
    8

    默认参数:

    >>> def add(a,b=3):
    ...         print(a+b)
    ...
    >>> add(3,4)
    7
    >>> add(3)
    6

    不定长参数:

    >>> def func1(*arg):
    ...         print(arg)
    ...         print(type(arg))
    ...
    >>> func1(1,'a',5)
    (1, 'a', 5)
    <class 'tuple'>

    >>> def func2(**arg):
    ...         print(arg)
    ...         print(type(arg))
    ...
    >>> func2(a=1,b=4,name="xiaofan")
    {'b': 4, 'name': 'xiaofan', 'a': 1}
    <class 'dict'>

    >>> def func2(*arg,**args):
    ...         print(arg)
    ...         print(type(arg))
    ...         print(args)
    ...         print(type(args))
    ...
    >>> func2('a',1,2,3,x=1,y=10)
    ('a', 1, 2, 3)
    <class 'tuple'>
    {'x': 1, 'y': 10}
    <class 'dict'>
    >>> func2('a',1,2,3)
    ('a', 1, 2, 3)
    <class 'tuple'>
    {}
    <class 'dict'>
    >>> func2(x=1,y=10)
    ()
    <class 'tuple'>
    {'x': 1, 'y': 10}
    <class 'dict'>

    函数返回值:return

    >>> def func0():
    ...         return 1,2
    ...
    >>> func0()
    (1, 2)
    >>> print(type(func0()))
    <class 'tuple'>

    >>> def func1(*arg,**args):
    ...         return arg,args
    ...
    >>>
    >>> a,b=func1(1,2,3,x=1,y=2)
    >>> a
    (1, 2, 3)
    >>> b
    {'x': 1, 'y': 2}
    >>>

    显式修改函数返回值:

    >>> def func1(*arg,**args):
    ...          return list(arg),args
    ...
    >>> a,b=func1(1,2,3,x=1,y=2)
    >>> a
    [1, 2, 3]
    >>> b
    {'x': 1, 'y': 2}

    函数多态:

    >>> def add(a,b):
    ...         print(a+b)
    ...
    >>> add(1,2)
    3
    >>> add("xaiofan","b")
    xaiofanb
    >>> add([1,2,3],['x','y','z'])
    [1, 2, 3, 'x', 'y', 'z']

    函数作用域:

    >>> x = 1
    >>> def f():
    ...         x = 10
    ...         print("it is inside x:",x)
    ...
    >>> f()
    it is inside x: 10

    global语句的意义是用来在函数内部修改全局变量。

    >>> x = 10
    >>> def f1():
    ...         global x
    ...         x = 100
    ...         print(x)
    ...
    >>> f1()
    100
    >>> print(x)
    100

  • 相关阅读:
    大四实习几个课题
    Keil 4 与Proteus 7.8联调
    局域网共享
    win 8.1 网卡
    路由器无线桥接 router wireless bridge
    系统对话框alert-prompt-confirm
    处理浏览器兼容性
    pageX--clientX--scrollLeft-clientLeft-offsetWidth
    处理注册事件的兼容性问题
    处理innerText的兼容性问题
  • 原文地址:https://www.cnblogs.com/fanxuanhui-linux/p/5836874.html
Copyright © 2020-2023  润新知