Why would you use the return statement in Python?

PythonServer Side ProgrammingProgramming

The print() function writes, i.e., "prints", a string or a number on the console. The return statement does not print out the value it returns when the function is called. It however causes the function to exit or terminate immediately, even if it is not the last statement of the function.

Functions that return values are sometimes called fruitful functions. In many other languages, a function that doesn’t return a value is called a procedure.

In the given code the value returned (that is 2) when function foo() is called is used in the function bar(). These return values are printed on console only when the print statements are used as shown below.

Example

def foo():
    print("Hello from within foo")
    return 2
def bar():
    return 10*foo()
print foo()
print bar()

Output

Hello from within foo
2
Hello from within foo
20

We see that when foo() is called from bar(), 2 isn't written to the console. Instead it is used to calculate the value returned from bar().

raja
Published on 07-Dec-2017 10:56:25
Advertisements