0
Q:

fibonacci series for loop 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 faster
3
# # this is the fibonacci series by KV for for loop :)

n = int(input(":"))
for i in range(1,n+1):
    print(i, end = "")
0
# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms
n1, n2 = 0, 1
count = 0

# check if the number of terms is valid
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
       # update values
       n1 = n2
       n2 = nth
       count += 1
5
#Recursive Solutions
def fibo(n):
  if n<=1: return 1
  return fibo(n-1)+fibo(n-2)

fibo(5)
#OUTPUT:
#120
0
nterms = int(input("How many terms? "))

# first two terms
n1, n2 = 0, 1
count = 0

# check if the number of terms is valid
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
       # update values
       n1 = n2
       n2 = nth
       count += 1
        
0

New to Communities?

Join the community