Akshay Shukla
Akshay Shukla

Reputation: 3

Why can the return keyword be omitted in some Python functions?

I am new to Python and want to understand why there is no use of return in the following code, and still it is working perfectly fine.

def printCount(num):
    for i in range(2, num +1):
        print(i)
printCount(10)

Upvotes: 0

Views: 132

Answers (2)

MarianD
MarianD

Reputation: 14181

If you don't use the return statement in your function definition, the implicit statement

return None

is appended to the function body.

It means that your code

def printCount(num):
    for i in range(2, num +1):
        print(i)
printCount(10)

is fully equivalent to the code

def printCount(num):
    for i in range(2, num +1):
        print(i)
    return None
printCount(10)

Upvotes: 1

The Pilot Dude
The Pilot Dude

Reputation: 2227

In python return stops the function, and sends the returned value back. For example:

def printCount(num):
    for i in range(2, num +1):
        return(i) #THIS IS USING RETURN
printCount(10)

count = printCount(5)

In this code, on the first iteration in the for loop, it would return i, which would be 2. This would stop the function and set the variable count to the returned value, which is 2. The function wouldn't do anything else.

In your code, I pressume that return is not used because the desired output is: 2 3 4 5...

If you used return, the code would send back 2 at the beginning and that would be it.

Upvotes: 0

Related Questions