How is returning the output of a function different from printing it?

后端 未结 7 1708
死守一世寂寞
死守一世寂寞 2020-11-21 11:23

In my previous question, Andrew Jaffe writes:

In addition to all of the other hints and tips, I think you\'re missing something crucial: your functio

7条回答
  •  独厮守ぢ
    2020-11-21 12:11

    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']) 
    

    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'.

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

提交回复
热议问题