Monday 19 September 2022

Example programs in Python: Fibonacci Series

 Writing Fibonacci Series in Python using if else statement and for loop

Example:1

x=int(input("enter the number of terms "))
y=[]

if x==1:
    z=0
    y.append(z)
    print(y)
elif x==2:
    z=0
    q=1
    y.append(z)
    y.append(q)
    print(y)
else:
    z=0
    q=1
    y.append(z)
    y.append(q)
    for i in range(3,x+1):        
        l=y[i-3]
        m=y[i-2]
        k = l + m
        #k=y[i-1]
        y.append(k)
print(y)

Output

enter the number of terms 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

----------------------------------------------------------------------------------


Example 2: Fibonacci Series

x=int(input("Enter the number of terms: "))
a=0
b=1
print(a,b,end=" ")
for i in range(2,x):
    c = a+b
    print(c,end=" ")
    a=b
    b=c
   
Output

0 1 1 2 3 5 8 13 21 34

No comments:

Post a Comment