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
  argparser not showing all options bigal 1 226 May-22-2024, 02:54 AM
Last Post: deanhystad
  Help with options raiden 1 1,992 Aug-30-2019, 12:57 AM
Last Post: scidam
  Display options - screen tcpip 2 2,923 Feb-06-2018, 02:41 PM
Last Post: tcpip
  Python Launch Options Flexico 6 7,229 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