1def fib(num):
2 a = 0
3 b = 1
4 for i in range(num):
5 yield a
6 temp = a
7 a = b
8 b = temp + b
9
10
11for x in fib(100):
12 print(x)
13
14
15def fib2(num): # Creates fib numbers in a list
16 a = 0
17 b = 1
18 result = []
19 for i in range(num):
20 result.append(a)
21 temp = a
22 a = b
23 b = temp + b
24 return result
25
26
27print(fib2(100))
28
1#Python program to generate Fibonacci series until 'n' value
2n = int(input("Enter the value of 'n': "))
3a = 0
4b = 1
5sum = 0
6count = 1
7print("Fibonacci Series: ", end = " ")
8while(count <= n):
9 print(sum, end = " ")
10 count += 1
11 a = b
12 b = sum
13 sum = a + b
14
1# WARNING: this program assumes the
2# fibonacci sequence starts at 1
3def fib(num):
4 """return the number at index `num` in the fibonacci sequence"""
5 if num <= 2:
6 return 1
7 return fib(num - 1) + fib(num - 2)
8
9# method 2: use `for` loop
10def fib2(num):
11 a, b = 1, 1
12 for _ in range(num - 1):
13 a, b = b, a + b
14 return a
15
16
17print(fib(6)) # 8
18print(fib2(6)) # same result, but much faster
1def Fibonacci( pos ):
2 #check for the terminating condition
3 if pos <= 1 :
4 #Return the value for position 1, here it is 0
5 return 0
6 if pos == 2:
7 #return the value for position 2, here it is 1
8 return 1
9
10 #perform some operation with the arguments
11 #Calculate the (n-1)th number by calling the function itself
12 n_1 = Fibonacci( pos-1 )
13
14 #calculation the (n-2)th number by calling the function itself again
15 n_2 = Fibonacci( pos-2 )
16
17 #calculate the fibo number
18 n = n_1 + n_2
19
20 #return the fibo number
21 return n
22
23#Here we asking the function to calculate 5th Fibonacci
24nth_fibo = Fibonacci( 5 )
25
26print (nth_fibo)
1# Implement the fibonacci sequence
2 # (0, 1, 1, 2, 3, 5, 8, 13, etc...)
3 def fib(n):
4 if n== 0 or n== 1:
5 return n
6 return fib (n- 1) + fib (n- 2)
1# WARNING: this program assumes the
2# fibonacci sequence starts at 1
3def fib(num):
4 """return the number at index num in the fibonacci sequence"""
5 if num <= 2:
6 return 1
7 return fib(num - 1) + fib(num - 2)
8
9
10print(fib(6)) # 8