Python Forum

Full Version: Need of return in function if statement inside the function already returns
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I'm learning python from some online tutorials. When learning about function, there was an exercise to check "Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20. If not, return False"

Before making function, i did following

a = (10, 20) 
sum(a) == 20 or a[0] == 20 or a[1] == 20
and it returns True if conditions satisfy.

but when I tried to make this in to a function

def func(a):
    sum(a) == 20 or a[0] == 20 or a[1] == 20
when called the above function
func((10,20))
. It didn't return anything. I had to put return inside the function to get True or False.

What is the need of this return since
sum(a) == 20 or a[0] == 20 or a[1] == 20
this line can already return true or False on it's own???
Thanks
You forget the return statement:

def func(a):
    return sum(a) == 20 or a[0] == 20 or a[1] == 20
Yeah I know that. What I meant is
When I run below code
a = (10, 20) 
sum(a) == 20 or a[0] == 20 or a[1] == 20
It gives the answer as
True
or
False
That means it returns something.
SO when I make this as a function, why do I have to type return before
sum(a) == 20 or a[0] == 20 or a[1] == 20
this, since it itself is returning the answer
A function always returns None if something else isn't specified.
So, your function returns None. That is why you have to use the return statement in front of the expression to get the result.
Also, when you enter something in the interactive interpreter, it evaluates it. It's not returning anything, it's evaluating the expression you entered.
Athul, what I have just recently learned is that the interpreter is only being nice to you by printing to the screen what you want to see, you are seeing what has happened within the interpreter and it is only showing you the internal answer, the evaluation only, and that evaluation is on stand by where it could be used by another part of the program if needed, but this is not the external answer that you need, this is why the return statement is actually needed, to give you the answer outside of the program where you can actually use it properly. I hope that explains it a little better.