Python Manual Record (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 59

OMoARcPSD| 45433932 lOMoAR cPSD| 45433932

Program No: 1A
Ex. No: DEVELOPING FLOWCHARTS FOR ELECTRICITY BILLING
Date:

AIM:

ALGORITHM:

Tariff rates in TN

Scheme Unit Per unit(₹)


0 to 100 0-100 0
0 to 200 0-100 0
101-200 1.5
0 to 500 101-200 2
201-500 3
> 500 0-100 0
101-200 3.5
201-500 4.6
>500 6.6
lOMoAR cPSD| 45433932

Program for calculating electricity bill in Python

Unit = int(input("Enter 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

RESULT:
lOMoAR cPSD| 45433932

Program No: 1B
Ex. No: DEVELOPING FLOWCHARTS FOR RETAIL SHOP BILLING
Date:

AIM:

ALGORITHM:

1. Start the program


2. Assign tax=0.5
3. Assign rate for Shirt, Saree, Teashirt, Trackpant.
4. Get the quantity of items from the user
5. Calculate total cost by multiplying rate and quantity of the items
6. Add tax value with the total cost and display the bill amount
7. Stop the program.

FLOW CHART:
lOMoAR cPSD| 45433932

Program for calculating retail shop billing in Python

tax=0.5

Rate={"SHIRT":250,"SAREE":650,"TEASHIRT":150,"TRACKPANT":150}

print("Retail Bill Calculator\n")

Bill=int(input("Enter the quantity of the ordered items:\n"))

SHIRT=int(input("SHIRT:"))

SAREE=int(input("SAREE:"))

TEASHIRT=int(input("TEASHIRT:"))

TRACKPANT=int(input("TRACKPANT:"))

cost=SHIRT*Rate["SHIRT"]+SAREE*Rate["SAREE"]+TEASHIRT*Rate["TEASHIRT"]+TRACK
PANT*Rate["TRACKPANT"]

Bill=cost+cost*tax

print("Please pay Rs.%f"%Bill)

OUTPUT:

Retail Bill Calculator

Enter the quantity of the ordered items:3

SHIRT:1

SAREE:1

TEASHIRT:1

TRACKPANT:0

Please pay Rs.1575.000000

Result:
lOMoAR cPSD| 45433932

Program No: 1C DEVELOPING FLOWCHARTS FOR DETERMINING WEIGHT


Ex. No: OF A STEEL BAR

Date:

AIM:

ALGORITHM:

FLOWCHART:
START

Read
Diameter

Calculate

Weight=(D*D)/162

Print

STOP
lOMoAR cPSD| 45433932

Program for calculating Weight of a Steel Bar and motor bike in Python

# Weight of a steel bar

print("Calculating weight of a steel bar:")


D=int(input("Enter the diameter of steel bar:"))
Weight=(D*D)/162
print("Weight of the steel bar is%.fkg/m"%Weight)

OUTPUT:

Enter the diameter of steel bar: 15

Weight of the steel bar is 1.38kg

RESULT:
lOMoAR cPSD| 45433932

Program No: 1D DEVELOPING FLOWCHARTS FOR COMPUTING


Ex. No: ELECTRICAL CURRENT IN 3 PHASE AC CIRCUIT

Date:

AIM:

ALGORITHM:

FLOWCHART:
START

Read
Watts,

Calculate

power=√3 * Volts*Amperes

Print

STOP
lOMoAR cPSD| 45433932

PROGRAM:

import math
P = eval(input("Enter power (in Watts) : "))
pf = eval(input("Enter power factor (pf<1): "))

VL = eval(input("Enter Line Voltage (in Volts) : "))


CL = P/(math.sqrt(3)*VL*pf)

print("Line Current =", round(CL,2),"A")

OUTPUT:

python current.py

Enter power (in Watts) : 5000

Enter power factor (pf<1): 0.839

Enter Line Voltage (in Volts) : 400

Line Current = 8.6 A

RESULT:
lOMoAR cPSD| 45433932

Program No: 2A PROGRAMS USING SIMPLE STATEMENTS EXCHANGE THE VALUES


Ex. No: OF TWO VARIABLES
Date:

AIM:

ALGORITHM:

PROGRAM:

def exchange(x,y): #Function Definition

x,y=y,x # swapping using tuple assignment

print("After exchange of x,y")

print("x =",x)

print("Y= ",y)

x=input("Enter value of X ") #Main Function

y=input("Enter value of Y ")

print("Before exchange of x,y")

print("x =",x)

print("Y= ",y)

exchange(x,y) # Function call

OUTPUT:

Enter value of X: 67
Enter value of Y: 56
lOMoAR cPSD| 45433932

Before exchange of x,y


x = 67
Y= 56

After exchange of x,y x = 56


Y= 67

RESULT:
lOMoAR cPSD| 45433932

Program No: 2B
Ex. No: PROGRAM TO CIRCULATE THE VALUES OF N VARIABLES
Date:

AIM:

ALGORITHM:

1. Start the program


2. Read the value of n
3. Circulate the values using slice operator
4. Print the values
5. Stop the program

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])

RESULT:
lOMoAR cPSD| 45433932

Program No: 2C
Ex. No: PROGRAM TO CALCULATE DISTANCE BETWEEN TWO VARIABLES
Date:

AIM:

ALGORITHM:

1. Start the program


2. Read the value of x1,x2,y1 and y2
3. Calculate distance=√((𝑥2 − 𝑥1) ∗∗ 2) − ((𝑦2 − 𝑦1) ∗∗ 2)
4. Print the distance
5. Stop the program

PROGRAM:

# Distance between two points

import math

print("Enter coordinates for Point 1 : ")

x1 = int(input("x1 = "))

y1 = int(input("y1 = "))

print("Enter coordinates for point 2 : ")

x2 = int(input("x2 = "))

y2 = int(input("y2 = "))

dist = math.sqrt( ((x2-x1)**2) + ((y2-y1)**2) )

print("Distance between given points is", round(dist,2))

OUTPUT:

Enter coordinates for Point 1 :

x1 = 50

y1 = 758
lOMoAR cPSD| 45433932

Enter coordinates for point 2 :

x2 = 25

y2 = 50

Distance between given points is 708.44

RESULT:
lOMoAR cPSD| 45433932

Program No: 3A
Ex. No: PROGRAMS USING CONDITIONALS AND ITERATIVE LOOPS
Date: NUMBER SERIES

AIM:

2
+22+32+….+N2.

ALGORITHM:

1. Start the program


2. Read the value of n
3. Calculate sum of number series(12+22+32+….+N2) using while condition
4. Print the value
5. Stop the program

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

RESULT:
lOMoAR cPSD| 45433932

Program No: 3B
Ex. No: PROGRAMS USING CONDITIONALS AND ITERATIVE LOOPS
Date: NUMBER PATTERN

AIM:

ALGORITHM:

1. Start the program


2. Read the number of rows to print from user
3. Print the pattern using for loops
4. Stop the program

PROGRAM:

N = int(input("Enter number of Lines : "))

print("Number Triangle : ")

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

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

print(n, end=" ")

print()

OUTPUT:

Enter number of Lines : 5

Number Triangle :
1
22
333
4444
55555

RESULT:
lOMoAR cPSD| 45433932

Program No: 3C PROGRAMS USING CONDITIONALS AND ITERATIVE LOOPS


Ex. No: PYRAMID PATTERN
Date:

AIM:

ALGORITHM:

PROGRAM:

N = int(input("Enter 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 number of Lines : 5


Pyramid Star pattern :

** *

** * * *

** * * * * *

** * * * * * * *

RESULT:
lOMoAR cPSD| 45433932

Program No: 4A
Ex. No: PYTHON PROGRAM DEMOSTRATING OPERATIONS OF LIST
Date:

AIM:

ALGORITHM:

PROGRAM:

# declaring a list of items in a Library

library =['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','Ebooks']

print('Library: ',library)

print('first element: ',library[0])

print('fourth element: ',library[3])

print('Items in Library from 0 to 4 index: ',library[0: 5])

library.append('Audiobooks')

print('Library list after append Audiobooks: ',library)

print('index of \'Newspaper\': ',library.index('Newspaper'))

library.sort()

print('after sorting: ', library);

print('Popped elements is: ',library.pop())

print('after pop(): ', library);

library.remove('Maps')
lOMoAR cPSD| 45433932

print('after removing \'Maps\': ',library)

library.insert(2, 'CDs')

print('after insert CDs: ', library)

print(' Number of Elements in Library list : ',len(library))

OUTPUT:

('Library: ', ['Books', 'Periodicals', 'Newspaper', 'Manuscripts', 'Maps', 'Prints', 'Documents',


'Ebooks'])

('first element: ', 'Books')

('fourth element: ', 'Manuscripts')

('Items in Library from 0 to 4 index: ', ['Books', 'Periodicals', 'Newspaper', 'Manuscripts', 'Maps'])

('Library list after append Audiobooks: ', ['Books', 'Periodicals', 'Newspaper', 'Manuscripts',
'Maps', 'Prints', 'Documents', 'Ebooks', 'Audiobooks'])

("index of 'Newspaper': ", 2)

('after sorting: ', ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts', 'Maps', 'Newspaper',
'Periodicals', 'Prints'])

('Popped elements is: ', 'Prints')

('after pop(): ', ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts', 'Maps', 'Newspaper',
'Periodicals'])

("after removing 'Maps': ", ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts',


'Newspaper', 'Periodicals'])

('after insert CDs: ', ['Audiobooks', 'Books', 'CDs', 'Documents', 'Ebooks', 'Manuscripts',
'Newspaper', 'Periodicals'])

(' Number of Elements in Library list : ', 8)

RESULT:
lOMoAR cPSD| 45433932

Program No: 4B
Ex. No: PYTHON PROGRAM DEMOSTRATING OPERATIONS OF TUPLE
Date:

AIM:

ALGORITHM:

1. Start the program


2. Declare a list variable car to list the components of a car
3. Print the elements of list
4. Stop the program

PROGRAM:

Car_Main_components = ['Chassis', 'Engine', {'Body':['Steering system','Braking


system','Suspension']}, {'Transmission_System':['Clutch','Gearbox','Differential','Axle']}]

Car_Auxiliaries = ['car lightening system','wiper and washer system','power door locks system','car
instrument panel','electric windows system','car park system']

def fnPrint(L):

for ele in L:

if(isinstance(ele,dict)):

for k, v in (ele.items()):

print("\t",k, ":", ", ".join(v))

continue

print("\t",ele)

print("Car Main Components:",)

fnPrint(Car_Main_components)
print("Car Auxiliaries:")

fnPrint(Car_Auxiliaries)
lOMoAR cPSD| 45433932

OUTPUT:

Car Main Components:

Chassis

Engine

Body : Steering system, Braking system, Suspension

Transmission_System : Clutch, Gearbox, Differential, Axle

Car Auxiliaries:

car lightening system

wiper and washer system

power door locks system

car instrument panel

electric windows system

car park system

RESULT:

Thus the program to components of a car has been executed successfully.


lOMoAR cPSD| 45433932

Program No: 4C
Ex. No: PYTHON PROGRAM DEMOSTRATING OPERATIONS OF LISTS
Date: AND TUPLE

AIM:

To write a python program to implement operations of list and tuple for a civil structure example.

ALGORITHM:

1. Start the program


2. Declare a tuple building to list the elements of a civil structure
3. Do the tuple operations add, update, pop and length
4. Print the result
5. Stop the program

Materials required for construction of a building


Cement

Bricks

Blocks

Wooden Products

Hardware and Fixtures

Natural Stones

Doors

Windows

Modular Kitchen

Sand

Aggregates

Electrical materials

Tiles
lOMoAR cPSD| 45433932

BuildingMaterials = ('Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware and


Fixtures', 'Natural Stones','Doors', 'Windows', 'Modular Kitchen', 'Sand','Aggregates',
'Tiles')

ElectricalMaterials = ('Conduit Pipes and Fittings', 'Wires and Cables', 'Modular switches and
sockets', 'Electric Panels', 'Switch Gear')

print("Created tuple : ")

print("Building Materials : ",BuildingMaterials)

print("Electrical Materials : ",ElectricalMaterials)

# Accessing elements by index

print("First element in tuple : ",BuildingMaterials[0])

print("Last element in tuple : ",BuildingMaterials[-1])

# Slicing

print("First 5 elements in tuple : ",BuildingMaterials[0:5])

# length of tuple

print("Length of tuple : ",len(BuildingMaterials))

# Concat, repetition

print("Concatenation operation")

AllMaterials = BuildingMaterials+ElectricalMaterials

print("All materials")

print(AllMaterials)

print("Repetition operation")

print(AllMaterials*2)

# Membership operator

SearchMaterial = input("Enter material to search : ")


lOMoAR cPSD| 45433932

if SearchMaterial in AllMaterials:

print("Material present in tuple.")

else:

print("Material not present in tuple.")

# Iteration operation

print("Iteration operation")

print("Materials required for construction of a building: ")

for mat in AllMaterials:

print(mat)

OUTPUT:

Created tuple :

Building Materials : ('Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware and Fixtures',
'Natural Stones', 'Doors', 'Windows', 'Modular Kitchen', 'Sand', 'Aggregates', 'Tiles')

Electrical Materials : ('Conduit Pipes and Fittings', 'Wires and Cables', 'Modular switches and
sockets', 'Electric Panels', 'Switch Gear')

First element in tuple : Cement

Last element in tuple : Tiles

First 5 elements in tuple : ('Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware and
Fixtures')

Length of tuple : 12

Concatenation operation

All materials
lOMoAR cPSD| 45433932

('Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware and Fixtures', 'Natural Stones', 'Doors',
'Windows', 'Modular Kitchen', 'Sand', 'Aggregates', 'Tiles', 'Conduit Pipes and Fittings', 'Wires and
Cables', 'Modular switches and sockets', 'Electric Panels', 'Switch Gear')

Repetition operation

('Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware and Fixtures', 'Natural Stones', 'Doors',
'Windows', 'Modular Kitchen', 'Sand', 'Aggregates', 'Tiles', 'Conduit Pipes and Fittings', 'Wires and
Cables', 'Modular switches and sockets', 'Electric Panels', 'Switch Gear', 'Cement', 'Bricks', 'Blocks',
'Wooden Products', 'Hardware and Fixtures', 'Natural Stones', 'Doors', 'Windows', 'Modular Kitchen',
'Sand', 'Aggregates', 'Tiles', 'Conduit Pipes and Fittings', 'Wires and Cables', 'Modular switches and
sockets', 'Electric Panels', 'Switch Gear')

Enter material to search : Natural Stones

Material present in tuple.

RESULT:
Thus the program to Materials required for construction of a building has been executed
successfully.
lOMoAR cPSD| 45433932

Program No: 5A
Ex. No: PYTHON PROGRAM DEMOSTRATING OPERATIONS OF SET
Date:

AIM:

To write a python program to implement operations on an automobiles set.

ALGORITHM:

1. Start the program


2. Declare set variables car and motorbike to list the components of a car and motorbike
3. Do the set operations union, intersection, difference and symmetric difference
4. Print the result
5. Stop the program

PROGRAM:

# declaring a set of Components of a car

car = {'Engine','Battery','Alternator','Radiator','Steering','Break','Seat Belt'}

# declaring a set of Components of a motorbike

motorbike={'Engine','Fuel tank','Wheels','Gear','Break'}

# Elements of the set car

print('Components of Car: ',car)

#Elements of the set motorbike

print('Components of motorbike: ',motorbike)

#union operation

print('Union of car and motorbike: ',car | motorbike)

#intersection operation

print('Intersection of car and motorbike: ',car & motorbike)


lOMoAR cPSD| 45433932

#difference operation

print('Difference operation: ', car - motorbike)

#Symmetric difference

print('Symmetric difference operation: ',car ^ motorbike)

OUTPUT:

('Components of Car: ', set(['Engine', 'Alternator', 'Radiator', 'Seat Belt', 'Battery', 'Break',
'Steering']))

('Components of motorbike: ', set(['Engine', 'Break', 'Wheels', 'Fuel tank', 'Gear']))

('Union of car and motorbike: ', set(['Engine', 'Alternator', 'Gear', 'Radiator', 'Seat Belt', 'Battery',
'Fuel tank', 'Break', 'Wheels', 'Steering']))

('Intersection of car and motorbike: ', set(['Engine', 'Break']))

('Difference operation: ', set(['Alternator', 'Battery', 'Steering', 'Radiator', 'Seat Belt']))

('Symmetric difference operation: ', set(['Alternator', 'Gear', 'Radiator', 'Seat Belt', 'Battery', 'Fuel
tank', 'Wheels', 'Steering']))

RESULT:
Thus the program to Components of an automobile of a building has been executed successfully.
lOMoAR cPSD| 45433932

Program No: 5B
Ex. No: PYTHON PROGRAM DEMOSTRATING OPERATIONS OF
Date: DICTIONARY

AIM:

To write a python program to implement operations of dictionary.

ALGORITHM:

1. Start the program


2. Declare a dictionary building to list the elements of a civil structure
3. Do the dictionary operations add, update, pop and length
4. Print the result
5. Stop the program

PROGRAM:

#declare a dictionary building

building={1:'foundation',2:'floor',3:'beams',4:'columns',5:'roof',6:'stair'}

#Elements in dictionary

print('Elements in dictionary building: ',building)

#length of a dictionary

print('Length of the dictionary building: ',len(building))

#value of the key 5

print('The value of the key 5',building.get(5))

#update key 6 :stair as lift

building.update({6:'lift'})

print('After updation of stair as lift: ',building)

#Add element window in the dictionary

building[7]='window'

print('After adding window: ',building)


lOMoAR cPSD| 45433932

#using pop operation to remove element

building.pop(3)

print('After removing element beams from building: ',building)

OUTPUT:

('Elements in dictionary building: ', {1: 'foundation', 2: 'floor', 3: 'beams', 4: 'columns', 5: 'roof', 6:
'stair'})

('Length of the dictionary building: ', 6)

('The value of the key 5', 'roof')

('After updation of stair as lift: ', {1: 'foundation', 2: 'floor', 3: 'beams', 4: 'columns', 5: 'roof', 6: 'lift'})

('After adding window: ', {1: 'foundation', 2: 'floor', 3: 'beams', 4: 'columns', 5: 'roof', 6: 'lift', 7:
'window'})

('After removing element beams from building: ', {1: 'foundation', 2: 'floor', 4: 'columns', 5: 'roof', 6:
'lift', 7: 'window'})

RESULT:

Thus the program to elements of a civil structure has been executed successfully.
lOMoAR cPSD| 45433932

Program No: 6A
Ex. No: PYTHON PROGRAM USING FUNCTIONS FOR FINDING
Date: FACTORIAL OF A NUMBER

AIM:

To write a python program to calculate the factorial of a number.

ALGORITHM:

1. Start the program


2. Read a number from user
3. If number=1, then return 1
4. Otherwise calculate the factorial of that number using recursive function
5. Print the result
6. Stop the program

PROGRAM:

def fnfact(N):

if(N==0):

return 1

else:

return(N*fnfact(N-1))

Num = int(input("Enter Number : "))

print("Factorial of", Num, "is", fnfact(Num))

OUTPUT

Enter Number : 5

Factorial of 5 is 120

Result:

Thus the program to factorial of a number has been executed successfully.


lOMoAR cPSD| 45433932

Program No: 6B
Ex. No: PYTHON PROGRAM FOR FINDING LARGEST NUMBER IN A LIST
Date:

AIM:

To write a python program to find the largest number in a list.

ALGORITHM:

1. Start the program


2. Read number of elements from user
3. Read the elements of list using for loop
4. Find the largest element from list using max() function
5. Print the result
6. Stop the program

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))


lOMoAR cPSD| 45433932

OUTPUT:

Enter no.of elements:5

('Enter', 5, 'elements')

65

78

52

99

56

('Largest element is:', 99)

RESULT:

Thus the program to finding largest number in a list has been executed successfully.
lOMoAR cPSD| 45433932

Program No: 6C
Ex. No: PYTHON PROGRAM FOR FINDING AREA OF SHAPES
Date:

AIM:

To write a python program to find the area of shapes.

ALGORITHM:

1. Start the program


2. Get the choice from user
3. If choice is 1, read side value and calculate area of square
4. If choice is 2, read length and breadth value and calculate area of rectangle
5. If choice is 3, read radius and calculate area of circle
6. If choice is 4, read breadth and weight value and calculate area of triangle
7. Print the result
8. Stop the program

PROGRAM:

# Functions

# Area of a shape

def fnSquare(s):

return (s*s)

def fnRectangle(l,b):

return (l*b)

def fnCircle(r):

return 3.142*r*r

def fnTriangle(base,ht):

return 0.5*base*ht

# square

s = eval(input("Enter side of square : "))

l,b = map(int,(input("Enter length and breath of rectangle : ").split()))


lOMoAR cPSD| 45433932

r = eval(input("Enter circle radius : "))

base,ht = map(int,(input("Enter base and height of triangle : ").split()))

print("Area of square =",fnSquare(s))

print("Area of rectangle =",fnRectangle(l,b))

print("Area of circle =",fnCircle(r))

print("Area of triangle =",fnTriangle(base,ht))

OUTPUT:

Enter side of square : 5

Enter length and breath of rectangle : 5 5

Enter circle radius : 5

Enter base and height of triangle : 5 5

Area of square = 25

Area of rectangle = 25

Area of circle = 78.55

Area of triangle = 12.5

RESULT:

Thus the program Area of shapes in a list has been executed successfully.
lOMoAR cPSD| 45433932

Program No: 7 A
Ex. No: PYTHON PROGRAM TO FIND THE REVERSE OF A STRING
Date:

AIM:

To write a python program to reverse a string

ALGORITHM:

1Start the program

2. Read a string from user

3. Perform reverse operation

4. Print the result

5. Stop the program

PROGRAM:

s=input("Enter a string:")

print("Original string is:",s)

print("Reversed string is:",s[::-1])

OUTPUT:

Enter a string: 'PYTHON PROGRAMMING'

('Original string is:', 'PYTHON PROGRAMMING')

('Reversed string is:', 'GNIMMARGORP NOHTYP')

RESULT:

Thus the program Reverse of a string has been executed successfully.


lOMoAR cPSD| 45433932

Program No: 7 B
Ex. No: PYTHON PROGRAM FOR CHECKING PALINDROME IN A STRING
Date:

AIM:

To write a python program to check whether a string is palindrome or not.

ALGORITHM:

1. Start the program


2. Read a string from user and store in variable s1
3. Perform reverse operation of s1 and store the reversed string in s2
4. Check whether the strings are equal or not
5. If both are equal print it is a palindrome. Otherwise print it is not a palindrome
6. Stop the program

PROGRAM:

s1=input("Enter a string:")

s2=s1[::-1]

if list(s1)==list(s2):

print("It is a palindrome")

else:

print("It is not a palindrome")

OUTPUT:

Enter a string: 'PYTHON'

It is not a palindrome

Enter a string: 'MADAM'

It is a palindrome

RESULT:

Thus the program checking palindrome in a string has been executed successfully.
lOMoAR cPSD| 45433932

Program No: 7 C
Ex. No: PYTHON PROGRAM FOR COUNTING CHARACTER IN A STRING
Date:

AIM:

To write a python program to count number of characters in a string

ALGORITHM:

1. Start the program


2. Read a string from user
3. Read a substring/ character to count
4. Count the number of occurrence using count() method and print the result
5. Stop the program

PROGRAM:

txt =input("Enter a string: ")

char=input("Enter a character/substring to count: ")

x = txt.count(char)

print(“The no.of times=”,char, “occurred is: =”,x)

OUTPUT:

Enter a string: "I love python programming, python is very interesting subject"

Enter a character/substring to count: 'python'

('The no.of times', 'python', 'occurred is:', 2)

RESULT:

Thus the program counting character in a string has been executed successfully.
lOMoAR cPSD| 45433932

Program No: 7 D
Ex. No: PYTHON PROGRAM FOR REPLACING CHARACTERS IN A
Date: STRING

AIM:

To write a python program to replace characters in a string

ALGORITHM:

1. Start the program


2. Read a string from user
3. Read old string
4. Read new string to replace
5. Replace the old string with new string using replace() method
6. Print the result
7. Stop the program

PROGRAM:

string = input("Enter any string: ")

str1 = input("Enter old string: ")

str2 = input("Enter new string: ")

print(string.replace(str1, str2))

OUTPUT:

Enter any string: 'Problem solving and python programming'

Enter old string: 'python'

Enter new string: 'C'

Problem solving and C programming

RESULT:

Thus the program Replacing characters in a string has been executed successfully.
lOMoAR cPSD| 45433932

Program No: 8 A
Ex. No: PYTHON PROGRAM FOR DEMOSTRATING OPERATIONS USING
Date: PANDAS

AIM:
To write a python program to compare the elements of the two Pandas Series using Pandas library.

Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 10]

ALGORITHM:

1. Start the program


2. Import pandas from python standard libraries
3. Assign data series as ds1 and ds2
4. Compare the elements of the series and print equals, greater than and less than
5. Stop the program

PROGRAM:

import pandas as pd

ds1 = pd.Series([2, 4, 6, 8, 10])

ds2 = pd.Series([1, 3, 5, 7, 10])

print("Series1:")

print(ds1)

print("Series2:")

print(ds2)

print("Compare the elements of the said Series:")

print("Equals:")

print(ds1 == ds2) print("Greater than:")

print(ds1 > ds2) print("Less than:")

print(ds1 < ds2)


lOMoAR cPSD| 45433932

OUTPUT:

Series1:

0 2

1 4

2 6

3 8

4 10

dtype: int64

Series2:

0 1

1 3

2 5

3 7

4 10

dtype: int64

Compare the elements of the said Series:

Equals:

0 False

1 False

2 False

3 False

4 True

dtype: bool

Greater than:
lOMoAR cPSD| 45433932

0 True

1 True

2 True

3 True

4 False

dtype: bool

Less than:

0 False

1 False

2 False

3 False

4 False

dtype: bool

RESULT:

Thus the program Replacing characters in a string has been executed successfully.
lOMoAR cPSD| 45433932

Program No: 8 B PYTHON PROGRAM FOR DEMOSTRATING OPERATIONS USING


Ex. No: NUMPY
Date:

AIM:
To write a program to test whether none of the elements of a given array is zero using
NumPy library.

ALGORITHM:

1. Start the program


2. Import numpy from python standard library
3. Declare an array and print the original array
4. Test whether none of the elements of the array is zero or not
5. If it contains zero print False otherwise print True
6. Stop the program

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:")


lOMoAR cPSD| 45433932

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

RESULT:

Thus the program Replacing characters in a string has been executed successfully.
lOMoAR cPSD| 45433932

Program No: 8 C PYTHON PROGRAM FOR DEMOSTRATING OPERATIONS USING


Ex. No: MATPLOTLIB
Date:

AIM:
To write a python program to plot a graph using matplotlib library.

ALGORITHM:

1. Start the program


2. Import matplotlib from python standard library
3. Declare two arrays to define coordinators for 2 points
4. Plot graph for those mentioned points using matplot library
5. Stop the program

PROGRAM:

import matplotlib.pyplot as plt

import numpy as np

xpoints = np.array([0, 6])

ypoints = np.array([0, 250])

plt.plot(xpoints, ypoints)

plt.show()
lOMoAR cPSD| 45433932

OUTPUT:

RESULT:

Thus the program Matplotlib has been executed successfully

.
lOMoAR cPSD| 45433932

Program No: 8 D PYTHON PROGRAM FOR DEMOSTRATING OPERATIONS USING


Ex. No: SCIPY
Date:

AIM:

To write a python program to return the specified unit in seconds (eg. Hour returns 3600.0)using
scipy library.

ALGORITHM:

1. Start the program


2. Import scipy from python standard library
3. Print specified units like minute, hour, day, etc in seconds using scipy
4. Stop the program

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')


lOMoAR cPSD| 45433932

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')

RESULT:

Thus the program Scipy has been executed successfully

.
lOMoAR cPSD| 45433932

Program No: 9 A PYTHON PROGRAM FOR COPYING FROM ONE FILE TO


Ex. No: ANOTHER
Date:

AIM:
To write a python program to copy from one file to another.

ALGORITHM:

1. Start the program


2. Import copyfile from python standard libraries
3. Read source and destination file name
4. Copy data from source file to destination file and print 8file copied successfully9
5. Stop the program

PROGRAM:

from shutil import copyfile

sourcefile = input("Enter source file name: ")

destinationfile = input("Enter destination file name: ")

copyfile(sourcefile, destinationfile)

print("File copied successfully!")

c=open(destinationfile, "r")

print(c.read())

c.close()

print()

print()
lOMoAR cPSD| 45433932

OUTPUT:

Enter source file name: 'file1.txt'

Enter destination file name: 'file2.txt'

File copied successfully!

ROSE

JASMINE

SUN FLOWER

RESULT:

Thus the program copy from one file to another has been executed successfully

.
lOMoAR cPSD| 45433932

Program No: 9 B PYTHON PROGRAM FOR DEMOSTRATING WORD COUNT FROM


Ex. No: A FILE
Date:

AIM:

Data.txt

A file is a collection of data stored on a secondary storage device like hard disk. They can be
easily retrieved when required. Python supports two types of files. They are Text files & Binary files.

ALGORITHM:

1. Start the program


2. Open file from the specified path and read the data using read() method
3. Count the number of words using len() method and print the count
4. Stop the program

PROGRAM:

file = open("F:\Data.txt", "rt")

data = file.read()

words = data.split()

print('Number of words in text file :', len(words))

OUTPUT:

Number of words in text file : 36

RESULT:

Thus the program word count from a file has been executed successfully
lOMoAR cPSD| 45433932

Program No: 9 C
Ex. No: PYTHON PROGRAM FOR FINDING LONGEST WORD IN A FILE
Date:

AIM:

To write a python program to find longest word in a file.

Data.txt

A file is a collection of data stored on a secondary storage device like hard disk. They can be easily
retrieved when required. Python supports two types of files. They are Text files & Binary files.

ALGORITHM:

1. Start the program


2. Open file from the specified path and read the data using read() method
3. Find the longest word using max() function and print the result
4. Stop the program

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']

RESULT:

Thus the program finding longest word in a file has been executed successfully
lOMoAR cPSD| 45433932

Program No: 10 A PYTHON PROGRAM FOR HANDLING EXCEPTIONS DIVIDE BY


Ex. No: ZERO
Date:

AIM:

To write a python program to handle divide by zero error using exception handling.

ALGORITHM:

1. Start the program


2. Read the values for n,d and c
3. Calculate Quotient=n/(d-c) in try block
4. If zeroDivisionError arise print Division by Zero
5. Stop the program

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!")
lOMoAR cPSD| 45433932

OUTPUT:

Enter the value of n:8

Enter the value of d:4

Enter the value of c:4

Division by Zero!

Enter the value of n:8

Enter the value of d:4

Enter the value of c:2

('Quotient:', 4)

RESULT:

Thus the program handle divide by zero error using exception handling has been executed
successfully
lOMoAR cPSD| 45433932

Program No: 10 B PYTHON PROGRAM FOR CHECKING VOTING ABITITY


Ex. No:
Date:

AIM:

To write a python program to check voter’s age validity.

ALGORITHM:

1. Start the program


2. Read year of birth from user
3. Calculate age by subtracting year of birth from current year
4. If Age is less than or equal to 18 print You are eligible to vote. Otherwiseprint you are
not eligible to vote
5. Stop the program
PROGRAM:

import datetime

Year_of_birth = int(input("In which year you took birth:- "))

current_year = datetime.datetime.now().year

Current_age = current_year-Year_of_birth

print("Your current age is ",Current_age)

if(Current_age<=18):

print("You are not eligible to vote")

else:

print("You are eligible to vote")

OUTPUT:

In which year you took birth:- 2004

('Your current age is ', 18)


lOMoAR cPSD| 45433932

You are not eligible to vote

In which year you took birth:- 1994

('Your current age is ', 28)

You are eligible to vote

RESULT:

Thus the program voters age validity has been executed successfully
lOMoAR cPSD| 45433932

Program No: 10 C PYTHON PROGRAM FOR VALIDATING STUDENT MARK


Ex. No:
Date:

AIM:

To write a python program to perform student mark range validation

ALGORITHM:

1. Start the program


2. Read student mark from user
3. If the mark is in between 0 and 100 print “The mark is in the range”
4. Otherwise print “The value is out of range”
5. Stop the program

PROGRAM:

Mark = int(input("Enter the Mark: "))


if Mark < 0 or Mark > 100:
print("The value is out of range, try again.")
else:
print("The Mark is in the range")

OUTPUT:

Enter the Mark: 123

The value is out of range, try again.

Enter the Mark: 95

The Mark is in the range

RESULT:

Thus the program student mark range validation has been executed successfully
lOMoAR cPSD| 45433932

Program No: 11 PYTHON PROGRAM FOR EXPLORING PYGAME


Ex. No:
Date:

PYGAME INSTALLATION

Step 1: Check for Python Installation

In order to install Pygame, Python must be installed already in your system. Tocheck whether Python
is installed or not in your system, open the command prompt and give the command as shown below.

First set the path of the directory using cd command


Eg: cd C:\Users\abc\AppData\Local\Programs\Python\Python312\Scripts
Now the path will be updated. Now type python -v

Step 2: Check for PIP installation


PIP is a tool that is used to install python packages. PIP is automatically installedwith Python
2.7. 9+ and Python 3.4+. Open the command prompt and enter the command shown below to check
whether pip is installed or not.

pip --version
lOMoAR cPSD| 45433932

Step 3: Install Pygame

To install Pygame, open the command prompt and give the command as shownbelow:

pip install pygame

Now, Pygame installed successfully.

To see if it works, run one of the included examples in pygame-2.0.3

 Open command prompt set the path to the directory where pygame is installed
 Run a game say aliens.py

RESULT:

Thus the program py game has been executed successfully


lOMoAR cPSD| 45433932

Program No: 12 PYTHON PROGRAM FOR GAME ACTIVITY USING PYGAME -


Ex. No: BOUNCING BALL
Date:

AIM:

To write a python program to create bouncing ball game activity using pygame

PROGRAM:

import pygame

pygame.init()

window_w = 800

window_h = 600

white = (255, 255, 255)

black = (0, 0, 0)

FPS = 120

window = pygame.display.set_mode((window_w, window_h))pygame.display.set_caption("Game: ")

clock = pygame.time.Clock()

def game_loop():

block_size = 20

velocity = [1, 1]

pos_x = window_w/2

pos_y = window_h/2

running = True

while running:

for event in pygame.event.get():

if event.type == pygame.QUIT:
lOMoAR cPSD| 45433932

pygame.quit()

quit()

pos_x += velocity[0]

pos_y += velocity[1]

if pos_x + block_size > window_w or pos_x < 0:

velocity[0] = -velocity[0]

if pos_y + block_size > window_h or pos_y < 0:

velocity[1] = -velocity[1]

# DRAW

window.fill(white)
pygame.draw.rect(window, black, [pos_x, pos_y, block_size, block_size])

pygame.display.update()

clock.tick(FPS)

game_loop()

OUTPUT:

RESULT:

Thus the program bouncing ball game has been executed successfully

You might also like