-8

I have defined a function using Python as follows:

def output ():
  print "Hello, world!"

output ()

When this script is run in windows command line it will return:

Hello, world!

What I would like clarified is: why this is? Why is a value output despite there having been no return value defined?

seeker
  • 530
  • 1
  • 4
  • 14
  • 5
    Because you are calling a method with a `print` inside it. The `print` will *print* to screen. – idjaw Oct 03 '16 at 21:28
  • 2
    The string "Hello, world!" is not returned, but printed to standard output. – Olaf Dietsche Oct 03 '16 at 21:29
  • 2
    The default return of the method will be `None`. If you do `res = output()` and print out `res`, it will be`None`. But you will still get something printed to screen, because the `print` statement will run when the method is called. – idjaw Oct 03 '16 at 21:35
  • @idjaw Thank you, I understand now. If you could kindly write that up as an answer I'd be glad to accept it. Thanks again – seeker Oct 03 '16 at 21:42

3 Answers3

1

Return values only have a meaning in the context of thinking how the program works. To the end users, they likely know nothing about return values.

A separate concept, output, is what the user typically sees. In this case, the program is using a print statement, which outputs to an output stream called stdout. This output stream is typically read by the console the program is running from, and thus outputted to the console.

The actual return value from that function is None, but it is never outputted to the user.

Natecat
  • 2,175
  • 1
  • 17
  • 20
1

The default return of the method will be None. If you perform the following:

res = output()

and print out res, it will be None. By default, None is always returned when not specifying a return.

>>> def output():
...     print "Hello, world!"
...
>>> res = output()
Hello, world!
>>> res
>>> type(res)
<type 'NoneType'>

However, you will still get something printed to screen, because the print statement will run when the method is called.

idjaw
  • 25,487
  • 7
  • 64
  • 83
0

Print will print to stdout. That's why.

Bill Bridge
  • 821
  • 1
  • 9
  • 30
  • Thank you for your answer, however I don't quite understand what you're saying. Some more exposition would be appreciated. Thanks! – seeker Oct 03 '16 at 21:31