blog/docs/code/python/func.md

138 lines
2.6 KiB
Markdown
Raw Permalink 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.

---
title: 函数
date: 2020-09-12 17:25:10
tags: [Python]
categories: [Python]
author: Anges黎梦
---
### 定义
函数也称为定义函数,可以理解为某一种作用的代码块。
### 优点
- 更简洁的代码
- 代码重用
- 易于测试
- 快速开发
- 便于团队合作
### 创建一个函数
**示例代码**
```python
# 使用def关键字创建def + 函数名(参数)+ ":"
def func_name(param):
# 函数注释
"""
定义一个函数
"""
# 函数内实现功能的代码块
print(param)
```
### 函数调用
#### 直接调用
**示例代码**
```python
# 函数调用,函数名() 若无参数则为空括号
func_name("黎梦")
```
### 函数传参
**函数的参数**
- 函数中的参数,可以为空。
- 可选参数,一般是包含,固定参数(形式参数)、可变参数
#### 形式参数和实际参数
**作用**
- 形式参数:在定义函数时,函数名后面括号内的参数为“形式参数”,也称为形参
- 实际参数:在调用一个函数时,函数名后面括号内的参数,为“实际参数”。函数调用者提供给函数的参数,叫实际参数,也称为实参。
#### 按照参数位置调用
> 按照正确的顺序传递到函数中。
**示例代码**
```python
def func_1(a, b):
print("a的值为{}".format(a))
print("b的值为{}".format(b))
func_1(1,2)
func_1(2,1)
```
**实际调用时,实参的数量要与形参一致**
**报错示例**
```python
func_1(1)
```
**报错信息**
```python
TypeError: func_1() missing 1 required positional argument: 'b'
```
#### 关键字调用
> 根据参数关键字调用
**示例代码**
```python
func_1(b=6, a=3)
```
#### 参数默认值
**示例代码**
```python
def func_2(a=1):
print("a的值为{}".format(a))
```
**响应结果**
```python
func_2() # a的值为1
```
**函数参数顺序,普通形式参数 > 有默认值的参数**
#### 异常场景
**示例代码**
```python
def func_3(b, a=[]):
# 带默认值的参数,会在定义函数时,定义,而不是在每次调用时定义。
a.append(b)
print(a)
func_3(b=1)
func_3(b=2)
func_3(b=5, a=[])
```
### 返回值 return
- 函数调用,可接收返回值
- 若函数没有return关键字定义返回值那么返回内容为None 空
**示例代码**
```python
def func_4():
return "ok"
res1 = func_3(b=4)
res2 = func_4()
print(res1)
print(res2)
```
### 占位符 pass
**示例代码**
```python
# 表示空语句,不做任何操作,一般起到占位置的作用。
def decs():
pass
```