Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (19.9k points)

I have the below code to generate fibonacci series upto 'num'

def fibo(num,a=0,b=1):

    while b <= num:

        print(b)

        a, b = b, a+b

        fibo(num,a,b)

fibo(30)

And below is the Output. However if i use 'if' instead of 'while' in my code it works fine. But I wanted to know what is the problem with while here..

1

1

2

3

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

3

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

2

3

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

3

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

1

2

3

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

3

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

2

3

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

3

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

5

8

13

21

21

13

21

21

8

13

21

21

13

21

21

1 Answer

0 votes
by (25.1k points)

This is because you are using both looping and recursion in your code. You need to use either one of them. e.g. if you wish to use loops:

def fibo(num,a=0,b=1):

    while b <= num:

        print(b)

        a, b = b, a+b

if you wish to use recursion:

def fibo(num,a=0,b=1):

    if b <= num:

        print(b)

        a, b = b, a+b

        fibo(num,a,b)

Browse Categories

...