-2

I'm doing my homework and I got confused between "print" and "return".

For example, when I asked to make a function that returns all the letters in ("a","e","i","o","u"), why cannot the output come out when I just use my def function (example all_letters("hello my wife"), but when I use "print letters" there is an output?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Wuchun Aaron
  • 291
  • 3
  • 4
  • 11

3 Answers3

3

With return, you can assign to a variable:

def my_funct(x):
    return x+1

You can then do y = my_funct(5). y now equals 6.

To help describe it, think of a function to be a machine (similar to what they use in some math classes). By plugging in the variables (in this case, x), the function outputs (or returns) something (in this case, x+1). The variables are the input, and the return gives the output.

However, with print, the value is just shown on the screen.

If you change the function to:

def my_funct(x):
    print(x+1)

And then do y = my_funct(x), y equals None, because print() does not return anything.

Using the machine metaphor, you plug in the variables (again, x) but instead of outputting something, it just shows you what it equals (again, x+1). However, it does not output anything.

Rushy Panchal
  • 15,807
  • 15
  • 56
  • 90
3

return returns a value to the calling scope. print (unless someone has done some monkey patching) pushes data to stdout. A returned value can be subsequently used from the calling scope whereas something printed is dispatched to the OS and the OS handles it accordingly.

>>> def printer(x):
...     print x * 2
...
>>> def returner(x):
...     return x * 2
...
>>> printer(2)
4
>>> y = printer(2)
4
>>> y is None
True
>>> returner(2)
4
>>> y = returner(2)
>>> y
4

The interactive console is a bit misleading for illustrating this since it just prints a string representation of a return value, but the difference in the value assigned to y in the example above is illustrative. y is None when assigned the result of printer because there is an implicit return None for any function which does not have an explicit return value.

Silas Ray
  • 24,966
  • 5
  • 46
  • 61
1

return is a keyword while print is a function:

return is useful when you want to assign a value to a variable.

print just allows you to print some text in the command prompt:

def foo():
    return 2
bar = foo() # now bar == 2
print(bar) # prints 2
aldeb
  • 6,014
  • 3
  • 23
  • 47