In Python, we may use the print statements to display the final output of a code on the console, whereas the return statement returns a final value of a function execution which may be used further in the code. In this article, we will learn about Python return and print statements.
Return Statement in Python
Python return statement is used to exit the function and return a value. The return keyword is used to specify a value that a function should return when a function is called. It performs some calculations or operations and then returns the value or a set of values to the calling code.
Syntax of Return Statement
def function_name(parameters): # The function body return value
Example:
In this example, we can see that when the ‘add_number’ function is called, it returns the sum of ‘a’ and ‘b’, which is stored in the result variable. Then using the print statement, the result is printed on the console.
Python3
def add_numbers(a, b): return a + b result = add_numbers( 7 , 9 ) print (result) |
Output:
16
Print Statement in Python
The print statement is a built-in function in Python that is used to display output to the console or terminal.
Syntax of Print Statement
print(*objects, sep=' separator', end='\n', file=sys.stdout, flush=False)
Example:
In this example, we can see that the ‘greet’ function does not return any value but simply prints the value using the print statement when it is called.
Python3
def greet(name): print ( "Hello, %s!" % name) greet( "ABC" ) |
Output:
Hello, ABC!
Difference between Return and Print Statement in Python
Let us see the difference between the Python return and Python Print statement.
Return Statement |
Print Statement |
---|---|
It is used to exit a function and return a value | It is used to display output to the console |
It returns a value that can be assigned to a variable or used in any expression | It displays output to the console but does not return the value |
It can be used multiple times in a function but only one value can be returned at a time | It can be used multiple times in a function but does not affect the function’s return value |
Exiting the function with return ends the function and control returns to calling code | The print does not affect program flow and execution continues normally |
Example: return sum in a function that calculates the sum of two numbers | Example: print(“Hello, world!”) to display a message on the console |