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

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

Clock Icon 发布时间:2026/9/4 13:38  · 

在NET/" style="text-decoration: none; color: inherit;" title="Python">Python中,自定义一个函数的基本语法如下:使用关键字`def`来定义函数,后接函数名称,再接上括号内的参数列表,最后用冒号表示函数的开始。函数体需要用缩进来表示。例如,定义一个简单的加法函数可以这样写:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Python def add(a, b): return a + b ``` 这个函数接收两个参数`a`和`b`,返回它们的和。
调用函数时,可以直接使用函数名称并传入必要的参数。这意味着你可以在程序中多次调用同一个函数。
比如说,使用刚才定义的加法函数,像这样:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Python result = add(3, 5) print(result) # 输出结果为8 ``` 这个例子展示了如何调用函数并打印结果。
NET/" style="text-decoration: none; color: inherit;" title="Python">Python的函数可以有默认参数。定义时可以为某个参数设置默认值,如果调用时没有传入这个参数,则会使用默认值。
例如:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Python def greet(name, greeting="Hello"): return f"{greeting}, {name}!" ``` 在这里,`greeting`有一个默认值“Hello”。如果只提供`name`参数,将使用该默认值。
函数也可以返回多个值,返回值会以元组的形式存在,调用时可以通过解包来获取这些值。
例如:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Python def get_coordinates(): return 10, 20 x, y = get_coordinates() print(x, y) # 输出10 20 ``` 这个例子演示了如何返回和接收多个值。
除了普通的参数外,NET/" style="text-decoration: none; color: inherit;" title="Python">Python还允许使用不定长参数。在函数定义中,使用`*args`可以接收任意数量的位置参数,使用`**kwargs`可以接收任意词典形式的关键字参数。
例如:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Python def func(*args, **kwargs): print(args) print(kwargs) ``` 调用这个函数时,可以提供不定数量的位置参数和关键字参数。
编写函数时,文档字符串非常重要。可以在函数定义的第一行添加文档字符串,用于说明函数的用途。
例如:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Python def square(x): """返回x的平方""" return x ** 2 ``` 通过文档字符串,用户可以更容易理解函数的功能。
在使用函数时,合理的函数设计能够提高代码的可读性和维护性,因此推荐尽量使每个函数只完成一个具体的任务。这种设计原则被称为单一职责原则。
所有这些功能一起使得NET/" style="text-decoration: none; color: inherit;" title="Python">Python的函数成为强大而灵活的工具。通过合理使用这些特性,可以编写出既简洁又高效的代码。

推荐文章

热门文章