This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 函数的参数\n",
"\n",
"## 一、基础知识"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Python 没有函数重载"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def ff( x ): return x \n",
"def ff( x,y ): return x + y # 同名函数后面的遮挡前面函数\n",
"\n",
"ff(2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 值传递和引用传递"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 值传递 :字符串、数字、元组 [ 不可变 ]\n",
"\n",
"def ff(x): x += 1 # 不改变调用值 a\n",
"a = 5 ; ff(a) ; a"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 引用传递: 列表、字典 [可变]\n",
"\n",
"def ff(x): x.append(1) # 改变调用值 a\n",
"a = [ 0 ] ; ff(a); a"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 二、函数参数形式\n",
"\n",
"Python函数的参数传递非常灵活,支持多种参数形式,使得函数定义和调用更加强大和灵活。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2.1 普通参数"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 位置参数\n",
"\n",
"位置参数是最基本的参数形式,按照它们在函数定义中的顺序传递。"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Alice, you are 25 years old\n"
]
}
],
"source": [
"def greet(name, age): # name 和 age 是位置参数\n",
" print(f\"Hello {name}, you are {age} years old\")\n",