Python bootcamp · Lab 11

Fibonacci sequence

mediumWhile Loops12 minLesson: While Loops

Read the question, write Python on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read n and print the first n Fibonacci numbers on one line, separated by spaces.

The sequence starts 0, 1, and each next number is the sum of the two before it.

Input. One line: an integer n ≥ 1.

Output. n space-separated numbers starting 0 1 1 2 3 …

Constraints

  • 1 ≤ n ≤ 50

Examples

Example 1
Input
7
Output
0 1 1 2 3 5 8
Example 2 — Just the first term.
Input
1
Output
0
Hint
  1. The swap a, b = b, a + b advances the pair in one clean line — no temp variable.
  2. Collect the terms in a list, then print(*seq).
Show correct code

Peek only after you have tried. You can still Check your own version.

n = int(input())
a, b = 0, 1
seq = []
for _ in range(n):
    seq.append(a)
    a, b = b, a + b
print(*seq)
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.