python - How is returning the output of a function different than printing it? -
in previous question, andrew jaffe writes:
in addition of other hints , tips, think you're missing crucial: functions need return something. when create
autoparts()
orsplittext()
, idea function can call, , can (and should) give back. once figure out output want function have, need put inreturn
statement.
def autoparts(): parts_dict = {} list_of_parts = open('list_of_parts.txt', 'r') line in list_of_parts: k, v = line.split() parts_dict[k] = v print(parts_dict) >>> autoparts() {'part a': 1, 'part b': 2, ...}
this function creates dictionary, not return something. however, since added print
, output of function shown when run function. difference between return
ing , print
ing it?
print prints out structure output device (normally console). nothing more. return function, do:
def autoparts(): parts_dict={} list_of_parts = open('list_of_parts.txt', 'r') line in list_of_parts: k, v = line.split() parts_dict[k] = v return parts_dict
why return? if don't, dictionary dies (gets garbage collected) , no longer accessible function call ends. if return value, can other stuff it. such as:
my_auto_parts=autoparts() print my_auto_parts['engine']
see happened? autoparts() called , returned parts_dict , stored my_auto_parts variable. can use variable access dictionary object , continues live though function call over. printed out object in dictionary key 'engine'.
for tutorial, check out dive python. it's free , easy follow.
Comments
Post a Comment