1.4 KiB
1.4 KiB
函数定义与参数
- def定义
def my_function(fname):
print(fname + " Gates")
my_function("Bill")
my_function("Steve")
my_function("Elon")
- 默认参数
def my_function(country = "China"):
print("I am from " + country)
my_function()
my_function("Brazil")
- 关键字参数:使用key=value形式传递参数,顺序不严格要求
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")
- 任意参数:相当于多个参数元组
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Phoebe", "Jennifer", "Rory")
- pass语句
def myfunction:
pass
函数返回值 return
- 返回两个参数,分别接收
>>> def myfunc():
... return 1,2
...
>>> a, b = myfunc()
>>> a
1
>>> b
2
>>>
- 返回两个结果,一个变量接收
>>> def myfunc():
... return 1,2
...
>>> a= myfunc()
>>> a
(1, 2)
>>>
- 返回值元组形式,多个变量接收,接收变量数超出返回值数量会报错
>>> def myfunc():
... return (1,2)
...
>>> a, b = myfunc()
>>> a
1
>>> b
2
>>> a, b, c = myfunc()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
>>>