python - 返回函数的输出与打印它有何不同?

标签 python return output

在我之前的 question , 安德鲁·贾菲 writes :

In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return something. When you create autoparts() or splittext(), the idea is that this will be a function that you can call, and it can (and should) give something back. Once you figure out the output that you want your function to have, you need to put it in a return statement.

def autoparts():
    parts_dict = {}
    list_of_parts = open('list_of_parts.txt', 'r')
    
    for line in list_of_parts:
        k, v = line.split()
        parts_dict[k] = v

    print(parts_dict)

>>> autoparts()
{'part A': 1, 'part B': 2, ...}

此函数创建一个字典,但它不返回任何内容。但是,由于我添加了 print,因此当我运行该函数时会显示该函数的输出。 returnprint 有什么区别?

最佳答案

print 只是将结构打印到您的输出设备(通常是控制台)。而已。要从您的函数中返回它,您可以:

def autoparts():
  parts_dict = {}
  list_of_parts = open('list_of_parts.txt', 'r')
  for line in list_of_parts:
        k, v = line.split()
        parts_dict[k] = v
  return parts_dict

为什么要回来?好吧,如果您不这样做,那么该字典就会死掉(被垃圾收集)并且一旦此函数调用结束就不再可以访问。如果你返回这个值,你可以用它做其他事情。如:

my_auto_parts = autoparts() 
print(my_auto_parts['engine']) 

看看发生了什么? autoparts() 被调用,它返回 parts_dict 并且我们将它存储到 my_auto_parts 变量中。现在我们可以使用这个变量来访问字典对象,即使函数调用结束,它也会继续存在。然后我们用 'engine' 键打印出字典中的对象。

要获得好的教程,请查看 dive into python .它是免费的,而且非常容易上手。

关于python - 返回函数的输出与打印它有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/750136/

相关文章:

Eclipse C++ 仅在调试时查看输出

python - networkx 节点着色中的异常行为

c - C 中函数的指针返回

c - 返回字符串而不是 int

python - 相同的函数在 Python 中以相反的顺序给出不同的结果。为什么?

java - 输入后显示输出

output - 如何将平滑的cspline曲线输出为数据文件

python - 使用 ast.literal_eval 时出现格式错误的字符串

python - 与Python/Pandas一起使用的时间序列数据库-我正在寻找哪种DB?

python - Django 表单提交单选按钮值显示为 None