在Python中,定义完函数后可以通过以下几种方式输出函数的结果:
直接调用函数并打印返回值
```python
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result) 输出:8
使用`print`函数打印函数名
```python
def my_function():
pass
print(my_function.__name__) 输出:my_function
使用`inspect`模块获取函数名 (更复杂,通常用于调试):
```python
import inspect
def my_function():
pass
function_name = inspect.getframeinfo(inspect.currentframe()).function
print(function_name) 输出:my_function
格式化输出(例如,使用`%`格式化字符串):
```python
def calculate_area(length, width):
return length * width
area = calculate_area(10, 5)
print("The area is %d square units." % area) 输出:The area is 50 square units.
使用`print`函数的不同参数进行输出(例如,不换行):
```python
print("Hello", "World", end=" ") 输出:Hello World
将输出写入文件```python
with open("output.txt", "a") as file:
print("Hello, World!", file=file) 将"Hello, World!"追加到output.txt文件中
以上是Python中定义函数后输出结果的一些常见方法。您可以根据需要选择合适的方法