Home > Software design >  what is the best way to display the output? (print,return)
what is the best way to display the output? (print,return)

Time:09-26

It seems that both print and return can display the output.

The only difference I found between is that return displays even quotation marks, whereas print doesn't.

How about using together?:

return print("Hello")

What is the most common and efficient way to display the output in a function(maybe the last line)?

Are there any changes to the flowchart between return and print?

CodePudding user response:

return certainly does not display output. It returns output from a function. If you happen to call a function in a python shell, you will get the output printed to the terminal, but this is incidental---it is because the python shell is a REPL: a Read Eval Print Loop. So it reads what you type, evaluates it (i.e. runs it), and then prints whatever is left.

Thus print is for printing to stdout. return is for getting values back from functions.

But I can see how one might get confused playing about in a REPL.

(Try just typing return 7 in a python REPL to see why you can't use return as a print replacement, even in a REPL.)

CodePudding user response:

return - Returns a value so that it can be stored in a variable.

print - prints values to the stdout.

fu():
    x = 1
    print(x)

y = fu()

y is None

fu():
    x = 1
    return x
y = fu()

y is 1

  • Related