128k views
2 votes
Use Python

The Fibonacci sequence starts 1, 1, 2, 3, 5, 8, . . .. Each number in the sequence (after the first two) is the sum of the previous two. Write a program that computes and outputs the nth Fibonacci number, where n is a value entered by the user.
SAMPLE RUN
--- Prompts For Keyboard/Console/Standard Input ---
Enter n:
Inputs
--- Keyboard/Console/Standard Input stdin ---
4
Outputs
--- Monitor/Console/Standard Output ---
Enter n: 4
The Fibonacci number is 3

User D M
by
4.5k points

1 Answer

5 votes

Answer:

terms = int(input("Enter n? "))

n1 = 0

n2 = 1

count = 0

while count < terms:

nterm = n1 + n2

n1 = n2

n2 = nterm

count += 1

print(n1)

Step-by-step explanation:

This prompts user for n

terms = int(input("Enter n? "))

The next lines initialises the first two terms of the series

n1 = 0

n2 = 1

This initialises count to 0

count = 0

The following iteration is used to determine the number at the nth position

while count < terms:

nterm = n1 + n2

n1 = n2

n2 = nterm

count += 1

This prints the required number

print(n1)

User Alexandr Kapshuk
by
5.4k points