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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #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

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

When I first read through the question I read it wrong.

I thought the exercise was to sum the numbers… So here is the result if you want to sum the numbers ðŸ™‚

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #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

RohanJune 5, 2017 at 12:47 pmdef main():

num=int(input(“Enter the fibo number to be calculated :”))

n1=0

n2=1

fib=0

sum=0

for i in range(num-1):

fib = n1+n2

print(“n1 is”,n1,”n2 is”,n2,”sum is”,fib)

n1=n2

n2=fib

sum=sum+fib

print(fib,”And sum :”,sum+1)#add 1 because starting value of n2=1 is lost

main()