您的位置:首页 > 编程语言 > Python开发

python之路(二)函数

2016-01-18 10:33 507 查看
python 函数

1. def 定义函数关键字;
2. 函数名,日后通过函数名调用该函数;
3. 函数声明,不自动执行;
4. 函数的参数;
5. 函数的返回值;

返回值:
1. 未明确指定返回值,返回none;
2. 返回值可以赋值给某个变量;
3. 返回值可以是变量也可以是数据结构。

参数:
1. 形参
2. 实参
3. 函数可以定义多个参数
默认参数:
1. 不传,则使用默认值;
2. 传参,则覆盖默认值。
动态参数:
1. 接收多个参数,传序列时;
2. 内部自动构造元祖;
3. 序列,*,避免内部自动构造元祖。

定义函数的格式:

def 函数名 ():
函数内容;函数内容
函数内容;函数内容
函数名() # 执行函数

# 1. 实现取字符串长度的功能 len 函数

a="hellomyteacher"
print len(a)

# 2. 实现字符串的切割 split 函数

a="student"
b=a.split("u")
print b

C:\Python27\python.exe "E:/python-file/learn - python.py"
['st', 'dent']

Process finished with exit code 0

# 自定义函数

def a():
print "hello";print 777
a()

C:\Python27\python.exe "E:/python-file/learn - python.py"
hello
777

Process finished with exit code 0

函数通过 reuturn 来实现让函数返回值得功能

函数的返回值有三种情况:
1. 一个返回值的情况

def test():
i=7
return i
print test()

2. 一个变量存储多个返回值赋予的情况

def test2(i,j):
k=i*j
return (i,j,k)
x=test2(4,5)
print x

C:\Python27\python.exe "E:/python-file/learn - python.py"
(4, 5, 20)

Process finished with exit code 0

3. 多个变量存储多个返回值的情况

def test3(i,j):
k=i*j
return (i,j,k)
x,y,z=test3(4,5)
print x
print y
print z

C:\Python27\python.exe "E:/python-file/learn - python.py"
4
5
20

Process finished with exit code 0

默认参数:
def show(args,arg1='a'):
print(args,arg1)
print(args,arg1)

show(12,arg1='1')
show(12)
12 1
12 1
12 a
12 a

动态参数:
1)
def show(*args,**kwargs):
print(args,type(args))
print(kwargs,type(kwargs))

show(12,34,a=1,b=2)
(12, 34) <class 'tuple'>
{'a': 1, 'b': 2} <class 'dict'>

2)
>>> def show(*args,**kwargs):
... print(args,type(args))
... print(kwargs,type(kwargs))
...
>>> i = [11,22,33]
>>> v = {'k2':1,'k1':2}
>>> show(i,v)
([11, 22, 33], {'k2': 1, 'k1': 2}) <class 'tuple'>
{} <class 'dict'>
>>> show(*i,**v)
(11, 22, 33) <class 'tuple'>
{'k2': 1, 'k1': 2} <class 'dict'>

3)
>>> test = 'name : {0}, pwd : {1}'
>>> test.format('lihongye','pwd1')
'name : lihongye, pwd : pwd1'
>>> test = 'name : {x}, pwd : {y}'
>>> test.format(x='lihongye',y='pwd1')
'name : lihongye, pwd : pwd1'
>>> test_dic = {'x':'lihongye','y':'pwd1'}
>>> test.format(**test_dic)

本文出自 “纷繁中享受技术的简单喜悦” 博客,请务必保留此出处http://51enjoy.blog.51cto.com/8393791/1736057
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: