Python. Why 2? Почему 2? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

Python. Why 2? Почему 2?

Eng: I can't figure out, why this code outputs 2. It needs to return 0 in the last loop, becouse 'a' or 'b' or both wiil be equal 0 and print 1. But it returns 2. If there will be '2 + sum(a-1, b-1)', it will return 4 and so on. Please help me solve this magic! Rus: Помогите понять эту магию. Вроде функция должна вызывать саму себя до тех пор, пока 'a' или 'b' не будет равно 0 или оба аргумента не будут равны нулю, тогда она вернёт 0. Но почему-то, когда она возвращает 0, она печатает не 1, а 2. Если вместо 1 прибавить 2, то распечатается 4. И так далее. Словно вместо нуля число прибавляет само себя. Никак не пойму, что тут происходит. Пробовал выводить значения переменных на разных этапах - не помогло, все равно вся магия заключается в строчке 'return 1 + sum(a-1, b-1)'. Буду благодарен за помощь! def sum(a,b): if a==0 or b==0: return 0 return 1 + sum(a-1, b-1) print sum(4,2)

20th Sep 2019, 10:39 AM
ConvertToRGB
2 Réponses
+ 5
Sum(4,2) returning sum(3,1)+1 Sum(3,1) returning sum(2,0)+1 Sum(2,0) returning 0 So, sum(3,1) returning 1+0 And sum(4,2) returning 1+1+0 equal 2 And then the anawer is 2. FOLLOW ME PLS😅👌😁
20th Sep 2019, 10:54 AM
KfirWe
KfirWe - avatar
+ 2
KfirWe, this means, that 'return' remembers previous value result and then summarizes values in previous iterations before output it to 'print' function. Didn't know that! Thanks! Jay Matthews, ty for answer! Output is the same. But I forgot, that I can change not only the code, but input values too.😅
20th Sep 2019, 11:13 AM
ConvertToRGB