Product SiteDocumentation Site

6.2. Fibonacci Series

Let us try to solve Fibonacci series. In this series we get the next number by adding the previous two numbers. So the series looks like 1,1,2,3,5,8,13 .......
#!/usr/bin/env python
a, b = 0, 1
while b < 100:
    print b
    a, b = b, a + b

The output
$ ./fibonacci1.py
1
1
2
3
5
8
13
21
34
55
89

In the first line of the code we are initializing a and b, then looping while b's value is less than 100. Inside the loop first we are printing the value of b and then in the next line putting the value of b to a and a + b to b in the same line.

If you put a trailing comma in the print statement , then it will print in the same line
#!/usr/bin/env python
a, b = 0, 1
while b < 100:
    print b,
    a, b = b, a + b

The output
$ ./fibonacci2.py
1 1 2 3 5 8 13 21 34 55 89