Python : WAP to to Print the Fibonacci sequence

Fibonacci sequence

Fibonacci sequence के पहले दो शब्द 0 और 1 हैं। अन्य सभी शब्द को पूर्व के दो शब्दों को जोड़कर प्राप्त किया जाता हैं। Fibonacci sequence एक integer sequence है |

For Example:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ..so on

0+1 =1

1+1 = 2

1+2 = 3

2+3 = 5

3+5 = 8

5+8 = 13

8+ 13 = 21 और ….

आज के इस प्रोग्राम मे हम Fibonacci sequence को  while loop का उपयोग करके print करना सीखेंगे।

Fibonacci sequence के इस प्रोग्राम को समझने के लिए आपको पाइथन control statement और loops को समझना पड़ेगा |

Using While loop 


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

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

if n <= 0:
   print("Please enter a positive integer number ")
elif n == 1:
   print("Fibonacci sequence upto", n ," :")
   print(n1)
else:
   print("Fibonacci sequence: ")
   while count < n:
       print(n1)
       n3 = n1 + n2
       n1 = n2
       n2 = n3
       count += 1

Output : 
How many terms? 8
Fibonacci sequence:
0
1
1
2
3
5
8
13

Using Recursion


def recur_fibonacci(n):
   if n <= 1:
       return n
   else:
       return(recur_fibonacci(n-1) + recur_fibonacci(n-2))
n = int(input("How many terms? "))

if n <= 0:
   print("Plese enter a positive integer")
else:
   print("Fibonacci sequence:")
   for i in range(n):
       print(recur_fibonacci(i))

Output 
How many terms? 4
Fibonacci sequence:
0
1
1
2

Using for loop 

num = int(input("How many terms? : "))
x= 0
y = 1

for i in range (0,num):
    print(x)
    z=x+y
    x=y
    y=z

OUTPUT : 
How many terms? : 7
0
1
1
2
3
5
8

 Python : WAP to check Armstrong number
 Python : WAP to print factorial of any number