livepython.net

194. Python Program to Print the Fibonacci Series up to N Terms

EasyPhase 1 · Warm-up

You need a for loop, two variables and print() with end. You know them all.

Overview

The Fibonacci series is one of the best-known number series. Printing it is a classic interview question, because you must keep track of two values in a loop.

Problem Statement

Ravi builds a game where a garden of flowers grows each day. The number of flowers follows the Fibonacci series.

A term is one number in the series. The first two terms are 0 and 1. Each term after that is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8 and so on.

Read n and print the first n terms on one line, with one space between them.

Steps

  1. Read n and turn it into a whole number.
  2. Keep the two latest terms in two variables. They start as 0 and 1.
  3. Loop n times. In each turn, print the first of the two terms, with a space after it.
  4. Then move one step forward: the new first term is the old second term, and the new second term is the sum of the old two.

Examples

Example 1. Input 7 gives:

0 1 1 2 3 5 8

Why: 0 + 1 = 1, 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5 and 3 + 5 = 8. That makes 7 terms.

Example 2. Input 1 gives:

0

Why: the first term is 0, and only 1 term is asked for.

Input

One whole number n (1 to 50). Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line with the first n terms, with one space between them. A space at the end of the line is fine: the tests ignore it. The tests try 5 different inputs, also 1 and 2.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 10 · For Loops
solution.py
# write your code here

EXPECTED OUTPUT

10 1 1 2 3 5 8

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.