python入门-函数传参

常规定义函数:

def fun():
	pass

笔记
传参相关

# 入参定义为不可变量
def func1(a=None):
	a = []
	a.append('test')
	return a
# 入参定义为可变量
def func2(a=[]):
	a.append('test')
	return a

# 调用2个函数
func1()
['test']
func1()
['test']

func2()
['test']
func2()
['test', 'test']
# 传多个参数
def func(*a):
	return a  # a的type是tuple

# 调用
# 1
func(1,2)
(1, 2)

# 2
num = [1, 2, 3]
func(*num)
(1, 2, 3)
# 传字典
def func3(**kw):
	print(kw)
    print(type(kw))
    
# 调用
func3()
{}
<class 'dict'>

func3(a=1)
{'a': 1}
<class 'dict'>

func3(a=1, b=2, c=3)
{'a': 1, 'b': 2, 'c': 3}
<class 'dict'>

dict1 = {'a':1, 'b':2}
func3(**dict1)
{'a': 1, 'b': 2}
<class 'dict'>
# 传固定字典,固定名称为a,b,前面需要用*分割
def func4(*, a, b):
    print(a)
    print(b)
    
# 调用
# 1、不填固定key值,报错
func4(1, 2)
Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2024.1.4\plugins\python-ce\helpers\pydev\pydevconsole.py", line 364, in runcode
    coro = func()
           ^^^^^^
  File "<input>", line 1, in <module>
TypeError: func4() takes 0 positional arguments but 2 were given

# 2、不填全部key值,会报错
func4(a=1)
Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2024.1.4\plugins\python-ce\helpers\pydev\pydevconsole.py", line 364, in runcode
    coro = func()
           ^^^^^^
  File "<input>", line 1, in <module>
TypeError: func4() missing 1 required keyword-only argument: 'b'

# 3、填了全部key值,正常输出
func4(a=1, b=2)
1
2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值