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

Python Manual New1

The document describes the laboratory manual for the course GE3171: Problem Solving and Python Programming. It contains 12 sections that outline various programming exercises to be completed in the lab. These include developing flowcharts, programs using simple statements, conditionals, iterations, lists, tuples, sets, dictionaries, functions, strings, modules, file handling, and exception handling. It also includes exercises to develop a simple game using Pygame. Flowcharts and Python code are provided for some sample exercises as examples.

Uploaded by

sankariyoga8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Python Manual New1

The document describes the laboratory manual for the course GE3171: Problem Solving and Python Programming. It contains 12 sections that outline various programming exercises to be completed in the lab. These include developing flowcharts, programs using simple statements, conditionals, iterations, lists, tuples, sets, dictionaries, functions, strings, modules, file handling, and exception handling. It also includes exercises to develop a simple game using Pygame. Flowcharts and Python code are provided for some sample exercises as examples.

Uploaded by

sankariyoga8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

SACS MAVMM

ENGINEERING COLLEGE
Kidaripatty (PO), Alagarkoil (via), Madurai – 625 301.

GE3171: Problem Solving and


Python Programming
Laboratory
LAB MANUAL
List of Programs
1. Developing flow charts
a. Electricity Billing,
b. Retail Shop Billing,
c. Sin Series,
d. Weight of a Motorbike,
e. Weight of a Steel Bar,
f. Compute Electrical Current in Three Phase AC Circuit,
2. Programs Using Simple Statements
a. Exchange the values of two variables,
b. Circulate the values of n variables,
c. Distance between two points.
3. Programs Using Conditionals and Iterative Statements
a. Number Series
b. Number Patterns
c. Pyramid Pattern
4. Operations of Lists and Tuples (Items present in a
library/Components of a car/ Materials required for construction of
a building)
5. Operations of Sets & Dictionaries (Language, components of an
automobile, Elements of a civil structure, etc)
6. Programs Using Functions
a. Factorial of a Number
b. Largest Number in a list
c. Area of Shape
7. Programs using Strings.
a. Reversing a String,
b. Checking Palindrome in a String,
c. Counting Characters in a String
d. Replacing Characters in a String
8. Programs Using modules and Python Standard Libraries (pandas, numpy.
Matplotlib, scipy)
9. Implementing real time /technical applications using File handling(copy one
file to another , word count longest word.

10. Programs Using Exception handling.

a.Divide by zero error,


b. Voter’s age validity,
c. Student mark range validation
11. Exploring pygame-installing
12. Developing a game activity using Pygame like bouncing ball, car race etc.
Ex. No: 1.A) ELECTRICITY BILLING
Aim
To draw flowchart for Electricity Billing
Flowchart

Start

Read Units

<=100 <=200 Units= <=500 >500


?

Amount = (100* 0) + Amount = (100* 0) +


Amount= (100*0)+ (200– 100)*2 + (200 – 100)*3.5 +
Amount=100*0
(Unit – 100) *1.5 (Unit – 200)*3 (500 – 200)* 4.6+
(Unit – 500) * 6.6

Print Amount

Stop

Result
Thus the flowchart for Electricity Billing was drawn successfully
Ex. No: 1.B) RETAIL SHOP BILLING

Aim
To draw flowchart for Retail shop billing
Flowchart

Start

tax=0.18
Rate_of_item

Display Items

Read Quantities

Cost=Rate_of_item * quantity+
Rate_of_item * quantity+ ……………..

Bill_Amount=cost+cost*tax

Print Bill_Amount

Stop

Result
Thus the flowchart for Retail shop billing was drawn successfully
Ex. No: 1.C) SINE SERIES

Aim
To evaluate and draw flowchart for Sine Series
Flowchart
Start

Read x, n

x=x*3.14159/180
t=x
sum=x

i=1; i<n; i++

t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;

Print sum as sin(x)

Stop

Result
Thus the flowchart for Sine Series was drawn successfully
Ex. No: 1.D) WEIGHT OF A MOTORBIKE

Aim
To draw flowchart for weight of Motorbike
Flowchart
Start

Read weight

==315 kg ==180 kg ==250 kg weight = ? ==115 kg ==400 kg ==340 kg

Print Print Print Print Print Print


Chopper Sports Cruiser Scooter Touring Bagger
Bike Bike

Stop

Result
Thus the flowchart for weight of Motorbike was drawn successfully
Ex. No: 1.E) WEIGHT OF A STEEL BAR

Aim
To draw flowchart for Weight of a Steel Bar
Flowchart

Start

Read Diameter D

W=D2/162

Print W

Stop

Result
Thus the flowchart for Weight of a Steel Bar was drawn successfully
Ex. No: 1.F) COMPUTE ELECTRICAL CURRENT IN THREEPHASE AC CIRCUIT

Aim
To draw flowchart for Compute electrical current in three phase AC circuit.
Flowchart

Start

Read Vline, Aline

VA =√𝟑 *Vline * Aline

Print VA

Stop

Result
Thus the flowchart for Compute electrical current in three phase AC circuit was drawn successfully
Ex. No: 2.A) EXCHANGE THE VALUES OF TWO VARIABLES USING TEMPORARY VARIABLE
Aim
To write a program to exchange the values of two variables using third variable
Algorithm
1. Start
2. Read x and y
3. Print x and y value before swap
3. Swap values using temporary variable
temp=x
x=y
y=temp
4. Print x and y value after swap
5. Stop
Program
x = int(input("Enter x value:")) y =
int(input("Enter y value:")) print("Value
of x and y before swap:",x,y) temp = x
x=y
y = temp
print("Value of x and y after swap:",x,y)
Output
Enter x value:10
Enter y value:23
Value of x and y before swap: 10 23
Value of x and y after swap: 23 10

Result
Thus the Python program to exchange the values of two variables by using a third variable
was executed successfully
Ex. No: 2.B) EXCHANGE THE VALUES OF TWO VARIABLES WITHOUT USING TEMPORARY
VARIABLE
Aim
To write a program to exchange the values of two variables without using third variable
Algorithm
1. Start
2. Read x and y
3. Print x and y value before swap
3. Swap values without temporary variable
x=x+y
y=x-y
x=x-y
4. Print x and y value after swap
5. Stop
Program
x = int(input("Enter x value:")) y =
int(input("Enter y value:")) print("Value
of x and y before swap:",x,y) x=x+y
y=x-y
x=x-y
print("Value of x and y after swap:",x,y)
Output
Enter x value:24
Enter y value:45
Value of x and y before swap: 24 45
Value of x and y after swap: 45 24

Result
Thus the Python program to exchange the values of two variables without using a third variable
was executed successfully.
Ex. No: 2.C) CIRCULATE THE VALUES OF N VARIABLES
Aim
To write a program to circulate the values of N variables.
Algorithm
1. Start
2. Read upper limit n
3. Read n element using loop
4. Store elements in list
5. POP out each element from list and append to list
6. Print list
7. Stop
Program
n = int(input("Enter number of values:"))
list1=[ ]
for i in range(0,n,1):
x=int(input("Enter integer:"))
list1.append(x)
print("Circulating the elements of list:",list1)
for i in range(0,n,1):
x=list1.pop(0)
list1.append(x)
print(list1)
Output
Enter number of values:3
Enter integer:2
Enter integer:3
Enter integer:5
Circulating the elements of list: [2, 3, 5]
[3, 5, 2]
[5, 2, 3]
[2, 3, 5]
Result
Thus the Python program to circulate the values of N variables was executed successfully.
Ex. No: 2.D) DISTANCE BETWEEN TWO VARIABLES

Aim
To write a program to find distance between two variables.
Algorithm
1. Start
2. Read four coordinates x1, y1, x2, y2

3. Find distance using


4. Print distance
5. Stop
Program
x1=int(input("Enter x1 value: "))
y1=int(input("Enter y1 value: "))
x2=int(input("Enter x2 value: "))
y2=int(input("Enter y2 value: "))
distance=((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))**0.5
print("Distance = ",distance)
Output
Enter x1 value: 1
Enter y1 value: 2
Enter x2 value: 3
Enter y2 value: 4
Distance = 2.8284271247461903

Result
Thus the Python program to find distance between two variables was executed successfully.
Ex. No: 3.A) NUMBER SERIES

Aim
To write a program to evaluate number series 12+22+32+….+N2
Algorithm
1. Start
2. Read maximum limit n
3. Initialize sum=0 and i=1
4. Calculate sum of series
while i<=n:
sum=sum+i*i
increment i
5. Print sum
6. Stop
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: 3
Sum = 14

Result
Thus the Python program to evaluate number series was executed successfully.
Ex. No: 3.B) NUMBER PATTERN

Aim
To write a program to print number pattern
Algorithm
1. Start
2. Read upper limit N
3. Print pattern using nested for loop
for i in range(rows)
for j in range(i+1)
print j
4. Stop
Program
rows = int(input("Enter number of rows: "))
for i in range(rows):
for j in range(i+1):
print(j+1, end=" ")
print("\n")
Output
Enter the number: 3

12

123

Result
Thus the Python program to print number pattern was executed successfully.
Ex. No: 3.C) HALF PYRAMID PATTERN

Aim
To write a python program to print half pyramid pattern
Algorithm
1. Start
2. Read upper limit rows
3. Print pyramid pattern using nested for loop
for i in range(rows):
for j in range(i+1)
print * in half pyramid
print newline
4. Stop
Program
rows = int(input("Enter number of rows: "))
for i in range(rows):
for j in range(i+1):
print("* ", end="")
print("\n")
Output
Enter number of rows: 4
*
**
** *
** * *

Result
Thus the Python program to print half pyramid pattern was executed successfully.
Ex. No: 3.D) FULL PYRAMID PATTERN

Aim
To write a program to print pyramid pattern.
Algorithm
1. Start
2. Read upper limit rows
3. Print pyramid using for and while loop
for i in range(row):
print s in range (rows,i,-1)
print end=” “
for j in range(i+1)
print(end=”* “)

4. Process continues upto range


5. Stop
Program
print("Enter Number of Rows: ")
row = int(input())
print("Star Pyramid of " + str(row) + " Rows or Lines: ")
for i in range(row):
for s in range(row, i, -1):
print(end=" ") for j
in range(i+1):
print(end="* ")
print()

Output
Enter the number of rows: 3
*
* *
* * *
Result

Thus the Python program to print full pyramid pattern was executed successfully.
Ex. No: 4.A) ITEMS PRESENT IN A LIBRARY

Aim
To write a program to implement operations in a library list
Algorithm
1. Start
2. Read library list
3. Print library details
4. Print first and fourth position element
5. Print items from index 0 to 4
6. Append new item in library list
7. Print index of particular element
8. Sort and print the element in alphabetical order
9. Pop the element
10. Remove the element
11. Insert an element in position
12. Count the number of elements in library
13. Stop
Program
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]) print('-7th
element: ',library[-7]) library.append('Audiobooks')
print('Library list after append( ): ',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')
print('After removing \'Maps\': ',library)
library.insert(2, 'CDs')
print('After insert: ', library)
print('Number of Elements in Library list: ',library.count('Ebooks'))
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']
-7th element: Periodicals
Library list after append( ): ['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: ['Audiobooks', 'Books', 'CDs', 'Documents', 'Ebooks', 'Manuscripts', 'Newspaper', 'Periodicals']
Number of Elements in Library list: 1

Result
Thus the Python program to print items present in a library using list operation was executed successfully.
Ex. No: 4.B) COMPONENTS OF A CAR

Aim
To write a program to implement operations of Tuple using Components of a Car
Algorithm
1. Start
2. Read car tuple
3. Print components of car
4. Print first and fourth position element
5. Print items from index 0 to 4
6. Print index of particular element
7. Count the number of ‘Seat Belt element’ in car tuple
8. Count number of elements in car tuple
9. Stop
Program
car = ('Engine','Battery','Alternator','Radiator','Steering','Break','SeatBelt')
print('Components of a car: ',car)
print('First element: ',car[0])
print('Fourth element: ',car[3])
print('Components of a car from 0 to 4 index: ',car[0: 5])
print('3rd or -7th element: ',car[-7])
print('Index of \'Alternator\': ',car.index('Alternator'))
print('Number of Elements in Car Tuple : ',car.count('Seat Belt'))
print('Length of Elements in Car Tuple : ',len(car))
Output
Components of a car: ('Engine', 'Battery', 'Alternator', 'Radiator', 'Steering', 'Break', 'SeatBelt')
First element: Engine
Fourth element: Radiator
Components of a car from 0 to 4 index: ('Engine', 'Battery', 'Alternator', 'Radiator', 'Steering')
3rd or -7th element: Engine
Index of 'Alternator': 2
Number of Elements in Car Tuple: 0
Length of Elements in Car Tuple: 7
Result
Thus the Python program to print components of a car using tuple operation was executed successfully.
Ex. No: 4.C) MATERIALS REQUIRED FOR CONSTRUCTION OF A BUILDING

Aim
To write a program for operations of list to print materials required for construction of a building
Algorithm
1. Start
2. Read material list
3. Print material details
4. Print first and fourth position element
5. Print number of elements in material list
6. Print items from index 0 to 2
7. Append new item in material list
8. Print list of material after append
9. Print ending alphabet of material
10. Print starting alphabet of material
11. Print index of particular element
12. Sort and print the element in alphabetical order
13. Pop the element and print remaining element of material
14. Remove an element and print remaining element of material
15. Insert an element in position
16. Print the element after inserting
17. Stop
Program
material =['Wood','Concrete','Brick','Glass','Ceramics','Steel']
print('Building Materials',material)
print('First element: ',material[0])
print('Fourth element: ',material[3])
print('Number of Elements in Material list : ',len(material))
print('Items in Material from 0 to 2 index: ',material[0: 3])
print('-3th element: ',material[-3])
material.append('Water')
print('Material list after append(): ',material)
print('Ending Alphabet of Material',max(material))
print('Starting Alphabet of Material',min(material))
print('Index of Brick: ',material.index('Brick'))
material.sort( )
print('After sorting: ', material);
print('Popped elements is: ',material.pop())
print('After pop(): ', material);
material.remove('Glass')
print('After removing Glass: ',material)
material.insert(3, 'Stone')
print('After insert: ', material)
Output
Building Materials ['Wood', 'Concrete', 'Brick', 'Glass', 'Ceramics', 'Steel']
First element: Wood
Fourth element: Glass
Number of Elements in Material list : 6
Items in Material from 0 to 2 index: ['Wood', 'Concrete', 'Brick']
-3th element: Glass
Material list after append(): ['Wood', 'Concrete', 'Brick', 'Glass', 'Ceramics', 'Steel', 'Water']
Ending Alphabet of Material Wood
Starting Alphabet of Material Brick
Index of Brick: 2
After sorting: ['Brick', 'Ceramics', 'Concrete', 'Glass', 'Steel', 'Water', 'Wood']
Popped elements is: Wood
After pop(): ['Brick', 'Ceramics', 'Concrete', 'Glass', 'Steel', 'Water']
After removing Glass: ['Brick', 'Ceramics', 'Concrete', 'Steel', 'Water']
After insert: ['Brick', 'Ceramics', 'Concrete', 'Stone', 'Steel', 'Water']

Result
Thus the Python program to print materials required for construction of a building using list operation
was executed successfully.
Ex. No: 5.A) COMPONENTS OF A LANGUAGE

Aim
To implement operations of set to print components of a language
Algorithm
1. Start
2. Read two sets L1 and L2
3. Print union of L1 and L2
4. Print Intersection of L1 and L2
5. Print Difference L1 and L2
6. Print Symmetric difference of L1 and L2
7. Stop
Program
L1 = {'Pitch', 'Syllabus', 'Script', 'Grammar', 'Sentences'};
L2 = {'Grammar', 'Syllabus', 'Context', 'Words', 'Phonetics'};
print("Union of L1 and L2 is ",L1 | L2)
print("Intersection of L1 and L2 is ",L1 & L2)
print("Difference of L1 and L2 is ",L1 - L2)
print("Symmetric difference of L1 and L2 is ",L1 ^ L2)
Output
Union of L1 and L2 is {'Phonetics', 'Sentences', 'Context', 'Script', 'Syllabus', 'Grammar', 'Words', 'Pitch'}
Intersection of L1 and L2 is {'Syllabus', 'Grammar'}
Difference of L1 and L2 is {'Script', 'Pitch', 'Sentences'}
Symmetric difference of L1 and L2 is {'Script', 'Phonetics', 'Sentences', 'Context', 'Pitch', 'Words'}

Result
Thus the Python program to print components of a language using set operation was executed successfully.
Ex. No: 5.B) ELEMENTS OF A CIVIL STRUCTURE

Aim
To implement operations of dictionary to print elements of a civil structure
Algorithm
1. Start
2. Read elements in civil variable
3. Print elements
4. Insert element in last position and print
5. Update element in particular position and print the elements
6. Print the value of key using square bracket and get method
7. Remove element from the structure and print the remaining elements
8. Remove element arbitrarily using popitem( ) function
9. Stop
Program
civil = {1:'Foundation',2:'Roof',3:'Beams',4:'Columns',5:'Walls'};
print(civil)
civil[6]='Stairs'
print("Print elements after adding:",civil)
civil[3]='Lintels'
print("Elements after updating key 3:",civil)
print("Print value of Key 2:",civil[2])
print("Print value of Key 5:",civil.get(5))
print("Element removed from key 1:",civil.pop(1))
print("Elements after removal:",civil)
print("Element removed arbitrarily:",civil.popitem())
print("Elements after pop:",civil)
Output
{1: 'Foundation', 2: 'Roof', 3: 'Beams', 4: 'Columns', 5: 'Walls'}
Print elements after adding: {1: 'Foundation', 2: 'Roof', 3: 'Beams', 4: 'Columns', 5: 'Walls', 6: 'Stairs'}
Elements after updating key 3: {1: 'Foundation', 2: 'Roof', 3: 'Lintels', 4: 'Columns', 5: 'Walls', 6: 'Stairs'}
Print value of Key 2: Roof
Print value of Key 5: Walls
Element removed from key 1: Foundation
Elements after removal: {2: 'Roof', 3: 'Lintels', 4: 'Columns', 5: 'Walls', 6: 'Stairs'}
Element removed arbitrarily: (6, 'Stairs')
Elements after pop: {2: 'Roof', 3: 'Lintels', 4: 'Columns', 5: 'Walls'}

Result
Thus the Python program to print elements of civil structure using dictionary operation was executed
successfully.
Ex. No: 6.A) FACTORIAL USING RECURSION

Aim
To write a program to find the factorial of a number using recursion
Algorithm
1. Start
2. Read num
3. Call fact (n)
4. Print factorial f
5. Stop
Fact (n)
1. if n==1 then
return n
2. else
return (n*fact (n-1))
Program
def fact (n):
if n==1:
return n
else:
return (n*fact (n-1))
num = int (input("Enter a number: "))
f=fact(num)
print("The factorial of",num,"is",f)
Output
Enter a number: 3
The factorial of 3 is 6

Result
Thus the Python program to find factorial of a number using recursion was executed successfully.
Ex. No: 6.B) FINDING LARGEST NUMBER IN A LIST USING FUNCTION

Aim
To write a program to find the largest number in a list using functions.
Algorithm
1. Start
2. Initialize empty list as lis1t=[ ]
3. Read upper limit of list n
4. Read values of list using for loop
for i in range(1,n+1)
Read num
Append num in list1
5. Call function myMax(list1)
6. Stop
myMax(list1)
1. Print largest element in a list using max( ) function
Program
def myMax(list1):
print("Largest element is:", max(list1))
list1 = [ ]
n = int(input("Enter number of elements in list: "))
for i in range(1, n + 1):
num = int(input("Enter elements: "))
list1.append(num)
myMax(list1)
Output
Enter number of elements in list: 4
Enter elements: 23
Enter elements: 15
Enter elements: 67
Enter elements: 45
Largest element is: 67
Result
Thus the Python program to find the largest number in a list using functions was executed successfully.
Ex. No: 6.C) FINDING AREA OF A SHAPE USING FUNCTION

Aim
To write a program to find the area of a shape using functions
Algorithm
1. Start
2. Print Calculate Area of Shape
3. Read shape_name
4. Call function calculate_area(shape_name)
5. Stop
calculate_area(name):
1. Convert letters into lowercase
2. Check name== “rectangle” :
Read l
Read b
Calculate rect_area=l*b
Print area of rectangle
3. elif name==”square”:
Read s
Calculate sqt_area = s * s
Print area of square
4. elif name == "triangle":
Read h
Read b
Calculate tri_area = 0.5 * b * h
Print area of triangle
5. elif name == "circle":
Read r
Calculate circ_area = pi * r * r
Print area of circle
6. else:
Print Sorry! This shape is not available
Program
def calculate_area(name):
name = name.lower()
if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))
rect_area = l * b
print ("The area of rectangle=", rect_area)
elif name == "square":
s = int(input("Enter square's side length: "))
sqt_area = s * s
print ("The area of square=",sqt_area)
elif name == "triangle":
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))
tri_area = 0.5 * b * h
print ("The area of triangle=",tri_area)
elif name == "circle":
r = int(input("Enter circle's radius length: "))
pi = 3.14
circ_area = pi * r * r
print ("The area of circle=",circ_area)
else:
print("Sorry! This shape is not available")
print("Calculate Area of Shape")
shape_name = raw_input("Enter the name of shape: ")
calculate_area(shape_name)
Output
Calculate Area of Shape
Enter the name of shape: rectangle
Enter rectangle's length: 2
Enter rectangle's breadth: 3
('The area of rectangle=', 6)
Result
Thus the Python program to find the area of a shape using functions was executed successfully.
Ex. No: 7.A) REVERSING A STRING

Aim
To write a program to find reverse a string.
Algorithm
1. Start
2. Read string in s
3. Print reversed string through function reverse(s)
4. Stop
reverse(string):
1. Reverse a string using join(reversed(string))
2. return reversed string
Program
def reverse(string):
string = "".join(reversed(string))
return string
s = raw_input("Enter any string: ")
print ("The original string is:",s)
print ("The reversed string(using reversed):",reverse(s))
Output
Enter any string: river
('The original string is:', 'river')
('The reversed string(using reversed):', 'revir')

Result
Thus the Python program to find reverse a string was executed successfully.
Ex. No: 7.B) PALINDROME IN A STRING

Aim
To write a program to check a given string is palindrome or not.
Algorithm
1. Start
2. Read string
3. Reverse a string using reversed( ) function
4. Check rev_string==original_string
Print "It is palindrome"
5. else
It is not palindrome
6. Stop
Program
string = raw_input("Enter string: ")
rev_string = reversed(string)
if list(string)== list(rev_string):
print("It is palindrome")
else:
print("It is not palindrome")
Output
Enter string: mam
It is palindrome

Result
Thus the Python program to check a string palindrome was executed successfully.
Ex. No: 7.C) COUNT CHARACTERS IN A STRING

Aim
To write a program to count number of characters in a string.
Algorithm
1. Start
2. Read string
3. Read character to count
4. Count number of characters using count( ) function
5. Print count
6. Stop
Program
string = raw_input("Enter any string: ")
char = raw_input("Enter a character to count: ")
val = string.count(char)
print("count",val)
Output
Enter any string: river
Enter a character to count: r
('count', 2)

Result
Thus the Python program to count number of characters in a string was executed successfully
Ex. No: 7.D) REPLACING CHARACTERS

Aim
To write a program to replace characters in a string.
Algorithm
1. Start
2. Read string
3. Read old string to replace in str1
4. Read new string in str2
5. replace(str1,str2)
6. Print replaced string
7. Stop
Program
string = raw_input("Enter any string: ")
str1 = raw_input("Enter old string: ")
str2 = raw_input("Enter new string: ")
print(string.replace(str1, str2))
Output
Enter any string: python
Enter old string: p
Enter new string: P
Python

Result
Thus the Python program to replace characters in a string was executed successfully
Ex.No:8A) 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]

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

Result
Thus the Python program to compare the elements of the two Pandas Series using Pandas library was executed
successfully.
Ex.No:8B) NUMBY

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

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

Result
Thus the Python program to test whether none of the elements of a given array is zero using Numpy was executed
successfully.
Ex.No:8C) MATPLOTLIB

Aim:

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

Program:

import matplotlib.pyplot as plt


import numpy as np
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('My first graph!')
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.show()

Output:

Result

Thus the Python program to plot a graph using matplotlib library was executed successfully.
Ex.No:8D) SCIPY

Aim:
To write a python program to return the specified unit in seconds
(e.g. hour returns 3600.0) using scipy library.

Program:

from scipy import constants print(constants.minute)


print(constants.hour)
print(constants.day)
print(constants.week)
print(constants.year) print(constants.Julian_year)

Output:

60.0
3600.0
86400.0
604800.0
31536000.0
31557600.0

Result

Thus the Python program to return the specified unit in seconds using scipy library was executed
successfully.
Ex.9.A File copy

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

Algorithm :

STEP 1: Create a New Text Document and Rename it as "a.txt"

STEP 2: Write Some Content in that file and Save.

STEP 3: Now Compile the Program and RUN it.

STEP 4: Now a new file will be created with a name "b.txt" and all the content would copy from a.txt to b.txt.

Program:

source=open("a.txt","r")

destination=open("b.txt","w")

for line in source:

destination.write(line)

source.close()

destination.close()

print("File Copied")

Output:
Result :

Thus the above program was executed and verified.


EX9.B. WORD COUNT

AIM :
To write a python program to count the words in a file.

ALGORITHM :

Step1 : Open a file in read mode using open() function.


Step2 : Read a line from file using read() function.
Step3 : Split the line into words and store it .
Step4 : len() function is used to count the words.
Step5 : Finally print the word count.

PROGRAM :

file = open("a.txt", "rt")

data = file.read()

words = data.split()

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

Output
Result :

Thus the above program was executed and verified.


Ex.no.9c Longest Count

Aim :

To write a python program to print the longest word in a file.

ALGORITHM :

Step1 : Open a file in read mode using open() function.


Step2 : Read a line from file using read() function.
Step3 : Split the line into words and store it .
Step4 : len() function is used to find the longest word in a text file.
Step5 : Finally print the longest word.

Program :

with open(inputFile, 'r') as filedata:

wordsList=filedata.read().split()

longestWordLength=len(max(wordsList,key=len))

result=[textword for textword in wordsList if len(textword) == longestWordLength]

print("The following are the longest words from a text file:")

print(result)

filedata.close()

Output
Result :

Thus the above program was executed and verified.


EX.NO:10A) DIVIDE BY ZERO USING EXCEPTION HANDLING

Aim:

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

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:10


Enter the value of d:5
Enter the value of c:5
Division by Zero!

Result

Thus the Python program handle divide by zero error using exception handling was executed successfully.
EX.NO:10 B) VOTER AGE VALIDATION

Aim:

To write a python program to check voters age validity.

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:- 1981


Your current age is 40
You are eligible to vote

In which year you took birth:- 2011


Your current age is 10
You are not eligible to vote

Result

Thus the Python program to check voters age validity was executed successfully.
EX.NO:10 C) STUDENT MARK RANGE VALIDATION

Aim:

To write a python program to perform student mark range validation.

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: 150


The value is out of range, try again.

Enter the Mark: 98


The Mark is in the range

Result

Thus the Python program to perform student mark range validation was executed successfully.
EX.NO:11 EXPLORING PYGAME

PYGAME INSTALLATION

Aim:
To Install Pygame Module

Steps:

1. Install python 3.6.2 into C:\


2. Go to this link to install pygame www.pygame.org/download.shtml

3. Click pygame-1.9.3.tar.gz ~ 2M and download zar file


4. Extract the zar file into C:\Python36-32\Scripts folder
5. Open command prompt
6. Type the following command
C:\>py -m pip install pygame --user
Collecting pygame
Downloading pygame-1.9.3-cp36-cp36m-win32.whl (4.0MB)

100% |████████████████████████████████| 4.0MB 171kB/s

Installing collected packages: pygame Successfully installed pygame-1.9.3

7. Now, pygame installed successfully


8. To see if it works, run one of the included examples in pygame-1.9.3
• Open command prompt
• Type the following

C:\>cd Python36-32\Scripts\pygame-1.9.3
C:\Python36-32\Scripts\pygame-1.9.3>cd examples

C:\Python36-32\Scripts\pygame-1.9.3\examples>aliens.py

C:\Python36-32\Scripts\pygame-1.9.3\examples>

Output:

Result:

Thus the pygame tool is installed successfully.


EX.NO:12 STIMULATE BOUNCING BALL AND CAR RACING USING
PYGAME

Aim:

To write a program to bouncing ball and car race in Pygame.

Program:
BOUNCING BALL
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()

CAR RACE
import pygame
pygame.init() #initializes the Pygame
from pygame.locals import* #import all modules from Pygame
screen = pygame.display.set_mode((798,600))

#changing title of the game window


pygame.display.set_caption('Racing Beast')

#changing the logo


logo = pygame.image.load('car game/logo.jpeg')
pygame.display.set_icon(logo)

#defining our gameloop function


def gameloop():

#setting background image


bg = pygame.image.load('car game/bg.png')

# setting our player


maincar = pygame.image.load('car game\car.png')
maincarX = 350
maincarY = 495

#other cars
car1 = pygame.image.load('car game\car1.jpeg')
car2 = pygame.image.load('car game\car2.png')

run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#CHANGING COLOR WITH RGB VALUE, RGB = RED, GREEN, BLUE
screen.fill((0,0,0))

#displaying the background image


screen.blit(bg,(0,0))

#displaying our main car


screen.blit(maincar,(maincarX,maincarY))

#displaing other cars


screen.blit(car1,(200,100))
screen.blit(car2,(300,100))

pygame.display.update()

gameloop()

Output
Bouncing Ball
CAR RACE

Result:

Thus the bouncing ball and car race was created successfully using pygame.

You might also like