P.S.
V COLLEGE OF ENGINEER IN AND TECHNOLOGY
KRISHNAGIRI-635108
DEPARTMENT OF INFORMATION TECHNOLOGY
LAB MANUAL
PROBLEM SOLVING AND PYTHON PROGRAMMING - LABORATORY
SUBJECT CODE : GE3171
YEAR/SEM : I/I
REGULATION : 2021
Vision
To facilitate technical education with high quality and ethics for
developing professionals to fit into the competitive atmosphere in the
global market.
Mission:
M1: To provide a learning ambience to enhance innovations, problem
solving skills managerial qualities, team-spirit and ethical responsibilities.
M2: To provide exposure to latest tools and technologies in the area of
Information Technology
M3: To support society by participating in and encouraging technology
transfer
M4: To undertake collaborative learning which offers opportunities for
long term interaction with academia and industry
EX.NO NAME OF THE EXPERIMENT REMARK
B) CHECKING PALINDROME
A) ELECTRICITY BILLINGIN A STRING
C)COUNTING
B) RETAILCHARACTER IN A STRING
SHOP BILLING
7
D)REPLACING
C) WEIGHT OF CHARACTERS
A STEEL BAR IN A STRING
1
A)
D) PANDAS
COMPUTE ELECTRICAL CURRENT IN 3 PHASE AC
CIRCUIT
B) NUMPY
A) PROGRAMS USING SIMPLE STATEMENTS EXCHANGE
8
THE
C) VALUES OF TWO VARIABLES
MATPLOTLIB
B) SCIPY
D) CIRCULATE THE VALUES OF N VARIABLES
2
C) DISTANCE BETWEEN TWO VARIABLES
9 A) COPY FROM ONE FILE TO ANOTHER
A) PROGRAMS USING CONDITIONALS & ITERATIVE LOOPS
B) WORD SERIES
NUMBER COUNT FROM A FILE
C) FINDING LONGEST WORD IN A FILE
B)NUMBER PATTERN
3 A) DIVIDE BY ZERO ERROR USING EXCEPTION HANDLING
C) PYRAMID PATTERN
A) VOTER’S
B) OPERATIONS OF LIST
AGE VALIDITY
ITEMS PRESENT IN A LIBRARY
10 B) OPERATIONS OF RANGE
TUPLE COMPONENTS
4 C) STUDENT MARK VALIDATION OF A CAR
A) OPERATIONS OF SET COMPONENTS OF AN AUTOMOBILE
11
5 B) OPERATIONS
EXPLORING OF DICTIONARY
PYGAME ELEMENTS OF A CIVIL
INSTALLATION
STRUCTURE
PROGRAMS USING FUNCTIONS
12 GAME ACTIVITY
A) FACTORIAL OFUSING PYGAME BOUNCING BALL
A NUMBER
B)FINDING LARGEST NUMBER IN A LIST
6
C) AREA OF SHAPES
PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
1. Identification and solving of simple real life or scientific or technical problems, and developing flow
charts for the same. (Electricity Billing, Retail shop billing, Sin series, weight of a motorbike,
Weight of a steel bar, compute Electrical Current in Three Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns,
pyramid pattern)
4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a
library/Components of a car/ Materials required for construction of a building –operations of list &
tuples)
5. Implementing real-time/technical applications using Sets, Dictionaries. (Language, components of
an automobile, Elements of a civil structure, etc.- operations of Sets & Dictionaries)
6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
7. Implementing programs using Strings. (reverse, palindrome, character count, replacing characters)
8. Implementing programs using written modules and Python Standard Libraries (pandas, numpy.
Matplotlib, scipy)
9. Implementing real-time/technical applications using File handling. (copy from one file to another,
word count, longest word)
10. Implementing real-time/technical applications using Exception handling. (divide by zero error,
voter’s age validity, student mark range validation)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.
1. A) ELECTRICITY BILLING
AIM:
To write a python program for implementing electricity billing.
ALGORITHM:
1. Start the program
2. Get the total units of current consumed by the customer using the variable unit.
3. If the unit consumed less or equal to 100 units, calculates the total amount of
consumed =units*1.5
4. If the unit consumed between 100 to 200 units, calculates the total amount of
consumed=(100*1.5)+(unit-100)*2.5)
5. If unit consumed between 200 to 300 units ,calculates total amount of
consumed=(100*1.5)+(200-100)*2.5+(units-200)*4
6. If unit consumed between 300-350 units ,calculates total amount of
consumed=(100*1.5)+(200-100)*2.5+(300-200)*4+(units-350)*5
7. If the unit consumed above 350 units, fixed charge – 1500/=
8. Stop the program
FLOW CHART:
START
Read units of current
consumed
IF
Units<=100
PayAmount=units*1.5
elif
unit<=200
PayAmount=(100*1.5)+(units-
100)*2.5
elif
unit<=300
PayAmount=(100*1.5)+(200-
100)*2.5+(units-200)*4
elif
unit<=350
PayAmount=(100*1.5)+(200-
100)*2.5+(300-200)*4+(units-300)*5
PayAmount=1500
STOP
#program for calculating electricity bill in Python
units=int(input("Please enter the number of units you consumed in a month : "))
if(units<=100):
payAmount=units*1.5
elif(units<=200):
payAmount=(100*1.5)+(units-100)*2.5
elif(units<=300):
payAmount=(100*1.5)+(200-100)*2.5+(units-200)*4
elif(units<=350):
payAmount=(100*1.5)+(200-100)*2.5+(300-200)*4+(units-300)*5
else:
payAmount=1500
Total=payAmount;
print("\nElectricity bill=%.2f" %Total)
OUTPUT:
Please enter the number of units you consumed in a month: 120
Electricity bill=200.00
1.B) RETAIL SHOP BILLING
AIM:
To write a python program for implementing retail shop billing.
ALGORITHM:
1. Start the program
2. Assign tax=0.18
3. Assign rate for pencil, pen, scale and A4paper
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.
FLOWCHART:
START
Assign tax=0.18
Assign rate={“Pencil”:10,”Pen”:20,
”Scale”:7,”A4Sheet”:150}
Read quantity of
all items from user
Calculate cost=Pencil*Rate[“Pencil”]
+Pen*Rate[“Pen”]+Scale*Rate[“Scale”]
+A4Sheet*Rate[A4Sheet]
Calculate Bill=cost+cost*tax
Print Bill
#program for calculating retail shop billing in Python
STOP
tax=0.18
Rate={"Pencil":10,"Pen":20,"Scale":7,"A4Sheet":150}
print("Retail Bill Calculator\n")
print("Enter the quantity of the ordered items:\n")
Pencil=int(input("Pencil:"))
Pen=int(input("Pen:"))
Scale=int(input("Scale:"))
A4Sheet=int(input("A4Sheet:"))
cost=Pencil*Rate["Pencil"]+Pen*Rate["Pen"]+Scale*Rate["Scale"]
+A4Sheet*Rate["A4Sheet"]
Bill=cost+cost*tax
print("Please pay Rs.%f"%Bill)
OUTPUT:
Retail Bill Calculator
Enter the quantity of the ordered items:
Pencil:5
Pen:2
Scale:2
A4Sheet:1
Please pay Rs.299.720000
1.C) WEIGHT OF A STEEL BAR
AIM:
To write a python program to calculate weight of a steel bar.
ALGORITHM:
1. Start the program
2. Read the diameter (D) value from user
3. Calculate weight=(D*D)/162
4. Print the weight
5. Stop the program
FLOWCHART:
START
Read
Diameter (D)
Calculate
Weight=(D*D)/162
Print Weight
STOP
#program for calculating weight of a steel bar in Python
print("Calculating weight of a steel bar:\n")
D=int(input("Enter the Diameter of Steel bar:"))
Weight=(D*D)/162
print("Weight of the steel bar is %f Kg/m" %Weight)
OUTPUT:
Calculating weight of a steel bar:
Enter the Diameter of Steel bar:250
Weight of the steel bar is 385.000000 Kg/m
1.D) COMPUTE ELECTRICAL CURRENT IN 3 PHASE AC CIRCUIT
AIM:
To write a python program to calculate electrical current in 3 phase AC circuit.
ALGORITHM:
1. Start the program
2. Read the value of volts and amperes from user
3. Calculate power=√ 3 *volts*amperes
4. Print the value of power
5. Stop the program
FLOWCHART:
START
Read Volts,
Amperes
Calculate
power=√ 3 * Volts*Amperes
Print power
STOP
#program for calculating electrical current
import math
print("Calculating electrical current of 3 phase AC circuit:\n")
volts=int(input("Enter the volts value:"))
amperes=int(input("Enter the amperes value:"))
power=math.sqrt(3)*volts*amperes
print("Power = %f KVA" %power)
OUTPUT:
Calculating electrical current of 3 phase AC circuit:
Enter the volts value:56
Enter the amperes value:85
Power = 8244.561844 KVA
2.a) PROGRAMS USING SIMPLE STATEMENTS EXCHANGE THE VALUES OF
TWO VARIABLES
AIM:
To write a python program to exchange the values of two variables.
ALGORITHM:
1. Start the program
2. Read the value of x and y
3. Exchange the values using the assignment statement x,y=y,x
4. Print the values
5. Stop the program
PROGRAM:
def exchange(x,y):
x,y=y,x
print("After exchange of x,y")
print("x =",x)
print("Y= ",y)
x=input("Enter value of X ")
y=input("Enter value of Y ")
print("Before exchange of x,y")
print("x =",x)
print("Y= ",y)
exchange(x,y)
OUTPUT:
Enter value of X 85
Enter value of Y 63
Before exchange of x,y
('x =', 85)
('Y= ', 63)
After exchange of x,y
('x =', 63)
('Y= ', 85)
2.b) CIRCULATE THE VALUES OF N VARIABLES
AIM:
To write a python program to circulate the values of n variables.
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])
2.c) DISTANCE BETWEEN TWO VARIABLES
AIM:
To write a python program to calculate distance between 2 variables.
ALGORITHM:
1. Start the program
2. Read the value of x1,x2,y1 and y2
3. Calculate distance=√ ( ( x 2−x 1 )∗¿ 2 )−( ( y 2− y 1 )∗¿ 2 )
4. Print the distance
5. Stop the program
PROGRAM:
import math
x1 = int(input("Enter a x1: "))
y1 = int(input("Enter a y1: "))
x2 = int(input("Enter a x2: "))
y2 = int(input("Enter a y2: "))
distance = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print("Distance = %.2f"%distance)
OUTPUT:
Enter a x1: 50
Enter a y1: 50
Enter a x2: 320
Enter a y2: 320
Distance = 381.84
3.a) PROGRAMS USING CONDITIONALS & ITERATIVE LOOPS
NUMBER SERIES
AIM:
To write a python program to calculate 12+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: 5
('Sum = ', 55)
3.b) NUMBER PATTERN
AIM:
To write a python program to print number pattern.
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:
print("Number Pattern Printing")
rows=input("Enter no.of rows to print:")
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(j),
print(' ')
OUTPUT:
Number Pattern Printing
Enter no.of rows to print: 5
12
123
1234
12345
3.c) PYRAMID PATTERN
AIM:
To write a python program to print number pattern.
ALGORITHM:
1. Start the program
2. Read the number of rows to print from user
3. Print the pyramid pattern using for loops
4. Stop the program
PROGRAM:
print("Print equilateral triangle Pyramid using asterisk symbol ")
size =input("Enter no.of rows:")
m = (2 * size) - 2
for i in range(0, size):
for j in range(0, m):
print(" "),
m=m-1
for j in range(0, i + 1):
print("* "),
print(" ")
OUTPUT:
Print equilateral triangle Pyramid using asterisk symbol
Enter no.of rows:5
*
* *
* * *
* * * *
* * * * *
4.A) OPERATIONS OF LIST
ITEMS PRESENT IN A LIBRARY
AIM:
To write a python program to implement operations in a library list
ALGORITHM:
6. Start the program
7. Declare variable library to list the items present in a library
8. Do the operations of list like append, pop, sort, remove, etc on the list
9. Print the result
10.Stop the program
PROGRAM:
# declaring a list of items in a Library
library
=['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','Ebooks']
# printing the complete list
print('Library: ',library)
# printing first element
print('first element: ',library[0])
# printing fourth element
print('fourth element: ',library[3])
# printing list elements from 0th index to 4th index
print('Items in Library from 0 to 4 index: ',library[0: 5])
# appending an element to the list
library.append('Audiobooks')
print('Library list after append Audiobooks: ',library)
# finding index of a specified element
print('index of \'Newspaper\': ',library.index('Newspaper'))
# sorting the elements of List
library.sort()
print('after sorting: ', library);
# popping an element
print('Popped elements is: ',library.pop())
print('after pop(): ', library);
# removing specified element
library.remove('Maps')
print('after removing \'Maps\': ',library)
# inserting an element at specified index # inserting CD at 2nd index
library.insert(2, 'CDs')
print('after insert CDs: ', library)
# Number of Elements in Library list
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)
4.b) OPERATIONS OF TUPLE
COMPONENTS OF A CAR
AIM:
To write a python program to implement operations in a car tuple
ALGORITHM:
1. Start the program
2. Declare a tuple variable car to list the components of a car
3. Print the elements of tuple
4. Stop the program
PROGRAM:
# declaring a tuple of Components of a car
car = ('Engine','Battery','Alternator','Radiator','Steering','Break','Seat Belt')
# printing the complete tuple
print('Components of a car: ',car)
# printing first element
print('first element: ',car[0])
# printing fourth element
print('fourth element: ',car[3])
# printing tuple elements from 0th index to 4th index
print('Components of a car from 0 to 4 index: ',car[0: 5])
# finding index of a specified element
print('index of \'Alternator\': ',car.index('Alternator'))
# Number of Elements in car tuple
print(' Number of Seat Belt in Car Tuple : ',car.count('Seat Belt'))
#Length of car tuple
print(' Length of Elements in Car Tuple : ',len(car))
OUTPUT:
('Components of a car: ', ('Engine', 'Battery', 'Alternator', 'Radiator', 'Steering', 'Break', 'Seat
Belt'))
('first element: ', 'Engine')
('fourth element: ', 'Radiator')
('Components of a car from 0 to 4 index: ', ('Engine', 'Battery', 'Alternator', 'Radiator',
'Steering'))
("index of 'Alternator': ", 2)
(' Number of Seat Belt in Car Tuple : ', 1)
(' Length of Elements in Car Tuple : ', 7)
5.A) OPERATIONS OF SET
COMPONENTS OF AN AUTOMOBILE
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)
#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']))
5.B) OPERATIONS OF DICTIONARY
ELEMENTS OF A CIVIL STRUCTURE
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)
#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'})
6) PROGRAMS USING FUNCTIONS
a. FACTORIAL OF A NUMBER
AIM:
To write a python program to calculate the factorial of a number.
ALGORITHM:
11.Start the program
12.Read a number from user
13.If number=1, then return 1
14.Otherwise calculate the factorial of that number using recursive function
15.Print the result
16.Stop the program
PROGRAM:
def fact(n):
if n==1:
return n
else:
return n*fact(n-1)
num = int(input("Enter a number: "))
print("The factorial of", num, "is", fact(num))
OUTPUT:
Enter a number: 6
('The factorial of', 6, 'is', 720)
6 b. FINDING LARGEST NUMBER IN A LIST
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))
OUTPUT:
Enter no.of elements:5
('Enter', 5, 'elements')
65
78
52
99
56
('Largest element is:', 99)
6 c. AREA OF SHAPES
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 radius and calculate area of circle
4. If choice is 2, read side value and calculate area of square
5. If choice is 3, read length and breadth value and calculate area of rectangle
6. If choice is 4, read breadth and weight value and calculate area of triangle
7. Print the result
8. Stop the program
PROGRAM:
def circle():
r=float(input("Enter r value:"))
return 3.14*r*r
def square():
a=float(input("Enter a value:"))
return a*a
def rectangle():
l=float(input("Enter l value:"))
b=float(input("Enter b value:"))
return l*b
def triangle():
b=float(input("Enter b value:"))
h=float(input("Enter h value:"))
return 0.5*b*h
print("select shape to calculate area:")
print("1.Circle")
print("2.Square")
print("3.Rectangle")
print("4.Triangle")
choice=input("enter choice(1/2/3/4): ")
if choice==1:
print("Area of circle is %.2f" %circle())
elif choice==2:
print("Area of square is %.2f" %square())
elif choice==3:
print("Area of rectangle is %.2f" %rectangle())
elif choice==4:
print("Area of triangle is %.2f" %triangle())
else:
print("invalid input")
OUTPUT:
select shape to calculate area:
1.Circle
2.Square
3.Rectangle
4.Triangle
enter choice(1/2/3/4) : 1
Enter r value:5
Area of circle is 78.50
enter choice(1/2/3/4): 3
Enter l value:8
Enter b value:9
Area of rectangle is 72.00
7) PROGRAMS USING STRINGS
a. REVERSE OF A STRING
AIM:
To write a python program to reverse a string
ALGORITHM:
17.Start the program
18.Read a string from user
19.Perform reverse operation
20.Print the result
21.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')
7b. CHECKING PALINDROME IN A STRING
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
7c. COUNTING CHARACTER IN A STRING
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)
7d. REPLACING CHARACTERS IN A 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
8.A) 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)
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:
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
8.B) NUMPY
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:")
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
8.C) MATPLOTLIB
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()
OUTPUT:
8.D) SCIPY
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')
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')
9.A) COPY FROM ONE FILE TO ANOTHER
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 ‘file copied successfully’
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()
OUTPUT:
Enter source file name: 'file1.txt'
Enter destination file name: 'file2.txt'
File copied successfully!
ROSE
JASMINE
SUN FLOWER
9.B) WORD COUNT FROM A FILE
AIM:
To write a python program to count number of words 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. 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
9.C) FINDING LONGEST WORD IN A FILE
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']
10.A) DIVIDE BY ZERO ERROR USING EXCEPTION HANDLING
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!")
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)
10.B) VOTER’S AGE VALIDITY
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’. Otherwise print ‘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)
You are not eligible to vote
In which year you took birth:- 1994
('Your current age is ', 28)
You are eligible to vote
10.C) STUDENT MARK RANGE VALIDATION
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
11. EXPLORING PYGAME
PYGAME INSTALLATION
Step 1: Check for Python Installation
In order to install Pygame, Python must be installed already in your system. To check
whether Python is installed or not in your system, open the command prompt and give the
command as shown below.
Step 2: Check for PIP installation
PIP is a tool that is used to install python packages. PIP is automatically installed with
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.
Step 3: Install Pygame
To install Pygame, open the command prompt and give the command as shown below:
pip install pygame
Now, Pygame installed successfully.
12) GAME ACTIVITY USING PYGAME
BOUNCING BALL
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:
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: