Python Forum
Return options - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Return options (/thread-5320.html)



Return options - Kongurinn - Sep-28-2017

Hey every just starting my first class in Python this semester.

What is the difference between a print() and a return function, when defining a user created function? They both return the answer so I was just wondering.


RE: Return options - ichabod801 - Sep-28-2017

First, print is a function (in Python 3.0 and higher) and return is a statement. You can use print in lots of places you can't use return.

The print function sends the parameter passed to it to the stdout, or standard output. It prints it on the screen.

The return statement passes the value after it to the place that called the function. If you just do this from the command line, it just prints it out. That's why you don't see a difference. But, you can assign it to a variable.

def printer(x):
    print(x + 2)

def returner(x)
    return x + 2
Output:
>>> printer(2) 4 >>> returner(2) 4 >>> x = printer(3) 5 >>> x >>> x = returner(3) >>> x 5
When we assign the printer, we see the value, but the value is not stored in the variable x (Note that None is stored in x, which doesn't print. That's the default return value if you don't specify one). We get the reverse behavior when we assign the returner.

You generally return from your functions, so that other parts of your program can make use of whatever value is returned.