Python Programs

You might also like

Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 4

1. Write a python code to generate the Fibonacci series till n.

Get n from user and pass as


argument to a function.

n=int(input(“enter a”))
def fibonacci(n):
a=c=0
b=1
for i in range(n+1):
print(c)
a=b
b=c
c=b+a
r=fibonacci(n)
print(r)

Output:
enter a: 5
0
1
1
2
3
5
none

2. Write a python code to compute the GCD of two numbers using functions

n=int(input(“enter a:”}}

m=int(input(“enter b:”)

def gcd(x,y):

If x>y:

dd=y

Else:

dd=x

for i in range(1,dd+1):

If x%i==0 and y %i==0:

d=i

return d

num=gcd(n,m)
print(“gcd of n and m “,num)

OUTPUT:

enter a:64

3. Write a python code to find the square and cube of a number by using functions

n=int(input(“enter a”))

def square(n):

r=n*n

q=n*n*n

print(“square”,r,”\ncube”,q)

square(n)

OUTPUT:

enter a: 8

square 64

cube 512

4. Write a python code using functions to find the sum of odd and sum of even numbers entered
by the user.

n=int(input(“enter a”))

def sum(n):

odd=even=0

for i in range(1,n+1):

if 1%2!=0:

even=even+i

else:

odd=odd+i

print(“sum of even:”,even,”\nsum of odd:”,odd)


sum(n)

OUTPUT:

enter a10

sum of even: 25

sum of odd: 30

5. Write a python code using functions to find the prime numbers in a range from 2 to 50.

def prime():

for i in range(2,51,1)

for j in range(2,51,1):

if i%j==0:

break

if i==j:

print(i)

print(“prime number from 2 to 50”)

prime()

OUTPUT:

Prime number from 2 to 50

11

13

17

19

23

29
31

37

41

43

47

You might also like