在Python中调用自定义函数通常遵循以下步骤:
定义函数:
使用`def`关键字定义函数,后面跟函数名和括号内的参数列表。函数体则缩进在函数名下方。
```python
def my_function(param1, param2):
result = param1 + param2
return result
调用函数:
在代码中直接使用函数名加上括号来调用函数,并传递所需的参数。
```python
sum_result = my_function(3, 5)
print(sum_result) 输出 8
如果函数定义保存在一个`.py`文件中,例如`my_functions.py`,你可以通过以下方式调用:
导入函数:
使用`from module_name import function_name`语句导入函数。
```python
from my_functions import my_function
result = my_function(3, 5)
print(result) 输出 8
使用`import`语句:
如果需要使用整个模块中的所有函数,可以使用`import module_name`,然后通过模块名调用函数。
```python
import my_functions
result = my_functions.my_function(3, 5)
print(result) 输出 8
确保函数定义和调用在同一作用域内,或者函数定义在调用它的脚本之前被导入。