I recently started learning python through Sololearn and got to Recursion. To get better understanding of the code, I simplified it to:
def is_even(x): return x def is_odd(x): return not is_even(x) print(is_odd(2))
The return not is_even(x)
is boolean and will resulted it as False
and when it passed to the def is_even(x):
it still would return as False.
However, when I change the return x
to print(x)
def is_even(x): print (x) def is_odd(x): return not is_even(x) print(is_odd(2))
The result would be:
2 True
How did this happen? What is going on between the return not is_even(x)
and print (x)
.
Thank you
Advertisement
Answer
Maybe this will get you on track:
def returning(x): return x def printing(x): print(x) returning(2) # 2 printing(2) # 2 a = returning(2) a # 2 b = printing(2) 2 b # None
The difference is that return
returns a value from a function
which can be used to pass to another function / variable. print
just prints out the information but does not return any value, this is why b
holds no value, but during the assigment b = printing(2)
it immediately printed out what was passed to it, when a = returning(2)
did not, it assigned the value to variable a
.
And None
is falsly in python.
None == False # False None == True # False not None == True # True
What you are lacking is for is_even
to return a bool
instead of the argument passed:
def is_even(x): return x % 2 == 0 def is_odd(x): return not is_even(x) is_odd(3) # True