+ 1

how this code function?

guys im doing the python course and i am at recursion. this code is a code of a exercise and the result is 5 but i don't know how this code function. can anyone say me how it works? thanks 0 Pl def fib(x) : if x == 0 or x == 1: return 1 else: return fib(x-1) + fib(x-2)

5th Nov 2021, 7:03 AM
Simone
Simone - avatar
3 Respostas
+ 2
Simone def fib(x) : if x == 0 or x == 1: return 1 else: return fib(x - 1) + fib(x - 2) print (fib(4)) #fib(3) + fib(2) #fib(2) + fib(1) + fib(1) + fib(0) #fib(1) + fib(0) + fib(1) + fib(1) + fib(0) #1 + 1 + 1 + 1 + 1 #5
5th Nov 2021, 7:10 AM
A͢J
A͢J - avatar
+ 2
This is an example of recursive function. A recursive function is a function which calls itself repeatedly until a termination condition is met, after when it returns a value. Here your function works as below for the call fib(4): fib(4) fib(3) + fib(2) fib(2)+fib(1) + fib(1)+fib(0) fib(2)+ 1 + 1 + 1 fib(1)+fib(0) + 3 1 + 1 + 3 5 And finally return the value 5. Hope you understood =)
5th Nov 2021, 7:11 AM
Rishi
Rishi - avatar
0
ok thank very much, now i understand
5th Nov 2021, 12:36 PM
Simone
Simone - avatar