Return vs Print in Python
In Python, we work with a wide range of functions that make our code simple. We can also create functions using the
def keyword. A function can be defined as per our requirement and can display something or return a value. This is where confusion occurs regarding the
Here is the quick description about return and print in Python.
print()is used to print something on console.
returnis used to return value such as string, integer from function and exit the function,
We will discuss the
Let us begin with
print() function to display some output in the standard output. The
print() function can be used anywhere in the program.
The above example is a Python 3 code where we print a string. We display this string to the user.
print() function when encountered within a function does not affect it. We only use it to display some output to the user.
return statement on the other hand is used to return some value from the given function. This means that the function sends a value back to the caller. This value is specified with the
return statement and can be any Python object like a string, number, list, and more.
Every function returns some value. A function that is missing the
return statement returns a
None value. The
return statement affects the function because it specifies the type of value which will be returned by the function. A
return statement is only used in a function definition.
Let us see an example of the
x = fun()
In the above example, the function
fun returns a value of
5 which is stored in the variable
A function can have both
See the code below.
print("Message from fun")
x = fun()
Message from fun
In the above example,
- We use the
print()function to display a message from outside and inside the function.
- In the function
fun(), we have both the
- The function
fun()prints a string and returns a value of 5.
- The returned value is stored in a variable which is later displayed using the
To conclude, we discussed
print() function displays some output. The
return statement is used to return some value from a given function. Every function in Python returns some value but does not necessarily print anything. The
print() function can be used anywhere in the program whereas the
return statement is limited to a function.