Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Why would you use the return statement in Python?

I have the following code

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

If this code is run I get only

Hello from within foo

Why is the return statement used in python?


1 Answer
Rajendra Dharmkar

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.

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().

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.