Printing and returning are fundamentally different concepts in Python.
- Printing means displaying a value in the console. To print a value in Python, you call the print() function. After printing a value, you can no longer use it.
- Returning is used to return a value from a function and exit the function. To return a value from a function, use the return keyword. You can use the returned value later by storing it in a variable.
Here is an example of a function that prints a value. If you call this function, you can see a greeting in the console:
def greet(name): print("Hello", name) greet("Alice")
Here is an example of a function that returns a value.
When you call this function with a name input, the function gives you back a value. The returned value in this case is a greeting with the name. You can store the return value into a variable and then do what you want with it.
def greet(name): return "Hello " + name greeting = greet("Alice")
Notice how running this piece of code does not show anything in the console! This is because the function returns a value. It does not print it. But you can print the stored value by calling the print() function on the greeting variable:
def greet(name): return "Hello " + name greeting = greet("Alice") print(greeting)
Why Print Is Used So Much?
The reason why printing is used so often in tutorials is that it’s the easiest way to see what’s behind a value. Besides, it’s easy to copy the code and run it on a console and instantly see a result.
Printing is great for visualizing the values you deal with in your program. Otherwise, you cannot know if your code is doing what it’s supposed to do. If a function returns a value, you need to print the value to truly know what it is before you start using the function.
Make Sure to Understand the Difference!
Please, make sure to read your course materials thoroughly. The difference between print and return is something that isn’t explicitly stated in a beginner course. This is because the difference is so fundamental that the course creators won’t even bother mentioning about it. When you understand these concepts return and print better, you realize how silly a comparison it even is :). Comparing return and print in Python is like comparing having a car vs looking at pictures of a car.
Printing and returning are completely different things in Python. As a beginner, you may be confused by these two because they are used in a very similar way in many examples.
To take home:
- Printing means showing a value in the console.
- Returning means giving back a value from a function.
When a function returns a value, you can store it as a variable and do whatever with it. But if a function only prints a value, it doesn’t return it. Thus, you cannot use it anywhere.