Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Functions, Packing, and Unpacking Getting Info In and Out of Functions All About Returns

Frances Angulo
Frances Angulo
5,311 Points

Print vs return

Def two_plus_two(): Val = 2 + 2 Print(Val)

Will get you the answer- but return doesn’t. Why would I use return vs. print?

2 Answers

return will also get you the answer as the following do the same thing:

def two_plus_two():
    val = 2 + 2
    print(val)

two_plus_two()
def two_plus_two2():
    val = 2 + 2
    return val

print(two_plus_two2())

return is useful if you want to do additional work with the result of the function. In the above the first function just displays the value to the console. It still has a return value but that value is None since there is no explicit return statement.

The second function would allow you to do further calculations. For example:

a = two_plus_two2()
a += 4
print(a)

would print 8

This is how I understand it. Like the previous comment, return allows you to do more with what your functions return back to you. Whereas print just prints to screen and that's it. Hope it helps:

print(5) # just prints 5; can't be assigned to anything

num = input("Enter a number: ") 
# num is string value in input function
num = int(num) 
# changing num from string to int so the function I declare below can use it

def add_five_to_something():
    sum = 5 + num
    print("Something printed; cannot do anything else with this.")
    return sum # can still be used in a variable
# sum of number entered plus 5 is being returned as an integer to us
# it can be passed to a variable in the global scope later
# in this case, this returned value of sum won't print to the screen until it's passed to a variable

final_result = add_five_to_something() 
# passing what is returned from this function (sum) to this variable
# we can't assign sum directly since it was declared locally inside the function
    # sum is not in the global scope

print("Final number is: " + str(final_result)) 
# change the returned int back to string for printing