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