fibonacci number in python code example
Example 1: fibonacci sequence python
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)
def fib2(num):
a, b = 1, 1
for _ in range(num - 1):
a, b = b, a + b
return a
print(fib(6))
print(fib2(6))
Example 2: how to create fibonacci sequence in python
n = int(input("Enter the value of 'n': "))
a = 0
b = 1
sum = 0
count = 1
print("Fibonacci Series: ", end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a = b
b = sum
sum = a + b
Example 3: python fibonacci
def Fibonacci( pos ):
if pos <= 1 :
return 0
if pos == 2:
return 1
n_1 = Fibonacci( pos-1 )
n_2 = Fibonacci( pos-2 )
n = n_1 + n_2
return n
nth_fibo = Fibonacci( 5 )
print (nth_fibo)
Example 4: fibonacci sequence python
num = 1
num1 = 0
num2 = 1
import time
for i in range(0, 10):
print(num)
num = num1 + num2
num1 = num2
num2 = num
time.sleep(1)
Example 5: fibonacci series in python
nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
Example 6: fibonacci sequence python
def fib(n):
a = 0
b = 1
print(a)
print(b)
for i in range(2, n):
print(a+b)
a, b = b, a + b
fib(7)