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

我的python学习之路----函数

2011-09-06 13:47 721 查看
1、python函数不能像perl一样,声明与定义可以分开,必须在使用前先定义

定义时使用def function_name:

def ll():

if _debug==True:

import pdb

pdb.set_trace()

print("hello")

ll()

也可以先在其它文件中先定义,然后使用import导入

2、函数参数

def ll(a, b):

3、默认参数

def ll(a,b = 3):

4、关键字参数

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):


5、以列表为参数

>>> lis = [1,2,3,4]

>>> def add(elements):

for ele in elements:

sum = ele +sum

return(sum)

>>> def add(elements):

sum=0

for ele in elements:

sum = ele +sum

return(sum)

>>> add(lis)

10

6、可变参数

def add(*args):

*args之后只能再接关键字参数

args实际上是一个元组

>>> add(lis)

10

>>> def add1(*args):

print(args)

>>> add1(3,4,5,6)

(3, 4, 5, 6)

7、字典参数

字典参数只能位于所有参数的最后,如:

def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
keys = sorted(keywords.keys())
for kw in keys:
print(kw, ":", keywords[kw])


It could be called like this:

cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")


and of course it would print:

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch


参考
http://docs.python.org/dev/tutorial/controlflow.html#defining-functions
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: