typora/note/Python/函数.md
2024-12-12 10:48:55 +08:00

95 lines
1.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

### 函数定义与参数
- def定义
```python
def my_function(fname):
print(fname + " Gates")
my_function("Bill")
my_function("Steve")
my_function("Elon")
```
- 默认参数
```python
def my_function(country = "China"):
print("I am from " + country)
my_function()
my_function("Brazil")
```
- 关键字参数使用key=value形式传递参数顺序不严格要求
```python
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")
```
- 任意参数:相当于多个参数元组
```python
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Phoebe", "Jennifer", "Rory")
```
- pass语句
```python
def myfunction:
pass
```
### 函数返回值 return
- 返回两个参数,分别接收
```python
>>> def myfunc():
... return 1,2
...
>>> a, b = myfunc()
>>> a
1
>>> b
2
>>>
```
- 返回两个结果,一个变量接收
```python
>>> def myfunc():
... return 1,2
...
>>> a= myfunc()
>>> a
(1, 2)
>>>
```
- 返回值元组形式,多个变量接收,接收变量数超出返回值数量会报错
```python
>>> 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)
>>>
```