Python函数实参操作

#1、位置参数:按照从左到右的顺序定义的参数
位置形参:必选参数
位置实参:按照位置给形参传值

#2、关键字参数:按照key=value的形式定义的实参
无需按照位置为形参传值
注意的问题:
1. 关键字实参必须在位置实参右面
2. 对同一个形参不能重复传值

#3、默认参数:形参在定义时就已经为其赋值
可以传值也可以不传值,经常需要变得参数定义成位置形参,变化较小的参数定义成默认参数(形参)
注意的问题:
1. 只在定义时赋值一次
2. 默认参数的定义应该在位置形参右面
3. 默认参数通常应该定义成不可变类型

#4、可变长参数:
可变长指的是实参值的个数不固定
而实参有按位置和按关键字两种形式定义,针对这两种形式的可变长,形参对应有两种解决方案来完整地存放它们,分别是*args,**kwargs

#5、命名关键字参数:*后定义的参数,必须被传值(有默认值的除外),且必须按照关键字实参的形式传递

传递任何数量实参

one = input("input your word: ")
two = input("input your word: ")
three = input("input your word: ")
def numbers(*nums):
	print(nums)
numbers(one, two, three)
#结果:
input your word: one
input your word: two
input your word: three
('one', 'two', 'three')

Process finished with exit code 0

Tips: 这里使用的是python3.x

结合使用固定参数与任何数量参数使用

def make_pizza(size, *toppings):
	print("Making a " + str(size) " and this is your pizza info: ")
	for topping in toppings: 
		print("- " + topping)
make_pizza(16, 'one')
make_pizza(17, 'two', 'three')\
#结果
[root@jensen f_rubbish]# python3 while.py 
Making a 16 and this is your pizza info: 
- one
Making a 17 and this is your pizza info: 
- two
- three

使用任意数量的关键字实参

def user_profile(first, last, **user_info):
	""""创建一个字典,其中包括我们知道的有关用户的一切"""
	profile = {} ###这是个字典
	profile['first'] = first
	profile['last'] = last
	for key,value in user_info.items()
		profile[key] = value
	return profile
user_info = user_profile(name, sex, school='china', location='sz')
"""可以以这种形式进行写入,固定的参数只有两个(first,last)"""
print(user_info)
name = input("input name: ")
sex = input("input sex: ")

意味着只有"name" and “sex” 这两个实参是可变的。
暂时做了这些研究后续有补充的会继续一一补上…

发布了39 篇原创文章 · 获赞 13 · 访问量 3354

猜你喜欢

转载自blog.csdn.net/qq_30036471/article/details/102155484