fibonacci sequence python for loop code example
Example 1: fibonacci sequence python
# WARNING: this program assumes the
# fibonacci sequence starts at 1
def fib(num):
"""return the number at index `num` in the fibonacci sequence"""
if num <= 2:
return 1
return fib(num - 1) + fib(num - 2)
# method 2: use `for` loop
def fib2(num):
a, b = 1, 1
for _ in range(num - 1):
a, b = b, a + b
return a
print(fib(6)) # 8
print(fib2(6)) # same result, but much faster
Example 2: fibonacci series in python
#Recursive Solutions
def fibo(n):
if n<=1: return 1
return fibo(n-1)+fibo(n-2)
fibo(5)
#OUTPUT:
#120
Example 3: python fibonacci sequence generator
number1 = 0
print('1:', number1)
number2 = 1
for count in range(2, 101):
print(count, ':', number1 + number2)
number1 += number2
number2 = number1 - number2
Example 4: fibonacci series for loop python
# # this is the fibonacci series by KV for for loop :)
n = int(input(":"))
for i in range(1,n+1):
print(i, end = "")