Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python printing the Fibonacci sequence

Python printing the Fibonacci sequence

Document Object Reference Manual Python3 Examples

The Fibonacci sequence is a classic mathematical problem where each number is the sum of the previous two. The first two numbers of the sequence are usually defined as 0 and 1. We can use Python to write a simple program to print the first n terms of the Fibonacci sequence.

Example

def

fibonacci

(

n

)

:

    fib_sequence

=

[

]

    a

,

b

=

0

,

1

   

for

_

in

range

(

n

)

:

        fib_sequence.

append

(

a

)

        a

,

b

=

b

,

a + b

   

return

fib_sequence

n

=

10

 

Print the first 10 terms

print

(

fibonacci

(

n

)

)

Code analysis:

  1. def fibonacci(n): defines a class named fibonacci function, which takes a parameter n, representing the number of Fibonacci terms to print.
  2. fib_sequence = [] Initialize an empty list fib_sequence, used to store the Fibonacci sequence.
  3. a, b = 0, 1 Initialize two variables a and b, representing the first two numbers of the Fibonacci sequence.
  4. for _ in range(n): Use a loop to generate the first n terms of the Fibonacci sequence.
  5. fib_sequence.append(a) Add the current a value to fib_sequence list.
  6. a, b = b, a + b update a and b value, so that a becomes b,b becomes a + b, which is the next Fibonacci number.
  7. return fib_sequence Return the generated Fibonacci sequence.
  8. n = 10 Set the number of Fibonacci terms to print to 10.
  9. print(fibonacci(n)) called fibonacci function and print the result.

Output result:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Document Object Reference Manual Python3 Examples