Write a function that takes as input a single integer parameter n and computes the nth Fibonacci Sequence number. The Fibonacci sequence first two terms are 1 and 1. (so, if n = 2, your function should return 1). From there, the previous two values are summed to come up with the next result in the sequence 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, etc.

Respuesta :

Answer:

Following are the code to this question:

def Fibonacci(n):#defining a method Fibonacci that accept a parameter

   a = 1#defining a variable a that holds a value 1

   b = 1#defining a variable b that holds a value 1

   if n <= 0:# Use if to check n value

       print("invalid number")#print message

   elif n == 2:#defining elif that check n equal to 2

        return 1#return 1

   else:#defining else block

       print(a)#print value of a

       print(b)#print value of b

       for i in range(2,n):#defining for loop to calculate series

           s = a + b# add value in s variable

           a = b # interchange value

           b = s# hold s value

           print(s)#print s value

Fibonacci(10)#calling method

Output:

1

1

2

3

5

8

13

21

34

55

Explanation:

In the above-given program code, a method "Fibonacci" is defined, which holds a value "n" in its parameter, and inside the method two-variable "a and b" is defined, that holds a value "1".

  • In the next step, if a block is defined that checks n value is less than equal to 0, it will print "invalid number" as a message.
  • In the elif, it checks n value is equal to 2 it will return a value that is 1.
  • In the else block, it will calculate the Fibonacci series and print its value.