`n 如何定义和调用函数在Python中?

如何定义和调用函数在Python中?

Clock Icon 发布时间:2026/11/30 19:09  · 

在NET/" style="text-decoration: none; color: inherit;" title="Python">Python中,定义函数的基本格式是使用关键字def,后面跟着函数名称和参数列表,最后是冒号。函数体需要缩进,包含实际要执行的代码。例如,一个简单的求和函数的定义可以写成如下形式:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythondef add(x, y): return x + y```
这里,add函数接受两个参数x和y,并返回它们的和。任何NET/" style="text-decoration: none; color: inherit;" title="Python">Python代码块都可以放在函数体内,可以执行计算、条件判断或循环等操作。
调用函数很简单,只需使用函数名称并传递必要的参数。继续以add函数为例,调用时可以这样写:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythonresult = add(3, 5)print(result)```
在这个示例中,add函数被调用,3和5被传递为参数,返回值被赋给result变量并打印出来。
函数可以设置默认参数,允许函数在调用时不提供所有参数。当没有传递相应参数时,函数将使用默认值。例如,给定一个带有默认值的函数:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythondef greet(name="世界"): print(f"你好, {name}!")```
使用greet函数时,可以选择不提供参数,系统会使用默认的“世界”作为输出:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythongreet() # 输出: 你好, 世界!```
若提供参数调用,如greet("朋友"),则输出会变为"你好, 朋友!"。
返回值是函数的重要特性,函数可以返回多个值,使用元组的形式来实现。例如,计算两个数的和与差:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythondef calculate(x, y): return x + y, x - y```
调用该函数可得到一对结果:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythonsum_result, difference_result = calculate(10, 5)```
NET/" style="text-decoration: none; color: inherit;" title="Python">Python还支持匿名函数,通常使用lambda关键字定义。这类函数适合简单操作,例如:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythondouble = lambda x: x * 2print(double(4)) # 输出: 8```
这些匿名函数在需要短小函数时非常方便,比如在filter、map和reduce等函数中运用。
了解如何定义和调用函数,有助于构建更为复杂的程序逻辑和模块化代码结构。通过将代码块封装在函数内,便于重复利用和提升代码可读性。熟悉这些基本概念可为编写更高级的程序打下基础。

推荐文章

热门文章