python--function

Source: Internet
Author: User

1. About function Parameters: default parameters, key parameters, non-fixed parameters (1) Default parameters
def stu_register(name, age, country=‘China‘):    print(‘注册信息‘.center(30‘-‘))    print(‘姓名:‘, name)    print(‘年龄:‘, age)    print(‘国籍:‘, country)stu_register(‘李白‘40)stu_register(‘李白‘40‘大唐‘)

country=‘China‘Default parameters, the default parameters must be placed after the default parameters to meet the syntax requirements, call the function when the default parameters can not be passed, if passed, the passed parameters will prevail

(2) Key parameters

Under normal circumstances, to the function of the parameter is transmitted in sequence, do not want to be transmitted sequentially, you can use the key parameters, that is, the parameter is specified when the parameter name.

Key parameters must be placed after the position parameter.

def stu_register(name, age, country=‘China‘):    print(‘注册信息‘.center(30‘-‘))    print(‘姓名:‘, name)    print(‘年龄:‘, age)    print(‘国籍:‘, country)stu_register(‘小钻风‘, country=‘赛博坦‘, age=25) stu_register(‘奇异博士‘, country=‘赛博坦‘25# 这种方式是错误的 
(3) Non-fixed parameters

When defining a function, you are not sure how many parameters are passed in, and you can use non-fixed parameters

def fun1(*args):    print(args)fun1(‘李白‘22‘诗人‘)fun1(‘鸣人‘25‘螺旋丸‘‘雏田‘‘疾风传‘)#打印结果:#(‘李白‘, 22, ‘诗人‘)#(‘鸣人‘, 25, ‘螺旋丸‘, ‘雏田‘, ‘疾风传‘)

**kwargs multiple incoming parameters into a dict form

def***kwargs):  # *kwargs 会把多传入的参数变成一个dict形式    print(name, age, args, kwargs)fun2(‘我爱罗‘30)fun2(‘卡卡西‘35‘千鸟‘‘神威‘‘写轮眼‘, students=‘鸣人、佐助、小樱‘, teacher=‘木叶闪光‘)#打印结果:#我爱罗 30 () {}#卡卡西 35 (‘千鸟‘, ‘神威‘, ‘写轮眼‘) {‘students‘: ‘鸣人、佐助、小樱‘, ‘teacher‘: ‘木叶闪光‘}
2. Local Variables
="大白"def change_name():    ="小黑"    print(‘函数内部打印:‘, name)change_name()print(‘函数外部打印:‘, name)#打印结果:#函数内部打印: 小黑#函数外部打印: 大白

Conclusion: variables defined at the level of code outside the function, that is, global variables, are globally available, variables defined inside the function, i.e. internal variables, can only be used locally.

If both global and local variables have a variable called name, the order in which the function is used to look for variables is the nearest principle, from the Inside Out

Also, in Python, the value of the global variable name cannot be changed in this way

How to modify a global variable in a function

=‘李白‘def fun():    global#global name的作用就是要在函数里声明全局变量name ,意味着最上面的name = "Alex Li"即使不写,程序最后面的print也可以打印name    =‘杜甫‘    print(‘函数内部:‘, name)fun()print(‘函数外部:‘, name)#打印结果:#函数内部: 杜甫#函数外部: 杜甫

In addition a small tail is added:

= [‘鸣人‘‘佐助‘‘小樱‘]def change():    names[0=‘六代目火影‘    print(‘函数内:‘, names)change()print(‘函数外:‘, names)#打印结果:#函数内: [‘六代目火影‘, ‘佐助‘, ‘小樱‘]#函数外: [‘六代目火影‘, ‘佐助‘, ‘小樱‘]#内容被改了,因为列表里面存的是内存地址,是可以修改的,类似于,元祖本身不可修改,但是元祖中包含的列表内容是可以修改的。

Lists, dictionaries, collections, objects can be modified, including ganso of types such as lists. Non-modifiable with string, number, Boolean

3. Function nesting
    • Functions can be defined inside the function, and all functions must be called before they are executed.
def fun1():    print(‘鸣人‘)    def fun2():        print(‘博人‘)    #fun2 只能在 fun2函数定义后才可以调用    #fun2 只能在 fun1 中调用,在fun1 外面无法调用#鸣人#博人
4. Scope
#python 中 函数就是一个作用域=18def fun1():    =73    def fun2():        print(age)    return fun2print(fun1())  # 打印结果:(函数地址)<function fun1.<locals>.fun2 at 0x00000000027A8AE8>= fun1()val()  # 打印结果:73  此处打印的部署18,是73,说明代码定义完成后,作用域已生成,作用域链向上查找。

Deployment 18, which is printed here, is 73, stating that after the code definition is complete, the scope has been generated and the scope chain is looked up.

Instead: When the FUN2 function is returned, it is called outside, it becomes global, and the inner function is still executed internally.

5. Anonymous functions

You do not need to use DEF to define a function that is created directly using lambda and cannot access parameters outside of its own argument list or global namespace.

=lambda* y  # 声明一个匿名函数print(f(2,3# 6

The above code : the previous x, Y is the parameter: the back is the return content

    • Anonymous functions can be used in conjunction with other functions, such as filter, map, etc.
    • When a program is used once and does not need to define a function name, anonymous functions can save space in the variable definition in memory
    • There is usually a row of expressions that must have a return value, but no return
    • Can have no parameters, can have multiple parameters, allow the parameter to have a default value
#无参匿名函数>>>F= Lambda:True>>>F ()True#带参匿名函数LambdaX:x**3 #一个参数LambdaX,y,z:x+Y+Z#多个参数LambdaX, y=3: X*Y#允许参数存在默认值>>>C= LambdaX, y=2: X+Y#使用了默认值>>>CTen)#如果不输入, the default value of 2 is used A

Give me another chestnut:

=range(10)print(list(map(lambda x:x*2#打印结果: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

map(func, *iterables), map uses each number in the data as an argument, passes in the anonymous function, and returns, eventually returning a list, which we cast with List (), and the address of the list that was printed before the conversion.

python--function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.