In this tutorial, we will learn how to print the Fibonacci sequence using a loop in Python. We will cover the basic loop structure to generate the Fibonacci sequence.
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence starts as 0, 1, 1, 2, 3, 5, 8, and so on.
The syntax to print the Fibonacci sequence using a loop in Python is:
def fibonacci_loop(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
We can use a loop to generate and print the Fibonacci sequence up to the n-th term.
For example,
fibonacci_loop
that takes one parameter n
.a
and b
, to 0 and 1 respectively.for
loop to iterate n
times.a
and update a
and b
to the next numbers in the sequence.def fibonacci_loop(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
# Print the first 10 terms of the Fibonacci sequence
fibonacci_loop(10)
0 1 1 2 3 5 8 13 21 34