You are on page 1of 22

PYTHON PROGRAMMES

1) WRITE A PROGRAM TO SWAP TWO NUMBERS USING A THIRD


VARIABLE
PROGRAM:
x = int(input("enter no 1:"))
y = int(input("enter no 2:"))
print("original no are:",x,y)
t=x
x=y
y=t
print("after swapping no are:",x,y)

OUTPUT:
enter no 1:2
enter no 2:4
original no are: 2 4
after swapping no are: 4

1
2) WRITE A PROGRAM TO FIND AVERAGE OF TWO NUMBERS

PROGRAM:
x = int(input("enter a no 1:"))
y = int(input("enter a no 2:"))
z = int(input("enter a no 3:"))
print("three no are:",x,y,z)
avg = (x+y+z)/3
print("the average is:",avg)

OUTPUT:
enter a no 1:56
enter a no 2:80
enter a no 3:24
three no are: 56 80 24
the average is: 53.333333333333336

2
3) WRITE A PROGRAM TO ACCEPT THREE NUMBERS AND PRINT THE
LARGEST NUMBER
OUTPUT:
x=y=z=0
x=float(input("enter a no 1 :"))
y=float(input("enter a no 2 :"))
z=float(input("enter a no 3 :"))
max=z
if y>max:
max=y
if x>max:
max=x
print("the largest no is",max)
OUTPUT:
enter a no 1 :23
enter a no 2 :45
enter a no 3 :32
the largest no is 45.0

3
4) WRITE A PROGRAM TO TEST DIVISIBLITY OF A NUMBER BY A
NUMBER
OUTPUT:
n1=int(input("enter no 1:"))
n2=int(input("enter no 2:"))
remainder = n1%n2
if remainder==0:
print(n1,"is divisible by",n2)
else:
print(n1,"is not divisible by",n2)
OUTPUT:
enter no 1:34
enter no 2:67
34 is not divisible by 67

4
5) WRITE A PROGRAM TO FIND AREA OF A TRIANGLE

PROGRAM:
b=float(input("enter a no:"))
h=float(input("enter a no:"))
area=0.5*b*h
print("the area of triangle is",area)
OUTPUT:
enter a no:23
enter a no:89
the area of triangle is 1023.5

5
6) WRITE A PROGRAM TO READ NUMBERS IN ASCENDING ORDER

PROGRAM:
x=int(input("enter a first no:"))
y=int(input("enter a second no:"))
z=int(input("enter a third no:"))
if x<y and x<z:
if y<z:
min,mid,max=x,y,z
else:
min,mid,max=x,z,y
elif y<x and y<z:
if x<z:
min,mid,max=y,x,z
else:
min,mid,max=y,z,x
else:
if x<y:
min,mid,max=z,x,y
else:
min,mid,max+z,y,x
print("Numbers in ascending order:",min,mid,max)
OUTPUT:
enter a first no:23
enter a second no:12
enter a third no:65
Numbers in ascending order: 12 23 65

6
7) WRITE A PROGRAM TO CALCULATE AND PRINT THE SUM OF
EVEN INTEGERS AND ODD INTEGERS OF THE FIRST N NUMBERS

PROGRAM:
n=int(input("upto to which natural no?"))
ctr=1
sum_even=sum_odd=0
while ctr<=n:
if ctr%2==0:
sum_even+=ctr
else:
sum_odd+=ctr
ctr+=1
print("The sum of even integers is",sum_even)
print("The sum of odd integers is",sum_odd)
OUTPUT:
upto to which natural no?43
The sum of even integers is 462
The sum of odd integers is 484

7
8) WRITE A PROGRAM TO CALCULATE THE FACTORIAL OF A
NUMBER
PROGRAM:
num=int(input("enter a number:"))
fact=1
a=1
while a<=num:
fact*=a
a+=1
print("The factorial of",num,"is",fact)
OUTPUT:
enter a number:16
The factorial of 16 is 20922789888000

8
9) WRITE A PROGRAM TO INPUT A STRING AND CHECK IF IT IS A
PALINDROME STRING USING A STRING SLICE
PROGRAM:
s=input("enter a string :")
if (s==s[::-1]):
print(s,"is a palindrome")
else:
print(s,"is not a palindrome ")
OUTPUT:
enter a string :mirarim
mirarim is a palindrome

9
10) WRITE A PROGRAM THAT INPUTS A LIST, REPLICATES IT TWICE
AND THEN PRINT THE SORTED LIST IN ASCENDING AND
DESCENDING ORDER
PROGRAM:
val=eval(input("enter a list:"))
print("Original list",val)
val=val*2
print("Replicated list:",val)
val.sort()
print("sorted in ascending order:",val)
val.sort(reverse = True)
print("sorted in descending order:",val)
OUTPUT:
enter a list:[23,56,67]
Original list [23, 56, 67]
Replicated list: [23, 56, 67, 23, 56, 67]
sorted in ascending order: [23, 23, 56, 56, 67, 67]
sorted in descending order: [67, 67, 56, 56, 23, 23]

10
11) WRITE A PROGRAM TO CREATE A DICTIONARY WITH THE ROLL
NO ,NAME, MARKS OF N STUDENTS IN A CLASS AND DISPLAY THE
NAMES OF STUDENTS WHO HAVE MARKS ABOVE 75
PROGRAM:
no_of_std = int(input("Enter number of students: "))
result = {}
for i in range(no_of_std):
print("Enter Details of student No.", i+1)
roll_no = int(input("Roll No: "))
std_name = input("Student Name: ")
marks = int(input("Marks: "))
result[roll_no] = [std_name, marks]
print(result)
# Display names of students who have got marks more than 75
for student in result:
if result[student][1] > 75:
print("Student's name who get more than 75 marks is/are",(result[student]
[0]))
OUTPUT:
Enter number of students: 3
Enter Details of student No. 1
Roll No: 1
Student Name: ANDREW
Marks: 72
Enter Details of student No. 2
Roll No: 2
Student Name: JOEL
Marks: 77

11
Enter Details of student No. 3
Roll No: 3
Student Name: TOM
Marks: 76
{1: ['ANDREW', 72], 2: ['JOEL', 77], 3: ['TOM', 76]}
Student's name who get more than 75 marks is/are JOEL
Student's name who get more than 75 marks is/are TOM

12
12) WRITE A PROGRAM TO CREATE A THIRD DICTIONARY FROM
TWO DICTIONARIES HAVING SOME COMMON KEYS IN WAY THAT
THE VALUES ARE ADDED IN THE THIRD DICTIONARY
PROGRAM:
dict1 = {'a': 100, 'b': 200, 'c':300}
dict2 = {'a': 300, 'b': 200, 'd':400}
dict3= {}
dict3.update(dict1)
dict3.update(dict2)
for i,j in dict1.items():
for x,y in dict2.items():
if i ==x:
dict3[i] = j+y
print(dict3)
OUTPUT:
{'a': 400, 'b': 400, 'c': 300, 'd': 400}

13
13) WRITE A PROGRAM TO RECEIVE TWO NUMBERS IN A FUNCTION
AND RETURNS THE RESULTS OF ALL ARITHMETIC OPERATIONS ON
THESE NUMBERS
PROGRAM:
def arcalc(x,y):
return x+y,x-y,x*y,x/y
n1=int(input("enter number 1:"))
n2=int(input("enter number 2:"))
add,sub,mult,div=arcalc(n1,n2)
print("sum of given numbers are:",add)
print("subtraction of given numbers are:",sub)
print("product of given numbers are:",mult)
print("division of given numbers are:",div)
OUTPUT:
enter number 1:14
enter number 2:17
sum of given numbers are: 31
subtraction of given numbers are: -3
product of given numbers are: 238
division of given numbers are: 0.8235294117647058

14
14) WRITE A PROGRAM TO CALCULATE SIMPLE INTEREST USING A
FUNCTION INTEREST () THAT CAN RECEIVE PRINCIPAL
AMOUNT ,TIME, RATE AND RETURN CALCULATED SIMPLE INTEREST
PROGRAM:

def interest(principal,time=2,rate=0.10):
return principal*time*rate

prin=float(input("enter a principal amount:"))


print("simple interest with default roi and time values is :")
si1=interest(prin)
print("Rs.",si1)
roi=float(input("enter rate of interest(roi):"))
time=int(input("enter time in years:"))
print("simple interest with you provided roi and time values is:")
si2=interest(prin,time,roi/100)
print("Rs",si2)
OUTPUT:
enter a principal amount:7000
simple interest with default ROI and time values is :
Rs. 1400.0
enter rate of interest(roi):6
enter time in years:3
simple interest with you provided roi and time values is:
Rs 1260.0

15
15) WRITE A PROGRAM TO DISPLAY ALL RECORDS IN A FILE ALONG
WITH LINE/RECORD NUMBER
PROGRAM:
def linenumber():
f=open("ABC.txt","r")
count=1
while True:
line=f.readline()
if line=='':
break
else:
print(count,":",line,end='')
count+=1
f.close()
linenumber()
OUTPUT :
1 : MERCY IS FALLING IS FALLING
2 : MERCY ID FALLING
3 : LIKE SWEET SPRING RAIN
4 : OVER MEE
5 : I BELEIVE YOUR GRACE

16
16) WRITE A PROGRAM TO READ DATA FROM A TEXT FILE AND
COUNT ALL THJE LINES HAVING ‘G’ AS LAST CHARACTER
PROGRAM:
def countendG():
f=open("ABC.txt",'r')
count=0
data=f.read()
words=data.split()
for i in words:
if i[-1]=='G':
count+=1
print(i)
print("Total words ending with 'G':",count)
f.close()
countendG()
OUTPUT:
FALLING
FALLING
FALLING
SPRING
Total words ending with 'G': 4

17
17) WRITE A PROGRAM TO GET ITEM DETAILS (CODE,DESCRIPTION
AND PRICE) FOR MULTIPLE ITEMS FROM THE USER AND CREATE A
CSV FILE BY WRITING ALL THE ITEMS DETAILS IN ONE GO
PROGRAM:
import csv
fh=open("items.csv","w")
iwriter=csv.writer(fh)
ans='y'
itemrec=[['Item_name','description','price']]
print("enter item details")
while ans=='y':
iname=input("enter item code:")
desc=input("enter description:")
price=float(input("enter price:"))
itemrec.append([iname,desc,price])
ans=input("want to enter more items?(y/n)...")
else:
iwriter.writerows(itemrec)
print("Records written successfully.")
fh.close()
OUTPUT:
enter item details
enter item code:AO1
enter description:PENCIL
enter price:5

18
want to enter more items?(y/n)...y
enter item code:AO2
enter description:SHARPENER
enter price:3
want to enter more items?(y/n)...n
Records written successfully.

19
18) WRITE A PROGRAM TO GET STUDENT DATA FROM USER AND
WRITE ONTO A BINARY FILE.THE PROGRAM SHOULD BE ABLE TO
GET DATA FROM THE USER AND WRITE ONTO THE FILE AS LONG AS
THE USER WANTS
PROGRAM:
import pickle
stu={}
stufile=open('stu.dat','wb')
ans='y'
while ans=='y':
rno=int(input("enter roll no:"))
name=input("enter a name:")
marks=float(input("enter marks:"))
stu['roll no']=rno
stu['name']=name
stu['marks']=marks
pickle.dump(stu,stufile)
ans=input("Want more records to enter?(y/n)...")
stufile.close()
OUTPUT:
enter roll no:2
enter a name:joel
enter marks:65
Want more records to enter?(y/n)...y
enter roll no:4
enter a name:george
enter marks:60
Want more records to enter?(y/n)...n

20
19) WRITE A PYTHON PROGRAM TO COPY ALL THE DATA FROM ONE
TEXT FILE TO ANOTHER
PROGRAM:
def copy(s,d):
f1=open(s,"r")
f2=open(d,"w")
data=f1.read()
f2.write(data)
f1.close()
f2.close()
source=input("enter source file(with.txt extension:")
destination=input("enter destination file(with.txt extension:")
copy(source,destination)
print("DATA COPIED SUCCESSFULLY")
OUTPUT:
enter source file(with.txt extension:ABC.txt
enter destination file(with.txt extension:123.txt
DATA COPIED SUCCESSFULLY

21
20) WRITE A PROGRAM TO READ RANDOM LINE FROM A FILE

PROGRAM:
import random
def readrandomline():
f=open("ABC.txt","r")
lines=f.readlines()
length=len(lines)
r1=random.randint(0,length-1)
print(lines[r1])
f.close()
readrandomline()
OUTPUT:
LIKE SWEET SPRING RAIN

======================= RESTART: F:/python programs/jk.py


======================
MERCY ID FALLING

22

You might also like