Python recursive function - can anyone explain me this code in detail | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Python recursive function - can anyone explain me this code in detail

def is_even(x): if x == 0: return True else: return is_odd(x-1) def is_odd(x): return not is_even(x) print(is_odd(17)) print(is_even(23))

17th Jul 2018, 3:49 PM
Gagan Lohar
Gagan Lohar - avatar
4 Answers
+ 1
this is the biggest eyesore of a function i've ever seen. to explain it in detail let's take a smaller number like 5: is_even(5): is 5 equal to 0? no so, is_odd(4) gets called is_odd(4) returns !(is_even(4)) is_even(4): is 4 equal to 0? no so, is_odd(3) gets called is_odd(3) returns !(is_even(3)) is_even(3): is 3 equal to 0? no so, is_odd(2) gets called is_odd(2) returns !(is_even(2)) is_even(2): is 2 equal to 0? no so, is_odd(1) gets called is_odd(1) returns !(is_even(1)) is_even(1): is 1 equal to 0? no so, is_odd(0) gets called is_odd(0) returns !(is_even(0)) is_even(0): is 0 equal to 0? yes is_even(0) returns true is_odd(0) returns false (negation of is_even(0)) is_even(1) then returns the result of is_odd(0) (which is false) is_odd(1) returns true is_even(2) returns true (same like is_even 1) is_odd(2) returns false is_even(3) returns false is_odd(3) returns true is_even(4) returns true is_odd(4) returns false and finally is_even(5) returns false, therefore concluding 5 is not even
17th Jul 2018, 7:35 PM
hinanawi
hinanawi - avatar
+ 1
Gagan Lohar well there's a condition that if it's 0 it returns true, and thus the odd one is a negation of it, returning false
17th Jul 2018, 8:31 PM
hinanawi
hinanawi - avatar
0
Thank you for replying.....i really appreciate for your detailed answer.... but still i didn’t get the point that how even values returning true from 1st function and odd values returning false from 1st function
17th Jul 2018, 8:00 PM
Gagan Lohar
Gagan Lohar - avatar
0
thank you so much hinanawi
18th Jul 2018, 9:07 AM
Gagan Lohar
Gagan Lohar - avatar