我的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、关键字参数
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、字典参数
字典参数只能位于所有参数的最后,如:
It could be called like this:
and of course it would print:
参考
http://docs.python.org/dev/tutorial/controlflow.html#defining-functions
定义时使用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
相关文章推荐
- Python学习之路-变量、字符串、函数
- python学习之路——函数参数问题
- Python学习之路day3-函数
- python学习之路-第三天-函数
- python学习之路——函数关于可变对象和不可变对象问题
- 王亟亟的Python学习之路(五)-dictionary,set,函数,函数参数
- 我的Python学习之路之基本语法-函数
- Python小白学习之路(十)—【函数】【函数返回值】【函数参数】
- 王亟亟的Python学习之路(五)-dictionary,set,函数,函数参数
- python小菜的学习之路之函数
- 王亟亟的Python学习之路(10)-函数对象的作用域,函数作为返回值,闭包
- Python学习之路-函数
- Python学习之路5 - 函数
- 王亟亟的Python学习之路(10)-函数对象的作用域,函数作为返回值,闭包
- Python小白学习之路(十五)—【map()函数】【filter()函数】【reduce()函数】
- python学习之路-基础篇-函数-day03
- python 学习之路(函数与函数式编程)
- python 学习笔记1(序列;if/for/while;函数;类)
- Python学习之路
- Python学习笔记:函数、模块和包