55.2k views
3 votes
A python script to print fibonacci series first 20 elements

2 Answers

0 votes

Final answer:

To print the first 20 elements of the Fibonacci series in Python, a function can be used which iterates through a specified number of elements, updating and printing the next number in the sequence in each step.

Step-by-step explanation:

The Fibonacci series is a sequence where each number is the sum of the two preceding ones, usually starting with 0 and 1. To print the first 20 elements of the Fibonacci sequence in Python, you can use the following script:

fibonacci.py

def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b

fibonacci(20)

This script uses a simple loop to generate the series and prints out each element. The variables a and b start with values 0 and 1, which are the first two numbers in the Fibonacci sequence. Each iteration of the loop updates the values of 'a' and 'b' to the next two numbers in the sequence, and 'a' is printed out each time. Running this script will output the first 20 numbers of the Fibonacci series.

0 votes

Answer:

nterms =20

# first two terms

n1, n2 = 0, 1

count = 0

# check if the number of terms is valid

if nterms <= 0:

print("Please enter a positive integer")

elif nterms == 1:

print("Fibonacci sequence upto",nterms,":")

print(n1)

else:

print("Fibonacci sequence:")

while count < nterms:

print(n1)

nth = n1 + n2

# update values

n1 = n2

n2 = nth

count += 1

Step-by-step explanation:

Here, we store the number of terms in nterms. We initialize the first term to 0 and the second term to 1.

If the number of terms is more than 2, we use a while loop to find the next term in the sequence by adding the preceding two terms. We then interchange the variables (update it) and continue on with the process.

output:

Fibonacci sequence:

0

1

1

2

3

5

8

User Zvezda
by
4.9k points