Python函数

Python函数

在 Python中, 命名函数时, 在其前面加上 def .

在函数的调用, 与c++有些不同, 具体的不同, 看看代码就一目了然了

关键字的传入



>>> def Fun(name, score):
...     print(name);
...     print(score)
... 
>>> Fun("abc", 90)
abc
90

#关键字的传入, 这样传入时不用分顺序, 建议这样做
>>> Fun(score = 90, name = "abc")
abc
90

*score : 收集参数, 可以传入多个参数
在传入参数的关键字前加入 * 表示可以传入多个参数, 并且可以用索引号来访问这些参数.
这个 * 被叫做解包, 当然, 跟苹果的 swift 语言的解包不一样哈


>>> def Fun1(name, *score):
...     print(name)
...     print(sum(score))
... 
>>> Fun1("abc", 90, 20, 80, 70)
abc
260
>>> a = [90, 20, 80, 70]
>>> Fun1("abc", a)
abc
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in Fun1
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> Fun1("abc", *a)
abc
260

*name : 可以用索引, 当然在传入的时候一定要写出传入关键字
所以建议传入参数加上关键字




>>> def Fun2(*name, score):
...     print(name[1])
...     print(score)
... 
>>> Fun2("abc", "bcd", "efg", 90)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Fun2() missing 1 required keyword-only argument: 'score'
>>> Fun2("abc", "bcd", "efg", score = 90)
bcd
90
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值