Can anyone explain me what is happening in this code because i don't understand it at all. its from Recursion chapter

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

20th Sep 2023, 2:52 PM
Izo tmg
Izo tmg - avatar
3 Answers
+ 1
This code defines two functions, is_even() and is_odd(), which determine whether a given integer is even or odd. The is_even() function first checks if the input integer x is equal to 0. If it is, then it returns True because 0 is an even number. If x is not equal to 0, then it calls the is_odd() function with the argument x-1 and returns the result of that call. The is_odd() function determines whether an integer x is odd by returning the opposite of the result of calling is_even() with the argument x. Finally, the code calls is_odd() and is_even() with the inputs 17 and 23, respectively, and prints the results. Since 17 is an odd number and 23 is an odd number, the program would output: True False indicating that 17 is an odd number and 23 is not even number.
20th Sep 2023, 4:03 PM
Reza Mardani
Reza Mardani - avatar
Reza Mardani In Your description needs correction.. 23 is not even.. Izo tmg ,According to your code, This code uses recursion to determine whether a number is odd or even. #`is_odd(x)`: this checks if the number `x` is odd. #`is_even(x)`: this checks if the number `x` is even. If `x` is equal to 0, it returns True, Otherwise, it calls the function `is_odd(x-1)`. So, the output of the code will be: True ( 17 is odd) False ( 23 is not even)
20th Sep 2023, 4:22 PM
Darpan kesharwani🇮🇳[less active📚]
Darpan kesharwani🇮🇳[less active📚] - avatar
Function is_odd(17) runs like this: 1. Execute "return not is_even(17)" 2. In is_even(17), since 17 is not equal to 0, it execute "return is_odd(16) 3. In is_odd(16) once again call function is_even(x) 4. It gets repeat until is_odd(0), which execute is_even(0), it return True back to the caller is_odd(0), which become "return not True" and return "False" to the original caller is_odd(17), so it become "return not False", thus print out True. Function is_even(23) runs in similar way: 1. Since 23 is not equal to 0, it execute "is_odd(22)" 2. In is_odd(22), and call function is_even(22) 3. It gets repeat until is_odd(0), which call is_even(0) and return "True" back to caller is_odd(0), and it return "True" back to is_even(1), and return "True" back to is_odd(1) until is_odd(23), one step before to the original caller is_ever(23). In is_odd(23) it become "return not True" which turn out to be "False" and return "False" back to original caller is_even(23), thus print out False.
21st Sep 2023, 2:12 AM
Wong Hei Ming
Wong Hei Ming - avatar