## Thursday, March 14, 2019

### Python script for Fibonacci sequence using while loop or recursion

Python script for Fibonacci sequence using while loop or recursion.

Using recursive function:

```#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 05:32:45 2019

@author: milospjanic
"""

# Python program to display the Fibonacci sequence up to n-th term using recursive functions

def recur_fibo(n):
"""Recursive function to
print Fibonacci sequence"""
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

# Change this value for a different result
#nterms = 10

# uncomment to take input from the user
nterms = int(input("How many terms? "))

# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):```
print(recur_fibo(i), end=" , ")```

Using while loop:

```#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 05:22:28 2019

@author: milospjanic
"""

# Program to display the Fibonacci sequence up to n-th term where n is provided by the user

# change this value for a different result
#nterms = 10

# uncomment to take input from the user
nterms = int(input("How many terms? "))

# first two terms
n1 = 0
n2 = 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 upto",nterms,":")
while count < nterms:
print(n1,end=" , ")
n3 = n1 + n2
# update values
n1 = n2
n2 = n3
count += 1```

#### 1 comment:

1. Thank you so much for posting this. I really appreciate your work. Keep it up. Great work!Best software training company with placement in Hyderabad