Python Forum

Full Version: Difference between return and print
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
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)
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?
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.
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))
(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
line 7:
dime, dollar = myfunction()
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
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
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.