在我之前的 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()
orsplittext()
, 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 areturn
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
,因此当我运行该函数时会显示该函数的输出。 return
和 print
有什么区别?
最佳答案
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/