0% found this document useful (0 votes)
13 views

python prgm

The document contains multiple Python programs that perform various tasks such as electricity billing, retail shop billing, calculating unit weight of steel bars, and swapping numbers. It also includes programs for calculating distances, generating number patterns, managing lists and dictionaries, and calculating areas of shapes. Each program is accompanied by sample inputs and outputs demonstrating their functionality.

Uploaded by

zabuzarkhan00
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

python prgm

The document contains multiple Python programs that perform various tasks such as electricity billing, retail shop billing, calculating unit weight of steel bars, and swapping numbers. It also includes programs for calculating distances, generating number patterns, managing lists and dictionaries, and calculating areas of shapes. Each program is accompanied by sample inputs and outputs demonstrating their functionality.

Uploaded by

zabuzarkhan00
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

PROGRAM:

# Electricity billing
Unit = int(input(“Enter the number of units:”))
L = [0],[0,1,5],[0,2,3],[0,3,5,4.6,6.6]]
Bill =0
if(Unit>= 0 and Unit<=100):
Bill = 0
elif(Unit<=200):
Bill = (Unit – 100)*L[1][1]
elif(Unit<=500):
Bill =100*L[2][1]+(Unit-200)*L[2][2]
else:
Bill = 100*L[3][1]+300*L[3][2]+(Unit-500)*L[3][3]
print(“Unit:”, Unit)
print(“Bill: Rs”, Bill)

OUTPUT:
Enter number of units: 500
Unit: 500
Bill: Rs 1100
PROGRAM:
# Retail Shop Billing
Tax =0.5
Rate={'Shirt': 250, 'Saree': 650, 'T-Shirt': 150, 'Trackpant': 150}
print('Retail Bill Calculator')
Bill = int(input('Enter the quantity of the ordered items'))
Shirt = int(input('Shirt:'))
Saree = int(input('Saree:'))
TShirt = int(input('TShirt:'))
Trackpant = int(input('Trackpant:'))
Cost = Shirt*Rate['Shirt']+ Saree*Rate['Saree']+ TShirt*Rate['T-
Shirt']+Trackpant*Rate['Trackpant']
Bill = Cost + Cost*Tax
print('Please pay Rs.%f'%Bill)
OUTPUT:
ENTER THE QUANTITY OF THE ORDERED ITEMS : 3
Shirt : 1
Saree: 1
TShirt:1
Trackpant:0
Please pay Rs. 1575.000000
PROGRAM:
#UNIT WEIGHT OF STEEL BARS
D=float(input("Enter Diameter of steel bars in mm:") )
W=D*D/162
print("Unit Weight of the steel bar is {:.4f} kg/m ".format(W))

OUTPUT:
Enter Diameter of steel bars in mm:20
Unit Weight of the steel bar is 2.4691 kg/m
PROGRAM:
# WEIGHT OF MOTORBIKE
Mb1 = 30000
Mb2 = 40000
print("Enter your order items:")
num = int(input(" Number of Motror bike1: "))
num1= int(input(" Number of Motor bike2: "))
total_weight = num*Mb1 + num1*Mb2
print("Your order total weight is:",total_weight,"gm")

OUTPUT:
Enter your order items:
Number of Motror bike1: 2
Number of Motor bike2: 3
Your order total weight is: 180000 gm
PROGRAM:
# Sine series
x = int(input("Enter the value of x: "))
n = int(input("Enter the value of n: "))
sign = -1
fact = i =1
sum = 0
while i<=n:
p=1
fact = 1
for j in range(1,i+1):
p = p*x
fact = fact*j
sign = -1*sign
sum = sum + sign* p/fact
i = i+2
print("sin(",x,") =",sum)
OUTPUT:
Enter the value of x: 2
Enter the value of n: 3
sin( 2 ) = 0.6666666666666667
PROGRAM:
# SWAPPING OF TWO NUMBERS USING TEMPORARY VARIABLE
X=int(input("Enter the value of X:") )
Y=int(input("Enter the value of Y:") )
print("Before Swapping ")
print("X=",X,"Y=",Y)
Temp=X
X=Y
Y=Temp
print("After Swapping ")
print("X=",X,"Y=",Y)

OUTPUT:
Enter the value of X:1
Enter the value of Y:2
Before Swapping
X= 1 Y= 2
After Swapping
X= 2 Y= 1
PROGRAM:
# SWAPPING OF TWO NUMBERS WITHOUT USING TEMPORARY
VARIABLE
X=int(input("Enter the value of X:") )
Y=int(input("Enter the value of Y:") )
print("Before Swapping ")
print("X=",X,"Y=",Y)
X=X+Y
Y=X-Y
X=X-Y
print("After Swapping ")
print("X=",X,"Y=",Y)

OUTPUT:
Enter the value of X:1
Enter the value of Y:2
Before Swapping
X= 1 Y= 2
After Swapping
X= 2 Y= 1
PROGRAM:
# SWAPPING OF TWO NUMBERS USING TUPLE ASSIGNMENT
X=int(input("Enter the value of X:") )
Y=int(input("Enter the value of Y:") )
print("Before Swapping ")
print("X=",X,"Y=",Y)
X,Y=Y,X
print("After Swapping ")
print("X=",X,"Y=",Y)

OUTPUT:
Enter the value of X:1
Enter the value of Y:2
Before Swapping
X= 1 Y= 2
After Swapping
X= 2 Y= 1
PROGRAM:
# DISTANCE BETWEN TWO POINTS
import math
X1=float(input("Enter the value of X1:") )
Y1=float(input("Enter the value of Y1:") )
X2=float(input("Enter the value of X2:") )
Y2=float(input("Enter the value of Y2:") )
distance = math.sqrt ( (X2 - X1)**2 +(Y2 - Y1)**2 )
print("Distance is {:.4f}".format(distance))

OUTPUT:
Enter the value of X1:2
Enter the value of Y1:3
Enter the value of X2:4
Enter the value of Y2:5
Distance is 2.8284
PROGRAM:
# DISTANCE BETWEN TWO POINTS
P1=[2.0,3.0]
P2=[4.0,5.0]
distance = ( (P2[0] - P1[0])**2 +(P2[1] - P1[1])**2 )**0.5
print("Distance is {:.4f}".format(distance))

OUTPUT:
Distance is 2.8284
PROGRAM:
def circulate(A,N):
for i in range (1, N+1):
B = A[i:]+A[:i]
print(“ Circulation”,i,“=”,B)
return
A = [91,92,93,94,95]
N = int(input(“Enter n:”))
circulate (A,N)

OUTPUT:
Enter n 5
(Circulation, 1 = [92,93,94,95,91])
(Circulation, 2 = [93,94,95,91, 92])
(Circulation, 3 = [94,95,91, 92,93])
(Circulation, 4 = [95,91, 92, 93,94])
(Circulation, 5 = [91, 92, 93,94, 95])
PROGRAM:
n=int(input(“Enter a number”))
Sum = 0
i=1
while i<=n:
Sum = Sum + i*i
i+=1
print(“Sum=”,Sum)

OUTPUT:
Enter a number 10
Sum= 385
PROGRAM:
# NUMBER PATTERNS
N=int(input("Enter number of Lines : "))
print("Number Triangle : ")
for i in range(0,N+1,1):
for val in range(1,i+1,1):
print(i, end=" ")
print()

OUTPUT:
Enter number of Lines: 5
Number Triangle:
1
22
333
4444
55555
PROGRAM:
# PYRAMID PATTERN
n=int(input("Enter the number of lines:"))
print(“pyramid star pattern:”)
for n in range(1,N+1,1):
print(“” *(N-n),end= “”)
print(“*”*((2*n)-1))

OUTPUT:
Enter the number of lines:
*
***
*****
*******
*********
PROGRAM:
carparts =['Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery']
print(carparts)
print(carparts[0])
print(carparts[1])
print(carparts.index('Wheel'))
print(len(carparts))
carparts.append('Headlights')
print(carparts)
carparts.insert(2,'Radiator')
print(carparts)
carparts.remove('Headlights')
print(carparts)
carparts.pop(2)
print(carparts)
carparts[2]='Tyre'
print(carparts)
carparts.sort()
print("After sorting: ",carparts)
carparts.reverse()
print("Reversed list: ", carparts)
New = carparts[:]
print(New)
x = slice(2)
print(carparts[x])
test_list1 = [1, 4, 5, 6, 5]
test_list2 = [3, 5, 7, 2, 5]
for i in test_list2 :
test_list1.append(i)
print("Concatenated list using naive method : ", str(test_list1))

OUTPUT:
['Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery']
Engine
Transmission
2
6
['Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery',
'Headlights']
['Engine', 'Transmission', 'Radiator', 'Wheel', 'Gear', 'Brake', 'Battery',
'Headlights']
['Engine', 'Transmission', 'Radiator', 'Wheel', 'Gear', 'Brake', 'Battery']
['Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery']
['Engine', 'Transmission', 'Tyre', 'Gear', 'Brake', 'Battery']
After sorting: ['Battery', 'Brake', 'Engine', 'Gear', 'Transmission', 'Tyre']
Reversed list: ['Tyre', 'Transmission', 'Gear', 'Engine', 'Brake', 'Battery']
['Tyre', 'Transmission', 'Gear', 'Engine', 'Brake', 'Battery']
['Tyre', 'Transmission'] Concatenated list using naive method : [1, 4, 5,
6, 5, 3, 5,7,2,5]
PROGRAM:
Building_materials = ["Cement", "Bricks", "Sand", "Steel rod",
"Paint"]
print("Building Materials: ", Building_materials)
print("First Material: ", Building_materials[0])
print("Fourth Material: ", Building_materials[3])
print("Items in Building Materials from 0 to 4 index: ",
Building_materials[0:5])
item = input("Enter the Item to be appended: ")
Building_materials.append(item)
print("Building Materials after append(): ", Building_materials)
item = input("Enter the Item to find index position: ")
print("Index position of {} is {}".format(item,
Building_materials.index(item)))
Building_materials.sort()
print("after sorting: ", Building_materials)
print("popped element is: ", Building_materials.pop())
print("after deleting Last element: ", Building_materials)
item = input("Enter the Item to be deleted: ")
Building_materials.remove(item)
print("after removing: ", Building_materials)
item = input("Enter the Item to be inserted: ")
index = int(input("Enter the index where the Item to be inserted: "))
Building_materials.insert(index, item)
print("Building Materials after insert: ", Building_materials)
OUTPUT:
Building Materials: ['Cement', 'Bricks', 'Sand', 'Steel rod', 'Paint']
First Materialt: Cement
Fourth Material: Steel rod
Items in Building Materials from 0 to 4 index: ['Cement', 'Bricks',
'Sand', 'Steel rod', 'Paint']
Enter the Item to be appended :Plan
Building Materials after append() ['Cement', 'Bricks', 'Sand', 'Steel
rod', 'Paint', 'Plan']
Enter the Item to find index position: Sand
Index position of Sand is 2
after sorting: ['Bricks', 'Cement', 'Paint', 'Plan', 'Sand', 'Steel rod']
popped element is: Steel rod
after deleting Last element ['Bricks', 'Cement', 'Paint', 'Plan', 'Sand']
Enter the Item to be deleted :Plan
after removing ['Bricks', 'Cement', 'Paint', 'Sand']
Enter the Item to be inserted :Rod
Enter the index where the Item to be inserted :2
Building Materials after insert ['Bricks', 'Cement', 'Rod', 'Paint', 'Sand']
PROGRAM:
Building_materials={1:"Cement",2:"Bricks",3:"Sand",4:"Steel
rod",5:"Paint"}
print("Building Materials: ",Building_materials)
print("Display using items() method ")
print(Building_materials.items())
print("Dictionary key and values")
print(Building_materials.keys())
print(Building_materials.values())
item=input("Enter the Item to be appended :")
Building_materials[6]=item
print(Building_materials.items())
# Deleting Elements
index=int(input("Enter the key of the item to be deleted :"))
Building_materials.pop(index)
print("after removing " ,Building_materials)
# to clear the entire content of Dictionary
Building_materials.clear()
print(Building_materials)
OUTPUT:
Building Materials: {1: 'Cement', 2: 'Bricks', 3: 'Sand', 4: 'Steel rod', 5:
'Paint'}
Display using items() method
dict_items([(1, 'Cement'), (2, 'Bricks'), (3, 'Sand'), (4, 'Steel rod'), (5,
'Paint')])
Dictionary key and values
dict_keys([1, 2, 3, 4, 5])
dict_values(['Cement', 'Bricks', 'Sand', 'Steel rod', 'Paint'])
Enter the Item to be appended :Plan
dict_items([(1, 'Cement'), (2, 'Bricks'), (3, 'Sand'), (4, 'Steel rod'), (5,
'Paint'), (6, 'Plan')])
Enter the key of the item to be deleted :3
after removing {1: 'Cement', 2: 'Bricks', 4: 'Steel rod', 5: 'Paint', 6:
'Plan'}
{}
PROGRAM:
components1={'Engine','Chassis','Transmission'}
components2={'Steering','Tyre','Engine'}
print(components1)
print(components2)
components1.add('Gearbox')
print(components1)
components1.remove('Gearbox')
print(components1)
print(components1 | components2)
print(components2.union(components1))
print(components1 & components2)
print(components1.intersection(components2))
print(components1 - components2)
print(components2.difference(components1))
print(components1 ^ components2)
OUTPUT:
{'Engine', 'Transmission', 'Chassis'}
{'Engine', 'Steering', 'Tyre'}
{'Engine', 'Transmission', 'Chassis', 'Gearbox'}
{'Engine', 'Transmission', 'Chassis'}
{'Engine', 'Transmission', 'Chassis', 'Steering', 'Tyre'}
{'Engine', 'Transmission', 'Chassis', 'Steering', 'Tyre'}
{'Engine'}
{'Engine'}
{'Transmission', 'Chassis'}
{'Steering', 'Tyre'}
{'Chassis', 'Tyre', 'Transmission', 'Steering'}
PROGRAM:
# FACTORIAL OF A NUMBER
def Fact (N):
F=1
if (N==1):
return 1
else:
return N*Fact(N-1)
N=int(input("Enter a number:"))
print("Factorial of {} is {}".format(N,Fact(N)))

OUTPUT:
Enter a number:6
Factorial of 6 is 720
PROGRAM:
def calculate_area(name):
if name == "rectangle":
a = int(input("Enter rectangle length: "))
b = int(input("Enter rectangle breadth: "))
area = a * b
print("The area of rectangle is :", area)
elif name == "square":
s = int(input("Enter length of side : "))
area = s * s
print("The area of square is ", area)
else:
r = float(input("Enter radius : "))
pi = 3.14
area = pi * r * r
print("The area of circle is ", area)
print("Calculate Area of Shape ")
shape=input("enter the shape rectangle/square/circle : ")
calculate_area(shape)
OUTPUT:
enter the shape rectangle/square/circle : circle
Enter radius : 3.4
The area of square is 36.2984
PROGRAM:
def maximum(list):
return max(list)
list=[]
n=int(input(“Enter no.of elements:”))
print(“Enter”,n,”elements”)
i=0
for i in range (0,n):
element=int(input())
list.append(element)
print(“Largest element is:”, maximum(list))
OUTPUT:
Enter no.of elements:5
Enter 5 elements
650
28
78
56
99
Largest element is: 650
PROGRAM:
S=input(“Enter a string:”)
print(“original string is:”,S)
print(“Reversed string is”,S[::-1])

OUTPUT:
Enter a string PYTHON PROGRAMMING
PYTHON PROGRAMMING
original string is: PYTHON PROGRAMMING
Reversed string is GNIMMARGORP NOHTYP
PROGRAM:
Str1=input("Enter the text: ")
Str2=Str1[::-1]
print("reversed Text :",Str2)
if (Str1==Str2):
print("Given Text is Palindrome")
else:
print("the given Text is not Palindrome")

OUTPUT:
Enter the text: madam
reversed Text : madam
Given Text is Palindrome
PROGRAM:
Str1=input("Enter the text: ")
Str2=input("Enter the chracter to be counted: ")
count=Str1.count(Str2)
print("{} appears in {} {} number of times".format(Str2,Str1,count))

OUTPUT:
Enter the text: Welcome
Enter the character to be counted: e
e appears in Welcome 2 number of times
PROGRAM:
Str1 = input("Enter the Text:")
#print(Str1)
S1=input("Enter the Text to be replaced :")
S2=input("Enter the Text to be replaced by:")
Str2 = Str1.replace(S1,S2)
print("Replaced Text:")
print(Str2)
S1=input("Enter the Text to be replaced :")
S2=input("Enter the Text to be replaced by:")
count=int(input("Enter number of occurance to be replaced :"))
Str2 = Str1.replace(S1,S2,count)
print("Replaced Text:")
print(Str2)
OUTPUT:
Enter the Text:Class test Class score Class average
Enter the Text to be replaced :Class
Enter the Text to be replaced by:Internal
Replaced Text:
Internal test Internal score Internal average
Enter the Text to be replaced :Class
Enter the Text to be replaced by:Internal
Enter number of occurance to be replaced :2
Replaced Text:
Internal test Internal score Class average
PROGRAM:
Import pandas as pd
ds1 = pd.Series([2,4,6,8,10])
ds2 = pd.Series([1,3,5,7,10])
print(“Series 1:”)
print(ds1)
print(“Series 2:”)
print(ds2)
print(“Compare the elements of the said Series:”)
print(“Equals:”)
print(“Compare the elements of the said Series:”)
print(ds1>ds2)
print(“Greater Than:”)
print(ds1<ds2)
print(“Less Than:”)
print(ds1==ds2)
print(“Equal”)

OUTPUT:
Series 1:
02
14
26
38
4 10
dtype: int64
Series 2:
01
13
25
37
4 10
dtype: int64
Compare the elements of the said Series:
Equals:
Compare the elements of the said Series:
0 True
1 True
2 True
3 True
4 False
dtype: bool
Greater Than:
0 False
1 False
2 False
3 False
4 False
dtype: bool
Less Than:
0 False
1 False
2 False
3 False
4 True
dtype: bool
Equal
PROGRAM:
import numpy as np
x=np.array([1,2,3,4])
print(“Original array”)
print(x)
print(“Test if none of the elements of the said array is zero”)
print(np.all(x))
x=np.array([0,1,2,3])
print(“Original array”)
print(x)
print(“Test if none of the elements of the said array is zero”)
print(np.all(x))
OUTPUT:
Original array
[1 2 3 4]
Test if none of the elements of the said array is zero
True
Original array
[0 1 2 3]
Test if none of the elements of the said array is zero
False
PROGRAM:
import matplotlib.pyplot as plt
import numpy as np
x=np.array([0,6])
y=np.array([0,250])
plt.plot(xpoints,ypoints)
plt.show()

OUTPUT:
PROGRAM:
from scipy import constants
print(‘1 minute=’, constants.minute,’seconds’)
print(‘1 hour=’, constants.hour,’seconds’)
print(‘1 day=’, constants.day,’seconds’)
print(‘1 week=’, constants.week,’seconds’)
print(‘1 year=’, constants.year,’seconds’)
print(‘1 Julian year=’, constants.Julian_year,’seconds’)
OUTPUT:
1 minute= 60.0 seconds
1 hour= 3600.0 seconds
1 day= 86400.0 seconds
1 week= 604800.0 seconds
1 year= 31536000.0 seconds
1 Julian year= 31557600.0 seconds
PROGRAM:
# FILE COPY
fp1=open("source.txt","w")
fp1.write("python python\n")
fp1.write("java python\n")
fp1.write("c java\n")
fp1=open("source.txt","r")
fp2=open("dest.txt","w")
for line in fp1:
fp2.write(line)
fp1.close()
fp2.close()
fp2=open("dest.txt","r")
print("dest.txt")
print(fp2.read())

OUTPUT:
dest.txt
python python
java python
c java
PROGRAM:
# WORD COUNT
fp1=open("source.txt","r")
wordcount={}
content=fp1.read()
print("source.txt")
print(content)
words=content.split()
for w in words:
if w not in wordcount:
wordcount[w]=1
else:
wordcount[w]+=1
print (wordcount)
fp1.close()
OUTPUT:
source.txt
python python
java python
c java
{'python': 3, 'java': 2, 'c’}
PROGRAM:
def longest_word(filename):
with open (filename,’r’)as infile:words
= infile.read().split()
Max_len = len(max(words,key=len))
return [word for word in words if len(word)==max_len]
print(longest_word(“F:\Data.txt”)

OUTPUT:
[‘collection’]
PROGRAM:
# EXCEPTION HANDLING-VOTER’S AGE VALIDITY
try:
age=int(input("enter your age"))
if(age>=18):
print ("eligible to vote")
else:
print("not eligible to vote")
except:
print("enter a valid age")

OUTPUT:
enter your age :s
enter a valid age
PROGRAM:
n=int(input("enter the value of n:"))
d=int(input("enter the value of d:"))
c=int(input("enter the value of c:"))
try:
q=n/(d-c)
print(“Quotient”,q)
except ZeroDivisionError:
print("Division by zero")

OUTPUT:
enter the value of n:4
enter the value of d:4
enter the value of c:4
Division by zero
PROGRAM:
Mark=int(input("enter the mark:"))
if Mark <0 or Mark>100:
print (“ value is out of range”)
else:
print (“ value is in range”)

OUTPUT:
enter the mark: 123
value is out of range
PROGRAM:
import pygame
# Initialize Pygame
pygame.init()
# Set up the screen
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Bouncing Ball")
# Set up the ball
ball_color = (255, 255, 255)
ball_radius = 20
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_dx = 5
ball_dy = 5
# Start the game loop
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Move the ball


ball_x += ball_dx
ball_y += ball_dy
# Bounce off the walls
if ball_x + ball_radius > screen_width or ball_x - ball_radius < 0:
ball_dx = -ball_dx
if ball_y + ball_radius > screen_height or ball_y - ball_radius < 0:
ball_dy = -ball_dy
# Draw the ball and update the screen
screen.fill((0, 0, 0))
pygame.draw.circle(screen, ball_color, (ball_x, ball_y),
ball_radius)
pygame.display.update()
# Quit Pygame
pygame.quit()
OUTPUT:
PROGRAM:
# BINARY SEARCH
list=[11,17,20,23,29,33,37,41,45,56]
X=int(input("Enter the number to be searched:") )
l=0
h=len(list)-1
while(l<=h):
mid=(l+h)//2
if(X==list[mid]):
print ("Element found ")
break
elif(X<list[mid]):
h=mid-1
else:
l=mid+1
else:
print ("Element not found")
OUTPUT:
Enter the number to be searched:17
Element found
PROGRAM:
# INSERTION SORT
a = [16, 19, 11, 15, 10, 12, 14]
print(a)
for i in a:
j = a.index(i)
while(j>0):
if a[j-1] >a[j]:
a[j-1],a[j] = a[j],a[j-1]
else:
break
j= j-1
else:
print("Sorted List ")
print(a)

OUTPUT:
Sorted List
[10, 11, 12, 14, 15, 16, 19]
PROGRAM:
mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
new.py
import mymodule
a = mymodule.person1["age"]
print(a)

OUTPUT:
36

You might also like