<span style="font-size:14px;"># -*- coding: gbk -*-
#python进阶探究
a,b = 0,1
while b < 100:
print str(b)+',',
a,b = b,a+b
print("-"*40)
if b == 10:
pass #这句话什么都不做
#定义一个方法
def fib(n):
a,b = 0,1
while b < n:
print(str(b),',')
a,b = b,a+b
fib(2000)
print("-"*40)
#函数可以直接指定
f = fib
f(100)
print("-"*40)
#不定长参数
'''
python提供了两种特别的方法来定义函数的参数:
1. 位置参数 *args, 把参数收集到一个元组中,作为变量args
def show_args(*args): => how_args("hello", "world")
2. 关键字参数 **kwargs, 是一个正常的python字典类型,包含参数名和值
def show_kwargs(**args): = > show_kwargs(foo="bar", spam="eggs")
'''
def cheeseshop(kind,*arguments,**keywords):
print("-- Do you have any", kind, "?")
print(r"-- 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])
cheeseshop("Limburger", "It’s very runny, sir.",
"It’s really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
print("-"*40)
#字典可以用** 操作符实现关键字参数
def parrot(voltage, state='a stiff', action='voom'):
print("-- This parrot wouldn’t", action)
print("if you put", voltage, "volts through it.")
print("E's", state, "!")
d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d)
#3.2.3才支持此种写法
'''
def concat(*args,sep="/"):
return sep.join(args)
concat("earth", "mars", "venus")
concat("earth", "mars", "venus", sep=".")
print("-"*40)
'''
</span>
Python不定参数自定义函数
最新推荐文章于 2024-07-21 21:29:46 发布