Python By Example

Print Fibonacci numbers up to N

by Jiffin Joachim Gomez on 11th December 2017

The Fibonacci sequence of numbers are as below:
0, 1, 1, 2, 3, 5, 8, 13,..
The first two numbers in this sequence are 0 and 1. The next number in the sequence is obtained by adding the previous two numbers. Hence the third number is 0 + 1 = 1, fourth number is 1 + 1 = 2, fith number is 1 + 2 = 3 and so on...

Here is a Python program to print the first N numbers in the Fibonacci sequence.

This program prompts the user to input the number up to which the Fibonacci sequence is to be printd. Using a while loop the next number in the sequence is calculated and printed until the next number is less than the number entered by the user.

Program Sources

# Python program to print first N numbers
# in a Fibonacci sequence
i, j = 0, 1

# Taking input from the user
n  = int(input("Input any number: "))

print(i)
while j < n:
    print(j)
    i, j = j, i + j

Program Output

Input any number: 30
0
1
1
2
3
5
8
13
21

Post a comment

Comments

Nothing yet..be the first to share wisdom.