返回函数的输出与打印输出有何不同? [英] How is returning the output of a function different from printing it?

查看:70
本文介绍了返回函数的输出与打印输出有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我之前的问题中,Andrew Jaffe 写道:

In my previous question, Andrew Jaffe writes:

除了所有其他提示和技巧之外,我认为您还缺少一些关键的东西:您的函数实际上需要返回一些东西.当您创建 autoparts()splittext() 时,其想法是这将是一个您可以调用的函数,并且它可以(并且应该)回馈一些东西.一旦确定了您希望函数具有的输出,您需要将其放入return 语句中.

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,因此在运行该函数时会显示该函数的输出.returning 和 printing 有什么区别?

This function creates a dictionary, but it does not return something. However, since I added the print, the output of the function is shown when I run the function. What is the difference between returning something and printing it?

推荐答案

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

print simply prints out the structure to your output device (normally the console). Nothing more. To return it from your function, you would do:

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

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

Why return? Well if you don't, that dictionary dies (gets garbage collected) and is no longer accessible as soon as this function call ends. If you return the value, you can do other stuff with it. Such as:

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

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

See what happened? autoparts() was called and it returned the parts_dict and we stored it into the my_auto_parts variable. Now we can use this variable to access the dictionary object and it continues to live even though the function call is over. We then printed out the object in the dictionary with the key 'engine'.

要获得好的教程,请查看深入了解 Python.它是免费的,而且很容易遵循.

For a good tutorial, check out dive into python. It's free and very easy to follow.

这篇关于返回函数的输出与打印输出有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆