Python Forum
Difference between return and print
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Difference between return and print
#1
For this code, why can't you just replace return with print? What is the difference between return and print, explained so that a beginner can understand it?

def greater_less_equal_5(answer):
    if answer > 5:
        return 1
    elif answer < 5:          
        return -1
    else:
        return 0
        
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)
Reply
#2
that's like the difference between night and day.
print displays text to the display

return returns a value to the calling routine.

your statement:
print greater_less_equal_5(4)
id the same as:

result = greater_less_equal_5(4)
print result
except when the function is called directly from the print statement, it uses the return value from the call stack as the item to print.
It's like print 'the results of' greater_less_equal_5(4)
Reply
#3
I heard return can be used to save a value and use it again later, can someone show me how this is done using code a newbie can understand?
Reply
#4
return is a statement used in a function or method to cease the running of that function or method, resume the running of the code that called the function or method, and usually provide the value the calling code gets in place of the function or method call, typically in, or as, an assignment expression.

the calling code can also pass one or more values or object (such as a list or dictionary or many other things) references. the function or method can then store values or object references into elements of the objects referred to. the code that calls the function or method can access anything in objects it kept references to.

the code that calls the function or method can save the value that is returned or stored in a referenced object.

i am not going to show how this is done because it is so basic and just about all code with a called function or method has what you are looking for. and your question is rather vague to pin down a specific example. look at the variable assignments used on the same line of code with a function or method call.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#5
Quote:I heard return can be used to save a value and use it again later, can someone show me how this is done using code a newbie can understand?
In plain english:
return only returns what you tell it to return.
That can be a simple item, or several items, examples (untested)

Return 1 item:
def myfunction():
  dime = .10
  dollar = dime * 10
  return dollar

# Usage:
amount = myfunction()
print(amount)
Return more than one item:
def myfunction():
  dime = .10
  dollar = dime * 10
  return dime, dollar

# Usage:
dime, dollar = myfunction
print('a dime = {}, and a dollar = {}'.format(dime, dollar))
Reply
#6
(Oct-25-2018, 02:17 AM)Larz60+ Wrote:
Quote:I heard return can be used to save a value and use it again later, can someone show me how this is done using code a newbie can understand?
In plain english:
return only returns what you tell it to return.
That can be a simple item, or several items, examples (untested)

Return more than one item:
def myfunction():
  dime = .10
  dollar = dime * 10
  return dime, dollar

# Usage:
dime, dollar = myfunction
print('a dime = {}, and a dollar = {}'.format(dime, dollar))

For this code I get an error message:
Traceback (most recent call last):
File "python", line 7, in <module>
TypeError: 'function' object is not iterable
Reply
#7
line 7:
dime, dollar = myfunction()
Reply
#8
Some additional tidbits:

- The print() function writes, i.e., "prints", a string in the console. The return statement causes function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. The return statement is used when a function is ready to return a value to its caller

- In the Python REPL (Read–Eval–Print Loop) a function return will be output to the screen by default but this isn't quite the same as print.

- if function doesn't have return (or yield) statement in the body then it returns None. Such functions sometimes called a procedure

>>> def add(x, y):
...     print(x + y)
...
>>> add(1, 2)
3                        # everything seems fine
>>> add(1, 2) + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
>>> type(add(1, 2))
3                        # prints x + y      
<class 'NoneType'>       # returns None
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#9
DragonG Wrote:that is the difference between return and print, explained so that a beginner can understand it?
In example under gone look at some basic usage of function and return,this can make it clearer what return is good for.
In read_file() we don't want to print the result,but return it out for further progressing.
Same with check_gender(read_file) it take in read_file do work and return result.
In result(gender) when all is finish then print out result.

If look at code you see small task function(like black box isolated for outside world),
that take in a argument and return out the result.
This make code easier to read and test,than writing this same code within functions.
def read_file():
    try:
        with open("names.txt", encoding='utf-8') as f:
            return [i.strip() for i in f]
    except (OSError, IOError) as error:
        return f'Error reading file: {error}'

def check_gender(read_file):
    '''Make male and female list output'''
    male = []
    female = []
    for name in read_file:
        if name.lower().startswith('male'):
            male.append(name.split(' ', 1)[1])
        else:
            female.append(name.split(' ', 1)[1])
    return male, female

def result(gender):
    '''Show table of Male Female'''
    male, female = gender
    titles = ['Male', 'Female']
    print('{:>8}{:>15}'.format(*titles))
    print('-'*27)
    for item in zip(male, female):
        print('{:15}{:^10}'.format(*item))

if __name__ == '__main__':
    if 'Error' in read_file():
        print(read_file())
    else:
        gender = check_gender(read_file())
        result(gender)
Output:
Male Female --------------------------- Kent Hollow Emily Hunt Hans Klein Olivia Stock
Input names.txt:
Male Kent Hollow
Female Emily Hunt
Male Hans Klein
Female Olivia Stock 
You need Python 3.6 --> to run this code,so do not use Python 2 as you use in first post Wink
Reply
#10
there are two major versions of python, python2 ans python3. python2 will no longer be supported after the end of 2019 although it will still run if you still have it. it is suggested that all new learning focus on python3.

these two major versions are mostly the same with a few differences. the difference you will first encounter, if you switch over now, is that in python2, print is a statement while in python3, print is a function. python3 has been out for nearly a decade. so, everyone has had plenty of time to learn it and try it. if their scripts don't depend on other code that has not yet been upgraded to python3, then they should be upgrading to python3 real soon, if not already.

you will see many examples of print as a function call, such as post #9 in this topic thread. be ready for it and understand it.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  What a difference print() makes Mark17 2 566 Oct-20-2023, 10:24 PM
Last Post: DeaD_EyE
  return vs. print in nested function example Mark17 4 1,744 Jan-04-2022, 06:02 PM
Last Post: jefsummers
  output while using return instead of print muza 2 2,124 Apr-23-2020, 09:38 AM
Last Post: muza
  Error with print and return commands TheDark_Knight 2 1,939 Jan-15-2020, 04:59 PM
Last Post: TheDark_Knight
  Embedding return in a print statement Tapster 3 2,283 Oct-07-2019, 03:10 PM
Last Post: Tapster
  print 3 return values from function bluefrog 5 5,259 Mar-05-2017, 07:58 PM
Last Post: wavic

Forum Jump:

User Panel Messages

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