# 3.函数

## 函数定义

* 函数代码块以 def 关键词开头，后接函数标识符名称和圆括号 ()。
* 任何传入参数和自变量必须放在圆括号中间，圆括号之间可以用于定义参数。
* 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
* 函数内容以冒号起始，并且缩进。
* return \[表达式] 结束函数，选择性地返回一个值给调用方。不带表达式的return相当于返回 None。

```python

def test(str):    # def 函数名(参数) ：
    print(str)    #     函数体
    return

```

## 参数传递

> 由于python的所有类型都是对象类型（包括int，float），变量中保存的都是对象的地址。因此函数的参数传递都是指针传递。

## 参数

* 必需参数
* 关键字参数
* 默认参数
* 不定长参数

### 必须参数

```python

def test(str1,num1,str2):
    num2 = num1 + 1
    str3 = str1 + str2
    print(num2,str3)

test("123",1,"1234")

```

> 如上 str1，num1，str2都是必须参数，不可以少，且顺序不可以变

### 关键字参数

```python

# 仍是上面定义的test方法

test(str2 = "dadsa",str1 = "2131", num1 = 11)

```

> 可以通过关键字表明是传递的是哪个参数，这样可以不按顺序传入

### 默认参数

> 调用函数时，如果没有传递参数，则会使用默认参数；默认参数的后面必须都是默认参数

```python

def test(str1,num1 = 0,str2 = "123"):
    num2 = num1 + 1
    str3 = str1 + str2
    print(num2,str3)


test("DASD")

```

> 如上num1，和 str2 有默认的参数，但是不可以num1为默认参数，而str2不是

### 变长参数

> 有些函数的参数的个数是不确定的，如，`def print(self, *args, sep=' ', end='\n', file=None):`这里就会需要变长参数

```python

def functionname([formal_args,] *var_args_tuple ):

def functionname([formal_args,] *var_args_dic ):

```

> 变长参数有两种形式，一种是


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.existorlive.cn/kai-fa-yu-yan-xue-xi/python/3.-han-shu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
