Fibonacci numbers in Python

In Fibonacci series of numbers, each number is the sum of the two preceding ones.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377
Fn = F(n-1) + F(n-2)


Fibonacci series of numbers by using loop and by recursive functions in Python

Generating Fibonacci Series

We will use while loop
n=15 # number of elements 
i=0  # counter 
n1=1 # One before
n2=0 # two before
while( i<n):
  print(n2, end=', ')
  temp=n1+n2
  n1=n2
  n2=temp
  i = i+1
Output
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 

Using For loop

By using this line we are removing the temp variable.
n1,n2=n2,(n1+n2)
Full code is here
n=15 # number of elements 
n1,n2,i=1,0,0 # Setting the values 
for i in range( 0,n): # 
  print(n2, end=', ')
  n1,n2=n2,(n1+n2) # change the values

Fibonacci series using recursive functions

Using recursive function
def feb(n):
  if(n<=1):
    return n
  else:
    return ((feb(n-1)+feb(n-2)))
for i in range(0,15):
  print(feb(i), end=', ')
Output
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 

All Sample codes Factorial of a Number Armstrong Number
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer