Select Page

Python Programming – John Zelle: Chapter 3 ex. 16

#Chapter 3 Exercise 16
A Fibonacci sequence is a sequence of numbers where each successive number is the sum of the previous two.
The classic Fibonacci sequence begins 1, 1, 2, 3, 5, 8, 13,….
Write a program that computes the nth Fibonacci number where the n is a value input by the user

```#Chapter 3 Exercise 16
#A Fibonacci sequence is a  sequence of numbers where each successive number is the sum of the previous two.
#The classic Fibonacci sequence begins 1, 1, 2, 3, 5, 8, 13,....
#Write a program that computes the nth Fibonacci number where the n is a value input by the user

def main():
print("This program that computes the nth Fibonacci number where the n is a value input by the user")
a,b = 1,1
num=eval(input("Please input what Fibonacci number you want to be calculated: "))
num_int=int(num-2)
for i in range (num_int):
a,b=b,a+b
print(b)

main()

```

Run =
This program that computes the nth Fibonacci number where the n is a value input by the user
Please input what Fibonacci number you want to be calculated: 6
8

*****************************************

I thought the exercise was to sum the numbers… So here is the result if you want to sum the numbers 🙂

```#Chapter 3 Exercise 16b
#A Fibonacci sequence is a  sequence of numbers where each successive number is the sum of the previous two.
#The classic Fibonacci sequence begins 1, 1, 2, 3, 5, 8, 13,....
#Write a program that computes the nth Fibonacci number where the n is a value input by the user

print("This program that computes the nth Fibonacci number where the n is a value input by the user")
num = eval(input("how many numbers would you like to sum? "))
def fib(n, a = 0, b = 1):
seq = [a,b]
while len(seq) < n:
seq += [seq[len(seq)-1] + seq[len(seq)-2]]
return seq

b = sum(fib(num + 1))
print(b)

```

This program that computes the nth Fibonacci number where the n is a value input by the user
how many numbers would you like to sum? 9
88