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
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
1def fib(n):
2 a = 0
3 b = 1
4
5 print(a)
6 print(b)
7
8 for i in range(2, n):
9 print(a+b)
10 a, b = b, a + b
11
12fib(7) #first seven nubers of Fibonacci sequence
1num = 1
2num1 = 0
3num2 = 1
4import time
5for i in range(0, 10):
6 print(num)
7 num = num1 + num2
8 num1 = num2
9 num2 = num
10 time.sleep(1)
11
1# This program also assumes the fibonacci sequence starts at 1
2# This code will print as many digits as the user wishes
3# Instead of printing a specific number in the sequence
4def fibonacci(digits):
5
6 digit1, digit2 = 1, 1
7 amount_of_digits = 0
8 print(str(digit1) + ", " + str(digit2) + ', ', end='')
9
10 while amount_of_digits != digits:
11 digit1, digit2 = digit2, digit1 + digit2
12 print(str(digit2) + ", ", end='') # we want to print on the same line
13 amount_of_digits = amount_of_digits + 1
14
15 if amount_of_digits == digits:
16 print('\n')
17 print('Loop done.')
18 break
19
20fibonacci(10) # this will print the first 10 digits in the sequence
1#Learnprogramo
2Number = int(input("How many terms? "))
3# first two terms
4First_Value, Second_Value = 0, 1
5i = 0
6if Number <= 0:
7print("Please enter a positive integer")
8elif Number == 1:
9print("Fibonacci sequence upto",Number,":")
10print(First_Value)
11else:
12print("Fibonacci sequence:")
13while i < Number:
14print(First_Value)
15Next = First_Value + Second_Value
16# update values
17First_Value = Second_Value
18Second_Value = Next
19i += 1