【每天1分钟】PYTHON基础之函数(函数的参数传递)

【每天1分钟】PYTHON基础之函数(函数的参数传递)

0. 参数定义的完整语法:

func(positional_args, keyword_args, *tuple_nonkw_args, **dict_kw_args)

1. 位置参数

按照参数的位置来进行传参,有几个位置参数在调用的时候就要传几个,否则就会报错

>>> def myFunc(name, age):
	print("My name is {name}, i'm {age} year old.".format(name = name, age = age))

	
>>> myFunc('Johnson777', 18)
My name is Johnson777, i'm 18 year old.

# 多了一个参数
>>> myFunc('Johnson777', 18, 179)
Traceback (most recent call last):
  File "<pyshell#55>", line 1, in <module>
    myFunc('Johnson777', 18, 179)
TypeError: myFunc() takes 2 positional arguments but 3 were given

# 少了一个参数
>>> myFunc('Johnson777')
Traceback (most recent call last):
  File "<pyshell#57>", line 1, in <module>
    myFunc('Johnson777')
TypeError: myFunc() missing 1 required positional argument: 'age'
>>> 
>>> 

2. 默认参数

默认参数就是在定义形参的时候,给函数默认赋一个值,比如说数据库的端口这样的,默认给它一个值,这样就算你在调用的时候没传入这个参数,它也是有值的

>>> def myFunc(name, age = 18):
	print("My name is {name}, i'm {age} year old.".format(name = name, age = age))

	
>>> myFunc("John", 20)
My name is John, i'm 20 year old.
# 没有传 age 参数的值, 使用默认值 18
>>> myFunc("John")
My name is John, i'm 18 year old.

# name 没有使用默认值,不传参数报错
>>> myFunc(age = 19)
Traceback (most recent call last):
  File "<pyshell#63>", line 1, in <module>
    myFunc(age = 19)
TypeError: myFunc() missing 1 required positional argument: 'name'
>>> 

3. 可变参数

1、可变参数用*,来接收,不是必传的;
2、它把传入的元素全部都放到了一个元祖里;
3、不显示参数个数,后面想传多少个参数就传多少个,它用在参数比较多的情况下
4、如果位置参数、默认值参数、可变参数一起使用的的话,可变参数必须在位置参数和默认值参数后面。

>>> def myFunc(*number):
	print(number)

	
>>> myFunc(1, 2, 3, 4)
(1, 2, 3, 4)
>>> myFunc()
()
>>> myFunc(1)
(1,)
>>> 

4. 关键字参数

1、关键字参数使用**来接收
2、返回的是字典
3、不限制参数个数,非必传
4、当然也可以和上面的几种一起来使用,如果要一起使用的话,关键字参数必须在最后面

>>> def myFunc(**kwargs):
	print(kwargs)

	
>>> myFunc()
{}
>>> myFunc(name = "John", age = 18)
{'name': 'John', 'age': 18}
>>> myFunc(name = "John", age = 18, country = 'China')
{'name': 'John', 'age': 18, 'country': 'China'}
>>> 

5. 以上四种放在一起使用

如果一定要一起用的话,要按下面的顺序写,不能换顺序,否则会出错
1、位置参数;2、默认值参数;3、可变参数;4、关键字参数

>>> def myFunc(name, age = 18, *args, **kwargs):
	print(name)
	print(age)
	print(args)
	print(kwargs)

	
>>> myFunc("John", '2', '3', '4', '5', country = 'China', province = '浙江')
John
2
('3', '4', '5')
{'country': 'China', 'province': '浙江'}
>>> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值