Zed-King Institute

    Python Program to Print Fibonacci Series

    mediumLoopsPython

    In the Fibonacci series each term is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8 …

    The question

    Read n and print the first n terms of the Fibonacci series, starting 0 1 1 2 3 …, on one line separated by spaces.

    The code

    program.py

    n = int(input())
    a, b = 0, 1
    for _ in range(n):
        print(a, end=" ")
        a, b = b, a + b
    print()

    Input

    10

    Output

    0 1 1 2 3 5 8 13 21 34

    How it works

    1. 1Keep the last two terms in a and b, starting with 0 and 1.
    2. 2Print a, then move forward with a, b = b, a + b — both values change at the same moment.
    3. 3end=" " keeps all the terms on one line; the final print() ends that line.

    Common mistakes

    • Updating in two lines (a = b then b = a + b) — a has already changed, so the series goes wrong.
    • Starting from 1 1 when the question starts the series at 0.

    Now solve a similar question yourself

    A new Python question every time, checked instantly.

    Practice questions

    More in Loops