python-11 函数定义、传参、缺省值、可变参数
函数
def add(x,y):
print(x,y)
return x + y
函数参数
缺省值参数要往后放
可变参数
def sum1(*iterable): # 可变形参,接收 0-n 个
print(type(iterable), iterable)
s = 0
for x in iterable:
s += x
return s
可变参数混合使用
keyword-only
def fn5(x, y, z=100, *args, m, n=200, o, **kwargs):
pass
参数解构
一个 * 解开一维(一层)
两个 ** 解 字典
import random
def max_min(x,y,*args):
print(x,y,args)
return (max(x,y,*args), min(x,y,*args))
max_min(*(random.randint(100, 110) for i in range(random.randint(2, 10))))
print(max_min(*(random.randint(100, 110) for i in range(random.randint(2, 10)))))
print(1,2,3,4, sep='\n')
def get_double_vals():
max_ = min_ = None
while True:
nums = input('>>').replace(',',' ').split()
if not nums:
break
nums = [int(x) for x in nums]
if max_ is None:
max_ = min_ = nums[0]
max_ = max(max_, *nums)
min_ = min(min_, *nums)
print(max_, min_)