python 基础 4.0 函数的一般形式及传参
hit lin style 参数 odi 你好 value weight 入参
#/usr/bin/python
#coding=utf-8
#@Time :2017/10/23 15:58
#@Auther :liuzhenchuan
#@File :函数的一般形式.py
##函数的定义
#x y 为形参 ,sum(6,4)叫实参
defsum(x,y):
print{‘x = 0‘.format(x)}
print{‘y = 0‘.format(y)}
returnx + y
m = sum(6,4)
printm
>>> set([‘x = 0‘])
set([‘y = 0‘])
10
###函数的参数
#给形参b定义一个默认的值
deffuncA(a,b=0):
printa
printb
funcA(1)
>>> 1
0
#如果实参传入的时候,判定了b的值,那么b优先选择传入的实参,当b没有值时,才会选择默认的值
deffuncA(a,b=0):
printa
printb
funcA(10,30)
>>> 10
30
##参数为tuple
#a对应1,b对应2,*c对应剩下的元组列型
deffuncD(a,b,*c):
printa
printb
print‘length of c is :%d‘%len(c)
printc
funcD(1,2,3,4,5,6)
>>> 10
1
2
length of c is :4
(3, 4, 5, 6)
#通过解包的形式传入元组
deffuncD(a,b,*c):
printa
printb
print‘length of c is :%d‘%len(c)
printc
# funcD(1,2,3,4,5,6)
#通过解包的形式传入元组
test = (‘hello‘,‘world‘)
funcD(1,2,*test)
>>> 1
2
length of c is :2
(‘hello‘, ‘world‘)
##传入参数为字典,两个星号b代表的是字典,x是字典的键值,b[x]是字典的value.100是a的实参;x=‘hello‘,y=‘nihao‘ 是b的实参,是给a和b赋值
所以不能写成 a=‘hello‘,b=‘nihao‘,也就是不能再用a和b当作实参。
deffuncF(a,**b):
printa
printb
forxinb:
printx + ":"+str(b[x])
funcF(100,x=‘hello‘,y=‘nihao‘)
>>> {‘y‘: ‘nihao‘, ‘x‘: ‘hello‘}
y:你好
x:hello
#还可以通过解包的形式,传入字典
deffuncF(a,**b):
printa
printb
forxinb:
printx + ":"+str(b[x])
# funcF(100,x=‘hello‘,y=‘你好‘)
#还可以通过解包的形式传入字典
args = {‘1‘:‘a‘,‘2‘:‘b‘}
funcF(100,**args)
>>> {‘1‘: ‘a‘, ‘2‘: ‘b‘}
1:a
2:b
python 基础 4.0 函数的一般形式及传参
hit lin style 参数 odi 你好 value weight 入参
原文:http://www.cnblogs.com/lzcys8868/p/7768804.html
来源: http://www.bubuko.com/infodetail-2376340.html