导航
×
   ❮   
HTML CSS JavaScript PHP Python C C++ Go Sass W3C Colors TypeScript ECMS

Python 教程

Python 简介 Python 历史 Python 下载安装配置 Python 入门 Python 语法 Python 语句 Python 输出 Python 注释 Python 变量 Python 数据类型 Python 数值类型 Python 类型转换 Python 字符串 Python 布尔值 Python 运算符 Python 列表 Python 元组 Python 集合 Python 字典 Python If...Else Python While 循环 Python For 循环 Python 函数 Python Range Python 数组 Python 类和对象 Python 继承 Python 迭代 Python 模块 Python 日期时间 Python 数学运算 Python JSON Python 正则表达式 Python PIP Python Try...Except Python 用户输入 Python 字符串格式化

Python 文件处理

Python 文件处理 Python 打开文件 Python 创建/写入文件 Python 删除文件

Python NumPy

NumPy 简介 NumPy 入门 NumPy 创建数组 NumPy 数组索引 NumPy 数组裁切 NumPy 数据类型 NumPy 副本 vs 视图 NumPy 数组形状 NumPy 数组重塑 NumPy 数组迭代 NumPy 数组连接 NumPy 数组拆分 NumPy 数组搜索 NumPy 数组排序 NumPy 数组过滤 NumPy 随机数 NumPy ufunc 通用函数

Python SciPy

SciPy 简介 SciPy 入门 SciPy 常量 SciPy 优化器 SciPy 稀疏数据 SciPy 图表 SciPy 空间数据 SciPy Matlab 数组 SciPy 插值 SciPy 统计显着性检验

Python 机器学习

Machine 机器学习入门 Machine 平均中位数模式 Machine 标准差 Machine 百分位数 Machine 数据分布 Machine 正态数据分布 Machine 散点图 Machine 线性回归 Machine 多项式回归 Machine 多元回归 Machine 缩放 Machine 训练/测试 Machine 决策树

Python MySQL

MySQL 入门 MySQL Create Database MySQL Create Table MySQL Insert MySQL Select MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL Join

Python MongoDB

MongoDB 入门 MongoDB 创建数据库 MongoDB 创建集合 MongoDB 插入 MongoDB 查找 MongoDB 查询 MongoDB 排序 MongoDB 删除 MongoDB 删除集合 MongoDB 更新 MongoDB 限制

Python 参考手册

Python 参考手册 Python 内置函数 Python 字符串方法 Python 列表/数组方法 Python 字典方法 Python 元组方法 Python 集合方法 Python 文件方法 Python 关键字 Python 内置异常 Python 词汇表
Python 词汇表 Indentation Multi Line Comments Creating Variables Variable Names Output Variables String Concatenation Global Variables Built-In Data Types Getting Data Type Setting Data Type Numbers Int Float Complex Random Number Specify a Variable Type String Literals Assigning a String to a Variable Multiline Strings Strings are Arrays Slicing a String Negative Indexing on a String String Length Check In String Format String Escape Characters Evaluate Booleans Return Boolean Value Comparison Operators Identity Operators Access List Items Change List Item Loop Through List Items Check if List Item Exists List Length Add List Items Remove List Items Copy a List Join Two Lists Access Tuple Items Change Tuple Item Loop List Items Check if Tuple Item Exists Tuple Length Tuple With One Item Remove Tuple Items Join Two Tuples 访问集合项 添加集合项目 Loop Set Items 检查集合项是否存在 集合长度 删除集合项 连接两个集合 Access Dictionary Items Change Dictionary Item Loop Dictionary Items Check if Dictionary Item Exists Dictionary Length Add Dictionary Item Remove Dictionary Items Copy Dictionary Nested Dictionaries If Statement If 缩进 Elif Else 简写 If Else If AND If OR 嵌套 If If中的pass关键字 While While Break While Continue While Else Loop Through a String For Break For Continue Looping Through a rangee For Else Nested Loops For pass Call a Function *args Keyword Arguments *kwargs Default Parameter Value Passing a List as an Argument Function Return Value The pass Statement i Functions Function Recursion Why Use Lambda Functions Array What is an Array Array Length Looping Array Elements Add Array Element Remove Array Element Array Methods Class Create Class The Class __init__() Function Object Methods self Modify Object Properties Delete Object Properties Delete Object Class pass Statement Create Parent Class Create Child Class Create the __init__() Function Add Class Properties Add Class Methods Iterator vs Iterable Loop Through an Iterator Create an Iterator StopIteration Global Scope Global Keyword Create a Module Variables in Modules Renaming a Module Built-in Modules Using the dir() Function Import From Module Date Output Create a Date Object The strftime Method Date Format Codes Parse JSON Convert into JSON Format JSON Sort JSON RegEx Functions Metacharacters in RegEx RegEx Special Sequences RegEx Sets RegEx Match Object Install PIP PIP Packages PIP Remove Package Error Handling Try Else Try Finally raise Comments Assign Values to Multiple Variables Type Conversion Boolean Values Operators Arithmetic Operators Assignment Operators Logical Operators 成员运算符 Bitwise Operators Lists Tuple 集合 Dictionary 简写 If For Function Function Arguments Lambda Function super Function Iterators Datetime Module JSON RegEx Module Handle Many Exceptions Access Arrays

Python 模块参考

Python 内置模块 Python random 随机模块 Python requests 请求模块 Python statistics 统计模块 Python math 数学模块 Python cMath 模块

Python 如何使用

Python 删除列表重复项 Python 反转字符串 Python 添加两个数字

Python 实例

Python 实例 Python 测验

Python 函数


函数是一种仅在调用时运行的代码块。

您可以将数据(称为参数)传递到函数中。

函数可以把数据作为结果返回。


创建函数

在 Python 中,使用 def 关键字定义函数:

实例

def my_function():
  print("Hello from a function")

调用函数

如需调用函数,请使用函数名称后跟括号:

实例

def my_function():
  print("Hello from a function")

my_function()
亲自试一试 »

参数

信息可以作为参数传递给函数。

参数在函数名后的括号内指定。您可以根据需要添加任意数量的参数,只需用逗号分隔即可。

下面的例子有一个带参数(fname)的函数。当调用此函数时,我们传递一个名字,在函数内部使用它来打印全名:

实例

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
亲自试一试 »

在Python文档中,参数 Arguments 通常被缩写为 args。


形式参数或实际参数?

parameter 和 argument 这两个术语可用于同一事物:传递给函数的信息。

从函数的角度来看:

parameter形式参数是函数定义中括号内列出的变量。

argument实际参数是在调用函数时发送给函数的值。


参数个数

默认情况下,必须使用正确数量的参数调用函数。这意味着如果您的函数需要 2 个参数,则必须使用 2 个参数调用该函数,即不是更多,也不是更少。

实例

此函数需要 2 个参数,并获取 2 个参数:

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil", "Refsnes")
亲自试一试 »
如果您尝试使用 1 或 3 个参数调用该函数,您将收到错误消息:

实例

这个函数需要 2 个参数,但只得到 1 个:

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil")
亲自试一试 »

任意参数 *args

如果您不知道将传递给函数的参数数量,请在函数定义中的参数名称前添加 *。

这样,函数将接收 tuple 元组参数,并可以相应地访问项目:

实例

如果实际参数个数未知,在形式参数名前加一个*:

def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")
亲自试一试 »

Arbitrary Arguments 在 Python 文档中通常缩写为 *args。


Keyword Arguments 关键字参数

您还可以使用 key = value 语法发送参数。

这样参数的顺序无关紧要。

实例

def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
亲自试一试 »

短语 Keyword Arguments 在 Python 文档中通常缩写为 kwargs。


任意关键字参数 **kwargs

如果您不知道将传递给函数的关键字实际参数的数量,请在函数定义中的形式参数名称前添加两个星号:**。< /p>

这样,函数将接收一个dictionary 字典参数,并可以相应地访问项目:

实例

如果关键字实参个数未知,在参数名前加一个双**:

def my_function(**kid):
  print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")
亲自试一试 »

Arbitrary Kword Arguments 在 Python 文档中通常缩写为 **kwargs。


默认参数值

下面的例子展示如何使用默认参数值。

如果我们调用了不带参数的函数,则使用默认值:

实例

def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
亲自试一试 »

以 List 传参

您发送到函数的参数可以是任何数据类型(字符串、数字、列表、字典等),并且在函数内其将被视为相同数据类型。

例如,如果您将 List 作为参数发送,它到达函数时仍将是 List(列表):

实例

def my_function(food):
  for x in food:
    print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)
亲自试一试 »

返回值

如需使函数返回值,请使用 return 语句:

实例

def my_function(x):
  return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
亲自试一试 »

pass 语句

函数定义不能为空,但是如果您出于某种原因写了无内容的函数定义,请使用 pass 语句来避免错误。

实例

def myfunction():
  pass
亲自试一试 »

递归

Python 也接受函数递归,这意味着定义的函数能够调用自身。

递归是一种常见的数学和编程概念。它意味着函数调用自身。这样做的好处是可以循环访问数据以达成结果。

开发人员应该非常小心递归,因为它可以很容易地编写一个永不终止的,或者使用过量内存或处理器能力的函数。但是,在被正确编写后,递归可能是一种非常有效且数学上优雅的编程方法。

在这个例子中,tri_recursion() 是我们定义为调用自身 ("recurse") 的函数。我们使用 k 变量作为数据,每次递归时递减(-1)。当条件不大于 0 时(比如当它为 0 时),递归结束。

对于新的开发人员来说,可能需要一些时间来搞清楚其工作原理,最好的方法是测试并修改它。

实例

递归的例子:

def tri_recursion(k):
 if(k > 0):
   result = k + tri_recursion(k - 1)
   print(result)
 else:
   result = 0
 return result

print("\n\nRecursion Example Results")
tri_recursion(6)
亲自试一试 »

Copyright ©2026 蒙ICP备2026009383号 All Rights Reserved 提供的内容仅用于学习和测试,不保证内容的正确性。