十一、python函数学习

1.    定义函数

def   函数名(形参):

    函数体

    return  xxx--------其下面的内容不再执行

---------------------------------------------------------------------------------------------------------------

2.执行函数

      函数名(实参)

---------------------------------------------------------------------------------------------------------------

3.形参,实参(默认按照顺序)

---------------------------------------------------------------------------------------------------------------

4.执行形参传入实参,可不按照顺序

---------------------------------------------------------------------------------------------------------------

5.函数可以有默认参数

---------------------------------------------------------------------------------------------------------------

6.动态参数  
#动态参数一,类型为元祖,传的参数为元祖的元素
def f1(*a):
print (a,type(a))
f1(123,234,[456123789],{1:2})
#动态参数二,类型为字典,传入的参数为字典的键值对
def f1(**a):
print (a,type(a))
f1(k1=123,k2=456)
#万能动态参数-------一*较**在前
def f1(*a,**p):
print (a,type(a),type(p))
f1(123,234,[456123789],{1:2},k1=123,k2=456)
---------------------

    ((123, 234, [456123789], {1: 2}), <type 'tuple'>)
    ({'k2': 456, 'k1': 123}, <type 'dict'>)
    ((123, 234, [456123789], {1: 2}), <type 'tuple'>, <type 'dict'>)

---------------------------------------------------------------------------------------------------------------

7.为动态参数传入字典,列表

def f1(*args):
print (args,type(args))
l1=[11,22,33,44]
f1(l1)
f1(*l1)
------------------------

 (([11, 22, 33, 44],), <type 'tuple'>)
 ((11, 22, 33, 44), <type 'tuple'>)

------------------------

def f2(**args):
print (args,type(args))
l1={"k1":"123"}
f2(l1=l1)
f2(**l1)
-------------------------

   ({'l1': {'k1': '123'}}, <type 'dict'>)
   ({'k1': '123'}, <type 'dict'>)

---------------------------------------------------------------------------------------------------------------

8.全局变量,局部变量

P="chushujin"
def func1():
#局部变量
a=123
global P #加上此关键词后,全局变量就会被修改,否则不会被修改
print (a)
P="zhangyu"
def func2():
print (P)
func1()
func2()
----------------------

   123
 zhangyu

猜你喜欢

转载自www.cnblogs.com/chushujin/p/9350874.html