Python Forum
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Return options
#1
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.
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Performance options for sys.stdout.writelines dgrunwal 11 3,104 Aug-23-2022, 10:32 PM
Last Post: Pedroski55
  Can argparse support undocumented options? pjfarley3 3 2,180 Aug-14-2020, 06:13 AM
Last Post: pjfarley3
  Help with options raiden 1 1,915 Aug-30-2019, 12:57 AM
Last Post: scidam
  Options for retaining persistent data? hunnimonstr 4 2,948 Feb-14-2018, 07:49 PM
Last Post: hunnimonstr
  Display options - screen tcpip 2 2,831 Feb-06-2018, 02:41 PM
Last Post: tcpip
  Python Launch Options Flexico 6 7,040 Dec-07-2016, 06:58 AM
Last Post: Flexico

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020