+ 4
Why True or False ??!!! I don't understand this output for this code, please help me
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(18)) print(is_even(24)) False True
4 ответов
+ 2
The output is the last two lines True and False.
False is the result for print(is_odd(18)).
True is the result for print(is_even(24)).
I am not sure what you want explained. Below is the explanation for the function calls. Please let me know what line needs more explanation if you don't understand.
What does is_even return?
1) if input is 0, it returns True
2) otherwise it returns is_odd(x-1)
example: is_even(3) will return whatever is_odd(2) returns
What does is_odd return?
returns the opposite of is_even(x)
example: is_odd(3) will return True because is_even(3) returns False
What does is_odd(18) return?
1) opposite of is_even(18)
2) is_even(18) returns is_odd(17)
3) is_odd(17) returns opposite of is_even(17)
4) is_even(17) returns is_odd(16)
Continue this and you will understand the code.
Happy New Year
0
You can trace it with smaller numbers
e.g. 0,1,2,3
0 is_even’s base case= True
0 is_odd returns not is_even(0) = not True=False
1 is_even returns is_odd(1-1)= is_odd(0)=not is_even(0)=not True, which from above= False
1 is_odd = not is_even(1)= not False=True
2 is_even = is_odd(2-1) = is_odd(1)=True
2 is_odd = not is_even(2)= not True= False
Basically via is_even it drills down to the base case if the remainder is 1.
0
I made a modified code, the output shows in which order the code runs. And I tried to explain with comment:
https://code.sololearn.com/c4rOYS5KEZuw/?ref=app
0
You know that the answer should be “not not not ~~~ not True” So you only need to count for “not”s. When counting, like in the question: is_even(23) must be changed to “is_odd” (because there is no ‘not’ at the first) —> so it is is_odd(22). Then, you should do —> 22-0+1= 23 odd number of “not”s, equals to one “not” which will then equal to “not True” So the answer is False.