0% found this document useful (0 votes)
9 views70 pages

GE3171_PSPP_Lab Record

The document is a laboratory record for the GE3171 Problem Solving and Python Programming course at Adithya Institute of Technology, detailing various experiments and exercises related to Python programming and problem-solving techniques. It includes flowcharts, algorithms, and pseudo code for tasks such as electricity billing, retail shop billing, and calculating distances between points. The record serves as a certified account of the work done by students for their practical examination.

Uploaded by

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

GE3171_PSPP_Lab Record

The document is a laboratory record for the GE3171 Problem Solving and Python Programming course at Adithya Institute of Technology, detailing various experiments and exercises related to Python programming and problem-solving techniques. It includes flowcharts, algorithms, and pseudo code for tasks such as electricity billing, retail shop billing, and calculating distances between points. The record serves as a certified account of the work done by students for their practical examination.

Uploaded by

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

ADITHYA INSTITUTE OF TECHNOLOGY

COIMBATORE-107

GE3171 – PROBLEM SOLVING AND


PYTHON PROGRAMMING LABORATORY

Department of

ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


Department of

ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

GE3171 – PROBLEM SOLVING AND PYTHON PROGRAMMING


LABORATORY
LABORATORY RECORD

NAME: .................................................................. ROLL NO: .............................................

CLASS: .................................................................. BRANCH: .............................................

Certified bonafide record of work done by…………………………….…………………

Place:

Date:

Staff In-Charge Head of the Department

University Register Number: ………………………………………………………………….

Submitted for the University Practical Examination held on …….………………

INTERNAL EXAMINER EXTERNAL EXAMINER


INDEX

MA FACUL
EX.NO EXPERIMEN PAG
TS R TY
E NO
KS SIGN
1 Flowcharts for simple real life or scientific or technical problems
1 Electricity Billing 1
a
1 Retail Shop Billing 3
b
1 Result of SINE Series 5
c
1 Weight of Motorbike 7
d
1 Weight of Steel Bar 8
e
1 Compute Electrical Current in Three Phase AC Circuit 9
f
2 Python programming using simple statements and expressions
2 Exchange the values of two variables 10
a
2 Circulate the values of n variables 11
b
2 Distance between two points 12
c
3 Scientific problems using Conditionals and Iterative loops
3 Number Series 13
a
3 Number Pattern 13
b
3 Pyramid Pattern 14
c
Implementing real-time/technical applications using Lists, Tuples.
4 (Items present in a library/Components of a car/ Materials required
for construction of a building –operations of list & tuples)
Basic list operations in items present in a
4 library/Components of a car/ Materials required 15
a for construction of a building
Basic tuple operations in items present in a 17
4 library/Components of a car/ Materials required
b for construction of a building
Implementing real-time/technical applications using Sets,
5 Dictionaries. (Language, components of an automobile, Elements
of a civil structure, etc.- operations of Sets & Dictionaries)
5 Basic Set Operations 18
a
5 Basic Dictionary Operations 19
b
Implementing programs using Functions. (Factorial, largest
6
number in a list, area of shape)
6 Calculate Factorial Using Functions 20
a
6 Finding largest number in a list using Functions 21
b
6 Calculate area of shape using Functions 22
c
Implementing programs using Strings. (Reverse, palindrome, character
7
count, replacing characters)
7a Reverse the string 23
7b Palindrome of a string 24
7c Count the character of string 25
7d Replacing the existing character in a string 26
Implementing programs using written modules and Python Standard
8
Libraries (pandas, numpy, Matplotlib, scipy)
8a Python programs using pandas module. 27
8b Python programs using numpy module. 29
.i.
8b Matrix Operations using numpy module 30
.ii
8c Python programs using Matplotlib module 31
8d Python programs using scipy module 32
Implementing real-time/technical applications using file handling.
9
(copy from one file to another, word count, longest word)
9a Copy from one file to another 33
9b Count number of words in a string 34
9c Find the longest word in a file 35
Implementing real-time/technical applications using Exception
10
handling. (divide by zero error, voter’s age validity, student mark
range validation)
10 Handling exception divide by zero error 36
a
10 Handling exception voters age validity 37
b
10 Handling exception Student mark range validation 38
c
11 Exploring Pygame tool.
11 Getting Started with PyGame 39
a
11 Image loading using Pygame 40
b
11 Font Style and size in Pygame 41
c
12 Developing a game activity using Pygame like bouncing ball, car race etc.
12 Bouncing Ball using Pygame 42
a
12 Simulate Car Race using Pygame 44
b
12 Simulate Elliptical Orbits in Pygame 49
c
Total
Average
Ex. No: 1 Date:
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 ACCircuit, etc.)
Aim:
To Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for the same.
1a. Electricity Billing
To input electricity unit charges and calculate total electricity bill

Per Unit rate in TNEB


Scheme Unit Per Fixed Charges Per Month
unit(₹)
0 to 100 0-100
0-100
0 to 200 2
101-200 1.5 0
0-100
0 to 500 3
101-200 2
0
201-500 3
0-100
101-200 3.5
> 500 5
201-500 4.6 0
>500 6.6

Algorithm
Step 1: Start
Step 2: Read unit
Step 3: If unit< = 100 then Electricity_Charge = 0
Step 4: else if unit <= 200 goto step 5 otherwise goto step 6
Step 5: Calculate Chargeable_unit and Electricity_Charge using the
formula Electricity_Charge = (100 * 0) + (units - 100)*1.5+20
Step 6: If unit <= 500 goto step 7 otherwise goto step 8
Step 7: Calculate Chargeable_unit and Electricity_Charge using the formula
Electricity_Charge = (100 * 0) + (100*2) + (units-200) * 3 + 30
Step 8: Calculate Chargeable_unit and Electricity_Charge using the formula Electricity_Charge
= (100 * 0) + (100 * 3.5) + ( 300 *4.6)+(units- 500)*6.6 + 50
Step 9: Print the value of
Electricity_Charge Step 10: Stop
Flowchart

Pseudo code
BEGIN
READ units
IF unit< = 100 THEN Electricity_Charge =
0 ELSE
IF unit <= 200 THEN
Electricity_Charge = (100 * 0) + (units - 100)*1.5+20
ELSE IF unit <= 500 THEN
Electricity_Charge = (100 * 0) + (100*2) + (units-200) * 3 + 30ELSE
Electricity_Charge = (100 * 0) + (100 * 3.5) + ( 300 *4.6)+(units- 500)*6.6 + 50END
IF
END
IF END
IF
PRINT Electricity_Charge
END
1b. Retail

Shop Billing

Algorithm

Step 1: Start
Step 2: Initialize the system and
total Step 3: Read the Barcode
Step 4: If barcode matched means read data from memory and display the value
Step 5: Add the total amount as items is added
Step 6: If any items removed then reduce the item value from the total
amount Step 7: Display the total amount
Step 8: Print the
bill Step 9: Stop

Pseudo code

BEGIN
Total=0
FOR all items in list
READ barcode
DISPLAY value
Total = total
+value
END FOR
IF item removed
Total = Total –Item_value
END IF
PRINT Total
END
Flowchart
1c. The Flowchart for calculating the result of Sine series

Description
sin (x) = (x^1/1!) - (x^3/3!) + (x^5/5!) - (X^7/7!) + ...n
input x is degrees. So we need to convert degree to radian. Formula for converting degree to radianis
x*(3.14159/180)

Algorithm

Step 1: Start
Step 2: Read n, x
Step 3: fact =1, sum=x, i=3, sign=-
1 Step 4: Calculate x=x/180*3.14
Step 5: If i<=n then goto step 6 else goto step
11 Step 6: Calculate fact = fact *i *(i-1)
Step 7: sum= sum
+pow(x,i)/fact Step 8: sign = sign * -
1
Step 9: i=i+2
Step 10: goto step
5 Step 11: Print sum
Step 12: Stop

Pseudo code

BEGIN
READ
n,x
INITIALIZE fact=1, sum=x, i=3, sign=-
1 CALCULATE x=x/180*3.14
FOR (if i<=n)
CALCULATE fact = fact *i *(i-1)
CALCULATE sum= sum
+pow(x,i)/factCALCULATE sign =
sign * -1 CALCULATE i=i+2
END FOR
PRINT
sum END
Flowchart

No
1d. Weight of a
Motorbike Description
The formula used to calculate weight of motorbike is w = mg
Where w=weight in Newton’s or kilograms-force, m=mass in
kilograms, g=9.81 Algorithm
Step 1: Start
Step 2: Read the value m
Step 3: Initialize g =9.81
Step 4: Calculate w = mg
Step 5: Print W
Step 6: Stop
Flowchart

Pseudo
code
BEGIN
READ m
INITIALIZE g=9.81
CALCULATE W= m* g
PRINT W
END
1e. WEIGHT OF A STEEL BAR
Description
The formula used to calculate the unit weight of steel bars is D²L/162. Where, D = Dia. Of
steelbars, 162 is a constant value.
Steel Weight formula W =
D2L/162W- Weight of steel bar
D – Diameter of steel bars in MML
– Length of bars in meter
Algorithm
Step 1: Start
Step 2: Read the values D, L
Step 3: Calculate W= (D
*D*L)/162 Step 4: Print W
Step 5: Stop
Flowchart

Pseudo
code
BEGIN
READ D, L
CALCULATE W=
(D*D*L)/162 PRINT W
END
1f. COMPUTE ELECTRICAL CURRENT IN THREE PHASE AC CIRCUIT
Description
I = P / (3 × pf × V)
Where P is the power, pf is the power factor, V is the voltage and, I is the current

Algorithm
Step 1: Start
Step 2: Read the values P, pf and V
Step 3: Calculate
I=P/(sqrt(3)*pf*V) Step 4: Print I
Step 5: Stop

Flowchart

Pseudo code
BEGIN
READ P, pf, V
CALCULATE I= P / (sqrt(3)*pf
*V) PRINT I
END

Result:
To Identification and solving of simple real life or scientific or technical problems, and
developing flow charts are demonstrated successfully.
Ex. No: 2 Date:

Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).

2a. Exchange the values of two variables

Aim
To write a python program to exchange the values of two variables.

Algorithm
step 1:Declared a temporary variable a and b
step 2:Assign the value of a and b,
step 3:Assign the value of a to b, and b to a
step 4: we don’t even need to perform arithmetic operations. We can use:
a,b = b,a
step 5:to print the result

Program

USING TUPLE

x=5
y=10
x,y=y,x
print('x=',x)
print('y=',y)

USING TEMP VARIABLE

x=5
y=10
TEMP = x
x=y
y = TEMP
print('x=',x)
print('y=',y)
OUTPUT:

1. x= 10
y= 5

2. x= 10
y= 5
2b. Circulate the values of n variables

Aim
To write a python program to circulate the values of n variables.

Algorithm

Step1: Circulate the values of n variables.


Step2: Get the input from the user
Step 3: To create the empty list then declare the conditional statements using for loop
Step 4: Using append operation to add the element in the list and the values are rotate by using this append
operation
Step 5: Stop the program

Program:

no_of_terms = int (input ("Enter number of values: "))


list1= [5,10,15,20,25]
for val in range(0,no_of_terms,1):
ele= int(input("Enter integer: "))
list1. append(ele)
print("Circulating the elements of
list =", list1)
for val in range(0,no_of_terms,1):
ele = list1. pop(0)
list1. append(ele)
print(list1)

OUTPUT:

Enter number of values: 2


Enter integer: 8
Circulating the elements of list = [5, 10, 15, 20, 25, 8]
Enter integer: 9
Circulating the elements of list = [5, 10, 15, 20, 25, 8, 9]
[10, 15, 20, 25, 8, 9, 5]
[15, 20, 25, 8, 9, 5, 10]
2c. Distance between two points

Aim
To write a python program to calculate distance between two points.
Algorithm
Step 1: Start the program
Step 2: Read the
x, y coordinate
values fro point
1 and point 2
Step 3: Calculate
the distance
using the
formula sqrt(dx2
+dy2) Step 4:
Print the distance
Step 5: Stop the program

Program

x1=float (input(‘Enter x1=’))


y1=float (input(‘Enter y1=’))
x2=float (input(‘Enter x2=’))
y2=float (input(‘Enter y2=’))
d=((x2-x1)**2 + (y2-y1)**2)**0.5
print(“Distance = % f “ % (d))

OUTPUT

Enter x1=.8
Enter y1=8.9
Enter x2=7.9
Enter y2=0.7
Distance = 10.846658

Result
Thus the above Python programming using simple statements and expressions has been
executed and verified output successfully.
Ex. No: 3 Date:

Scientific problems using Conditionals and Iterative loops. (Number Series, Number
Patterns, Pyramid Pattern)
3a. Number Series

Aim
To write a python program to display number series using conditionals and iterative loops.
Algorithm

Step 1: Start the program


Step 2: Read number
Step 3: Using range function to print the values from 1 to
n Step 4: Stop the Program

Program

def pypart (n):


if n == 0:
return
else :
pypart (n-1)
print('1' *n)

n=5
pypart(n)

Output

1
11
111
1111
11111
3b. Number Patterns

To write a python program to display number patterns using conditionals and iterative loops.
Algorithm
Step 1: Start the program
Step 2: Declare the value for rows.
Step 3: Let i and j be an integer number
Step 4: Repeat step 5 to 8 until all value parsed
Step 5: Set i in outer loop using range function, i = rows+1 and rows will be initialized to
Step 6: Set j in inner loop using range function and i integer will be initialized to j
Step 7: Print i until the condition becomes false in inner loop.
Step 8: Print new line until the condition becomes false in outer loop.
Step 9: Stop the program.

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

12

123

1234

12345
3c.Pyramid Pattern

Aim
To write a python program to display pyramid patterns using conditionals and iterative loops.

Algorithm
Step 1: Start the program
Step 2: Read number of
rows
Step 3: Using range function and inner loops to find the values
Step 4: Using while loop to print the pattern values
Step 4: Stop the program

Program

rows = int(input("Enter number of rows: "))

k=0

for i in range(1, rows+1):


for space in range(1, (rows-i)+1):
print(end=" ")

while k!=((2*i)-1):
print("* ", end="")
k += 1

k=0
print()

Output

*
***
*****
*******
*********

Result

Thus the above Python program for various scientific problems like Number Series, Number Patterns, and
Pyramid Pattern executed and verified successfully.
Ex. No: 4 Date:
Implementing real-time/technical applications using Lists, Tuples. (Items present in a
library/Components of a car/ Materials required for construction of a building –operationsof list &
tuples)

4a) Basic list operations in items present in a library/Components of a car/


Materials required for construction of a building

Aim
To create a python program to perform for basic list operations in items present in a
library/Components of a car/ Materials required for construction of a building

Algorithm

STEP 1: Start the program


STEP 2: Create the variable inside that variable assigned the list of elements based on the library using List and Tuples
STEP 3:Using array index to print the items using list and tuple
STEP 4:To print the result using output statement
STEP 5: Stop the program

Program
library=["books","author","barcodenumber","price"]
library[0]="ramayanam"
print(library[0])
library[1]="valmiki"
library[2]=123987
library[3]=234
print(library)
tup1=(12134,250000)
tup2=('books','totalprice')
tup3=tup1+tup2;
print(tup3)

Output

ramayanam
['ramayanam', 'valmiki', 123987, 234]
(12134, 250000, 'books', 'totalprice')
4b) Basic tuple operations in items present in a library/Components of a car/ Materials
required for construction of a building

Aim

To create a python program to perform for basic tuple operations in items present in a
library/Components of a car/ Materials required for construction of a building

Algorithm

STEP 1: Start the program


STEP 2: Create the variable inside that variable assigned the list of elements based on the car using List
and tuple
STEP 3:Using array index to print the items using list and tuple STEP 4:To print the result using output
statement
STEP 5: Stop the program

Program

cars = ["Nixen", "Mercedes Benz", "Ferrari", "Maserati", "Jeep", "Maruti Suzuki"]


new_list = []

for i in cars:
if "M" in i:
new_list.append(i)
print(new_list)

cars = ("Ferrari", "BMW", "Audi", "Jaguar")


print(cars)
print(cars[0])
print(cars[1])
print(cars[2])
print(cars[3])
print(cars[3])

Output

['Mercedes Benz', 'Maserati', 'Maruti Suzuki']


('Ferrari', 'BMW', 'Audi', 'Jaguar')
Ferrari
BMW
Audi
Jaguar
Jaguar

Result
Thus the above Python program for real time/technical applications using lists and tuples are executed and
verified successfully.
Ex. No: 5 Date:
Implementing real-time/technical applications using Sets, Dictionaries. (Language,
components of an automobile, Elements of a civil structure, etc.- operations of Sets &
Dictionaries)
5a) Basic Set
Operations Aim
To create a python program to perform basic sets operations for Language, components ofan
automobile, Elements of a civil structure.
Algorithm
Step 1: Start the program
Step 2: Define sets for language, automobile, civilelements with elements
Step 3: Perform various set operations
Step 4: Stop the program
Program

Materials =["CEMENTBAGS","BRICKS","SAND","STEEL BARS","PAINT"]


Materials. append("TILES")
Materials. insert(3,"AGGREGATES")
Materials. remove("SAND")
Materials[5]="ELECTRICAL"
print(Materials)
Materials =("CEMENTBAGS","BRICKS","SAND","STEEL BARS","PAINT")
print(Materials)
print("list of element is =",Materials)
print("Materials[0]:",Materials[0])
print("Materials[1:3]:",Materials[1:3])

Output

['CEMENTBAGS', 'BRICKS', 'AGGREGATES', 'STEEL BARS', 'PAINT', 'ELECTRICAL']


('CEMENTBAGS', 'BRICKS', 'SAND', 'STEEL BARS', 'PAINT')
list of element is = ('CEMENTBAGS', 'BRICKS', 'SAND', 'STEEL BARS', 'PAINT')
Materials[0]: CEMENTBAGS
Materials[1:3]: ('BRICKS', 'SAND')
5b) Basic Dictionary Operations
Aim
To create a python program to perform basic dictionary operations for Language,
components of an automobile, Elements of a civil structure.
Algorithm
Step 1: Start the program
Step 2: Define dictionary for language, automobile, civilelements with elements
Step 3: Perform various dictionary operations
Step 4: Stop the program
Program

Dict = {}
print("Empty Dictionary: ")
print(Dict)Dict[0] = 'BRICKS'
Dict[2] = 'CEMENT'
Dict[3] = 'BLUE PRINT'
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict[2] = 'STEEL'
print("\nUpdated key value: ")
print(Dict)
Dict[5] = {'Nested': {'1': 'LIME', '2': 'SAND'}}
print("\nAdding a Nested Key: ")
print(Dict)

Output

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE PRINT'}

Dictionary after adding 3 elements:


{0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE PRINT', 'Value_set': (2, 3, 4)}

Updated key value:


{0: 'BRICKS', 2: 'STEEL', 3: 'BLUE PRINT', 'Value_set': (2, 3, 4)}

Adding a Nested Key:


{0: 'BRICKS', 2: 'STEEL', 3: 'BLUE PRINT', 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'LIME', '2': 'SAND'}}}
Result
Thus the above Python program to perform basic sets and dictionary operations for Language,
components of an automobile, Elements of a civil structure are executed and verified successfully.
Ex. No: 6 Date:
Implementing programs using Functions. (Factorial, largest number in a list, area of shape)

6a) Calculate Factorial Using Functions

Aim
To create a python program to calculate factorial value using functions.
Algorithm

Step 1: Start the program


Step 2:Take a number from the user and store it in a variable.
Step 3:Pass the number as an argument to a recursive factorial function.
Step 4: Define the base condition as the number to be lesser than or equal to 1 and return 1 if it is.
Step 5: Otherwise call the function recursively with the number minus 1 multiplied by the
numberitself. Step 6: Then return the result and print the factorial of the number.
Step 7: Stop the Program

Program

def

factorial(n):

if(n <= 1):

return 1

else:

return(n*factorial(n-1))

n = int(input("Enter

number:")) print("Factorial:",

factorial(n))

Output

Enter number:5
Factorial: 120
6b) Finding largest number in a list using

Functions Aim

To create a python program to finding largest number in a list of numbers using functions.

Algorithm

Step 1: Start the program


Step 2: Initialize the empty list
Step 3: Read the number of elements.
Step 4: Read the value of elements and store it in list.
Step 5: Pass the list as an argument to a max_num_in_list function.

Step 6: Initialize max = list[ 0 ]


Step 7: Compare each element in a list and print the maximum
value. Step 8: Stop the program

Program

def max_num_in_list( list ):


max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
lis = []
print(max_num_in_list([1,2,-8,0]))

Output

2
6c) Calculate area of shape using Functions

Aim
To create a python program to calculate area of shape using Functions
Algorithm
Step 1: Start the program
Step 2: Read the name of the shape
Step 3: Pass the shape as an argument to a calculate_area function.
Step 4: Using the method lower convert the shape name as
lowercase.
Step 5: Check the matching shape name and calculate the area of specific
shape. Step 6: Print the value of area.
Step 7: Stop the program
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 is:",rect_area)
elif name == "square":
s = int(input("Enter square's side length:
")) sqt_area = s * s
print(f"The area of square is:",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(f"The area of triangle is:",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 is",circ_area)

else:
print("Sorry! This shape is not available")
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)
Result
Thus the above Python program using functions are executed and verified successfully.
Ex. No: 7 Date:

Implementing programs using Strings. (Reverse, palindrome, character count, replacing


characters)
7a)Reverse the string
Aim
To create a python program to reverse the string.
Algorithm

Step 1: Start the program


Step 2: Read the string from the
user Step 3: Print the original string
Step 4: Pass the string as an argument to the reverse_string function
Step 5: Using string concatenation operation and reverse the original string and print the string

Step 6: Stop the program

Program

def reverse(string):
string="".join[reversed(string))
return string
s=input("Enter ang string:")
print("The oringinal string is:",end"")
print(s)
print("The reversed string(using reversed/is:",end="")
print(reverse(s))

Output

Enter ang string:python


The oringinal string is:python
The reversed string(using reversed/is:nohtyp
7b) Palindrome of a

string

Aim

To create a python program to check whether the given string is palindrome or not.

Algorithm

Step 1: Start the program


Step 2: Read the string
Step 3: Compare the string with reversed string
Step 4: If both are equal print the string is palindrome else print string is not a palindrome

Step 5: Stop the Program

Program

str=input(“enter string”)
str=str. Casefold()
rev.str=reversed(str)
if list (str)=list(rev_str):
print(“ It’s a palindrome”)
else:
print(“ It’s not a palindrome”)

Output

Enter string: python


It’s not palindrom
7c) Count the character of string

Aim
To create a python program to count the character of string.

Algorithm

Step 1: Start the


program Step 2: Define
a string.
Step 3: Define and initialize a variable count to 0.
Step 4: Iterate through the string till the end and for each character except spaces, increment the count
by 1.
Step 5: To avoid counting the spaces check the condition i.e. string[i]!= '
'. Step 6: Print the number of characters
Step 7: Stop the Program

Program

string = input("Enter the


string:") count = 0
for i in range(0,
len(string)): if(string[i]
!= ' '):
count = count + 1
print("Total number of characters in a string: " + str(count))

Output

Enter the string:python


Total number of characters in a string: 6
7d). Replacing the existing character in a string

Aim

To create a python program to replacing the existing character in a string.

Algorithm
Step 1: Start the
program Step 2: Read
string
Step 3: Read the replacement
character Step 4: Read the new
character
Step 5: Using the method replace to change the
character. Step 6: Print the updated string
Step 7: Stop the Program

Program

str=input(“Enter a string”)
old str = input(“Enter the old character to be replace:”)
restr=input(“Entrerbthe character”)
result=str. replace(old str,restr)
print(result)

Output

Enter a string computer


Enter the old character to be replace:uter
Entrerbthe charactercomputer
Compcomputer

Result
Thus the python program to perform basic string operations are executed and verified successfully.

Python program to perform basic string operations are executed and verified successfully.
Ex. No: 8 Date:
Implementing programs using written modules and Python Standard Libraries (pandas,numpy,matplotlib,scipy)

Aim
Pandas is an open source Python package that provides numerous tools for data analysis. The package
comes with several data structures that can be used for many different data manipulation tasks.

Algorithm

Step 1: Start the program


Step 2: Import the module pandas

Step 3: Define dictionaries and lists


Step 4: Using pandas module perform various data
manipulations Step 5: Create data frame and print the details
Step 6: Create series and display the
values Step 7: Stop the program

Program
In command prompt install this package: pip install pandas

import pandas as pd
df = pd.DataFrame(
{
"Name": [ "Braund, Mr. Owen Harris",
"Allen, Mr. William Henry",
"Bonnell, Miss. Elizabeth",],
"Age": [22, 35, 58], "Sex": ["male", "male", "female"],
}
)
print(df)
print(df[“Age”])
ages = pd.Series([22, 35, 58], name="Age”)
print(ages)
df[“Age”].max()
print(ages.max())
print(df.describe())

Output

Name Age Sex


0 Braund, Mr. Owen Harris 22 male
1 Allen, Mr. William Henry 35 male
2 Bonnell, Miss. Elizabeth 58 female
0 22
1 35
2 58
Name: Age, dtype: int64
0 22
1 35
2 58
Name: Age, dtype: int64
58
Age
count 3.000000
mean 38.333333
std 18.230012
min 22.000000
25% 28.500000
50% 35.000000
75% 46.500000
max 58.0000
8b) i. Implementing Python programs in array operation using numpy module.

Aim
To create a python program for basic operations using numpy.
Description

NumPy is a Python library used for working with arrays. NumPy stands for NumericalPython.
NumPy provide an array object that is up to 50x faster than traditional Python lists.

Algorithm

Step 1: Start the program


Step 2: Import the module
numpy Step 3: Define the array
elements
Step 4: Print the maximum element, minimum element, sum of array elements, cumulative elementin
row using numpy module
Step 5: Stop the program

Program

import numpy as np
arr = np.array([[1, 5, 6],
[4, 7, 2],
[3, 1, 9]])
# maximum element of array
print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:", arr.max(axis =
1))# minimum element of array
print ("Column-wise minimum elements:", arr.min(axis = 0))

# sum of array elements


print ("Sum of all array elements:", arr.sum())

# cumulative sum along each row


print ("Cumulative sum along each row:\n", arr.cumsum(axis = 1))
Output
8b ii. Matrix Operations using numpy module

Aim
To create a python program for basic matrix operations using numpy module.

Algorithm
Step 1: Start the program
Step 2: Initialize the two different matrixs
Step 3: Using numpy module calculate the basic matrix operations and print the results
Step 4: Stop the program

Program

import numpy
# Two matrices are initialized by valuex
= numpy.array([[1, 2], [4, 5]])
y = numpy.array([[7, 8], [9, 10]])
print("X:",x)
print("Y:",y)
# add()is used to add matrices print
("Addition of two matrices: ")print
(numpy.add(x,y))
# subtract()is used to subtract matrices
print ("Subtraction of two matrices : ")
print (numpy.subtract(x,y))
# divide()is used to divide
matrices print ("Matrix Division :
")
print (numpy.divide(x,y))
print ("Multiplication of two matrices:
") print (numpy.multiply(x,y))
print ("The product of two matrices :
") print (numpy.dot(x,y))
print ("square root is :
") print (numpy.sqrt(x))
print ("The summation of elements :
") print (numpy.sum(y))
print ("The column wise summation : ")
print (numpy.sum(y,axis=0))
print ("The row wise summation:
") print (numpy.sum(y,axis=1))
# using "T" to transpose the matrix
print ("Matrix transposition : ")
print (x.T)
8c). Implementing Python programs using Matplotlib module
Aim
To create a python program to plotting graphs using matplotlib module.
Description
Matplotlib.pyplot is a plotting library used for 2D graphics in python programming language. It
can be used in python scripts, shell, web application servers and other graphical user interface toolkits.
Matploitlib is a Python Library used for plotting, this python library provides and objected-oriented APIs
for integrating plots into applications.
Algorithm
Step 1: Start the program
Step 2: Import the matplotlib module
Step 3: Define x axis and y axis values in list x and y
Step 4: Using plt.title, plt.xlabel and plt.ylabel method to display the title of the graph, naming thex axis
and y axis.
Step 5: Use the method plt.plot() method to plot the points, plt.bar() to bar graph
Step 6: Display the graph using the methos plt.show()
Step 7: Stop the program
Program
import matplotlib.pyplot as
plt from matplotlib import
style style.use('ggplot')
x = ["PSPP", "Chemistry", "English", "Maths", "Physics"]y
= [85,70,68,80,75]
plt.title('Student Mark
Analysis') plt.xlabel('Subject
Name') plt.ylabel('Marks')
plt.plot(x, y)
plt.yticks(list(range(0,100,10)))plt.show(
) plt.title('Student Mark Analysis')
plt.xlabel('Subject Name')
plt.ylabel('Marks')
plt.bar(x,y)
plt.show()
8d). Implementing Python programs using scipy module
Aim
To create a python program to perform various operation using scipy module.
Description
SciPy in Python is an open-source library used for solving mathematical, scientific, engineering,
and technical problems. It allows users to manipulate the data and visualize the data using a wide range of
high-level Python commands.
Algorithm
Step 1: Start the program
Step 2: Import necessary modules
Step 3: Perform simple mathematical operations using scipy module and print the results.
Step 4: Stop the program
Program

import numpy as np
from scipy import constants, ndimage,
miscfrom scipy.special import cbrt
from matplotlib import pyplot as plt
print(constants.pi)
print(constants.kilo)
print(constants.deci)
print(constants.minute)
print(constants.hour)
from scipy.sparse import csr_matrix arr =
np.array([0, 0, 0, 0, 0, 1, 1, 0, 2])
print(csr_matrix(arr))
#Find cubic root
a=int(input("Enter the value:
"))cb
= cbrt(a)
print("Cubic root of",a,"is",cb)
#get face image of panda from misc
package panda = misc.face()
#plot or show image of
face plt.imshow( panda )
plt.show()
#rotatation function of scipy for image – image rotated 135 degree
panda_rotate = ndimage.rotate(panda, 135)
plt.imshow(panda_rotate) plt.show()
Result
Thus the above Python program using modules and standard libraries are executed and verified successfully.
Ex. No: 9 Date:

Implementing real-time/technical applications using file handling. (copy from one file to another,
word count, longest word)

9a) Implementing Python programs for copy from one file to another

Aim
To create a python program for copy the content from one file to another file.
Algorithm

Step 1: Start the program


Step 2: Read the source file name in read mode
Step 3: Read the destination file name in write mode
Step 4: Using for loop read the every line form the source file and write the content in destinationfile
using write comment.
Step 5: Stop the program

Program

file1= str(input("Enter the file name:"))

file2= str(input("Enter the file name:"))

with open(file1,"rt") as file:

with open(file2,"w") as outfile:

for line in file:

outfile.write(line)

print("File

Copied...")

Output:

Enter the file name:photos


Enter the file name: album
FILE COPIED…
9b) Implementing Python programs for count number of words in a

string Aim

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

Algorithm

Step 1: Start the program


Step 2: Read the file
name
Step 3: Calculate the number of words using the built in function read() , split()Step 4:
Print the word count
Step 5: Stop the program

Program

filename= str(input("Enter the file name with extension:"))file =


open(filename,"rt")
data = file.read()
words = data.split()
print('Number of words in text file :', len(words))

output:
Enter the file name with extension:hello world
Number of words in text file :11
9c) Implementing Python programs for find the longest word in a file
Aim
To create a python program for find the longest word in a file.
Algorithm
Step 1: Start the program
Step 2: Read the file name
Step 3: Pass the filename as argument of function
longest_word Step 4: Open the file in read mode
Step 5: Using the method split(), len() and max() to find and return the longest word
Step 6: Print the longest word.
Step 7: 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]

file=str(input("Enter the File name:"))


print("Longest word in this file is:",longest_word(file))

OUTPUT
Enter the file name : photos
Longest word in this file is : artificial
Result
Thus the above Python program using file handling operations are executed and verified successfully.
Ex. No: 10 Date:
Implementing real-time/technical applications using Exception handling. (divide by zero
error, voter’s age validity, student mark range validation)

10a) Implementing Python programs for handling exception divide by zero error
Aim
To create a python program for handling exception divide by zero error

Algorithm

Step 1: Start the program


Step 2: Read the values of num1 and num2
Step 3: If the denominator is 0, throw divide by zero exception.

Step 4: If no exception is there, return the


result. Step 5: Stop the program

Program

try:
num1 = int(input("Enter First Number:"))
num2 = int(input("Enter Second Number:"))
result = num1/num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)

Output

Enter First Number:10


Enter Second Number:0
division by zero
10b) Implementing Python programs for handling exception voters age validity

Aim
To write a python program for handling exception on voters age validity.

Algorithm

Step 1: Start the


program Step 2: Read
the age
Step 3: If age is less than 18 then through the value error. It prints Not eligible to vote
Step 4: If no exception then print “ Eligible to vote”
Step 5: Stop the program

Program

while True:
try:
age=int(input("Please enter your age"))
except ValueError:
print("Sorry, I didnt understand that")
continue
if(age<0):
print("Sorry, your reponse must not be negtaive")
continue
else:
break
if(age>=18):
print("You are eligible to vote")
else:
print("You are not eligible to vote")

Output

Please enter your age 12


You are not eligible to vote
10c) Implementing Python programs for handling exception student mark range
validation Aim
To create a python program for handling exception on student mark range validation.
Algorithm
Step 1: Start the program
Step 2: Read marks and calculate the average
Step 3: If average is 50 then raise the value error and print “Grade F, The result is fail”

Step 4: If no exception then check the range and print the Grade
Step 5: Stop the program

Program

while True:
studentmark=int(input("Enter the student marks"))
if(studentmark<0 or studentmark>100):
print("The student mark value is out of range, try again")
else:
print("The student mark entered is valid")
break

Output

Enter the student marks102


The student mark value is out of range, try again
Enter the student marks80
The student mark entered is valid

Result
Thus the above Python program using exception handling are executed and verified successfully.
Ex.No : 11 Date:

Exploring Pygame tool.


11. a. Getting Started with PyGame

Aim
To create a python program for getting started with pygame.

Algorithm
Step 1: Start the program
Step 2: Import the pygame module
Step 3: Initialize Pygame using pygame.init () method.
Step 4: Set the name for the window using the method pygame.display.set_caption()

Step 5: Create the game window using the method pygame.display.set_mode ()

Step 6: Control the window using loop


Step 7: Quit the pygame using the method pygame.quit()
Step 8: Stop the program
Program

#importing
libraries import
pygame
# initializing the
pygame pygame.init()
#Setting name of the window
pygame.display.set_caption ("pygame
window")
# drawing the surface
surface=
pygame.display.set_mode((400,300)) done =
False
#initializing the
color color =
(255,0,0)
#Loop to control our window
while not done:
for event in pygame.event.get():
if event.type ==
pygame.QUIT: done =
True
pygame.display.flip()
# drawing the circle
pygame.draw.circle(surface, color, (150,150), 30)
pygame.display.flip()

OUTPUT:
11. b. Image loading using Pygame

Aim
To create a python program for image loading using pygame.

Algorithm
Step 1: Start the program
Step 2: Import the pygame module
Step 3: Initialize Pygame using pygame.init () method.
Step 4: Create the game window using the method pygame.display.set_mode ()
Step 5: Control the window using loop
Step 6: Load the necessary images using the method pygame.image.load()
Step 7: Quit the pygame using the method pygame.quit()
Step 8: Stop the program

Program

import
pygame
pygame.init()
pygame.display.set_caption ("pygame window")
surface= pygame.display.set_mode((500,600)) done
= False
clock =
pygame.time.Clock() while
not done:
for event in pygame.event.get():
if event.type ==
pygame.QUIT: done =
True
surface.fill((255, 255, 255))
image =
pygame.image.load(r"rose.jpg")
surface.blit(image,(0, 0))
pygame.display.flip()
clock.tick(60
) pygame.quit()
OUTPUT:
11 c. Font Style and size in
Pygame Aim
To create a python program for changing font and style using pygame.
Algorithm
Step 1: Start the program
Step 2: Import the pygame module
Step 3: Initialize Pygame using pygame.init() method.
Step 4: Create the game window using the method pygame.display.set_mode ()

Step 5: Using the method pygame.font.SysFont( ) to set the font


Step 6: Control the window using loop
Step 7: Quit the pygame using the method pygame.quit()
Step 8: Stop the program
Program

import
pygame
pygame.init()
window =
pygame.display.set_mode((800,500)) clock =
pygame.time.Clock()
done = False
font = pygame.font.SysFont(None,50)
text = font.render("Python Programming Lab", True, (255, 0,
0))while not done:
for event in pygame.event.get(): if
event.type == pygame.QUIT:
done = True
window.fill((255, 255, 255))
window.blit(text,
[text.get_width()//2,text.get_height()//2])
pygame.display.flip()
clock.tick(60
) pygame.quit()
OUTPUT:
Result
Thus the above Python program using exception handling are executed and verified successfully.
Ex. No: 12 Date:
Developing a game activity using Pygame like bouncing ball, car race etc.

12.a) Simulate Bouncing Ball Using Pygame


Aim

To write a Python program to bouncing ball in Pygame.

Algorithm

Step 1: Start the program


Step 2: Import the required packages

Step 3: Define the required variables


Step 4: Create the game window using display.set_mode() function to display the bouncingballs in
that space
Step 5: Change the title using the functions pygame.display‘ and ‘set_caption‘
Step 6: Create the game loop for bouncing the ball
Step 7: Stop the programe

Program

import pygame
pygame.init() window_w
= 800
window_h = 600
white = (255, 255, 255)
green = (0,255, 0)
FPS = 120
window = pygame.display.set_mode((window_w,
window_h)) pygame.display.set_caption("Bouncing Ball ")
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.circle(window,green, (pos_x, pos_y),
block_size) pygame.display.update()
clock.tick(FPS)
game_loop()
OUTPUT :
12 b. Simulate Car Race

using Pygame Aim

To write a Python program to simulate car race using Pygame.

Algorithm

Step 1: Start the program


Step 2: Import pygame, random module
Step 3: Create folder in the name of img under the img file create the –init--.py file and store
necessary images .
Step 4: Create the class car racing
Step 5: Create the necessary functions under this class
Step 6: Moving the images with the help of event
module Step 7: Set the boundaries
Step 8: Define the movement mechanisms of the
enemy Step 9: Create main program for car game
Step 10:Stop the program

Program
import random
from time import
sleep import pygame

class CarRacing: def


init (self):
pygame.init()
self.display_width = 800
self.display_height = 600
self.black = (0, 0, 0)
self.white = (255, 255, 255)
self.clock =
pygame.time.Clock()
self.gameDisplay = None
self.initialize()
def initialize(self):
self.crashed =
False
self.carImg = pygame.image.load('.\\img\\car.png')
self.car_x_coordinate = (self.display_width * 0.45)
self.car_y_coordinate = (self.display_height * 0.8)
self.car_width = 49

# enemy_car
self.enemy_car = pygame.image.load('.\\img\\enemy_car_1.png')
self.enemy_car_startx = random.randrange(310, 450)
self.enemy_car_starty = -600
self.enemy_car_speed = 5
self.enemy_car_width = 49
self.enemy_car_height = 100

# Background
self.bgImg = pygame.image.load(".\\img\\back_ground.jpg")
self.bg_x1 = (self.display_width / 2) - (360 / 2)
self.bg_x2 = (self.display_width / 2) - (360 / 2)
self.bg_y1 = 0
self.bg_y2 = -600
self.bg_speed = 3
self.count = 0

def car(self, car_x_coordinate, car_y_coordinate):


self.gameDisplay.blit(self.carImg, (car_x_coordinate,
car_y_coordinate))

def racing_window(self):
self.gameDisplay = pygame.display.set_mode((self.display_width, self.display_height))
pygame.display.set_caption('Car Dodge')
self.run_car()
def
run_car(self):
while not self.crashed:
for event in pygame.event.get(): if
event.type == pygame.QUIT:
self.crashed = True#
print(event)

if (event.type ==
pygame.KEYDOWN):if (event.key
== pygame.K_LEFT):
self.car_x_coordinate -= 50
print ("CAR X COORDINATES: %s" %
self.car_x_coordinate)if (event.key == pygame.K_RIGHT):
self.car_x_coordinate += 50
print ("CAR X COORDINATES: %s" % self.car_x_coordinate)
print ("x: {x}, y: {y}".format(x=self.car_x_coordinate, y=self.car_y_coordinate))

self.gameDisplay.fill(self.black
) self.back_ground_raod()

self.run_enemy_car(self.enemy_car_startx,
self.enemy_car_starty) self.enemy_car_starty +=
self.enemy_car_speed

if self.enemy_car_starty > self.display_height:


self.enemy_car_starty = 0 - self.enemy_car_height
self.enemy_car_startx = random.randrange(310,
450)

self.car(self.car_x_coordinate,
self.car_y_coordinate) self.highscore(self.count)
self.count += 1
if (self.count % 100 == 0):
self.enemy_car_speed += 1
self.bg_speed += 1
if self.car_y_coordinate < self.enemy_car_starty + self.enemy_car_height:
if self.car_x_coordinate > self.enemy_car_startx and self.car_x_coordinate <
self.enemy_car_startx + self.enemy_car_width or self.car_x_coordinate + self.car_width >
self.enemy_car_startx and self.car_x_coordinate + self.car_width < self.enemy_car_startx +
self.enemy_car_width:
self.crashed = True
self.display_message("Game
Over !!!")

if self.car_x_coordinate < 310 or self.car_x_coordinate >


460: self.crashed = True
self.display_message("Game Over !!!")

pygame.display.update()self.clock.tick(60

def display_message(self, msg):


font = pygame.font.SysFont("comicsansms", 72, True)text
= font.render(msg, True, (255, 255, 255))
self.gameDisplay.blit(text, (400 - text.get_width() // 2, 240 - text.get_height() // 2))
self.display_credit()
pygame.display.update()
self.clock.tick(60) sleep(1)
car_racing.initialize()
car_racing.racing_window()

def back_ground_raod(self):
self.gameDisplay.blit(self.bgImg, (self.bg_x1,
self.bg_y1))self.gameDisplay.blit(self.bgImg, (self.bg_x2,
self.bg_y2))

self.bg_y1 +=
self.bg_speed self.bg_y2
+= self.bg_speed

if self.bg_y1 >=
self.display_height: self.bg_y1 =
-600

if self.bg_y2 >=
self.display_height: self.bg_y2 =
-600
def run_enemy_car(self, thingx, thingy):
self.gameDisplay.blit(self.enemy_car, (thingx,
thingy))

def highscore(self, count):


font = pygame.font.SysFont("arial", 20)
text = font.render("Score : " + str(count), True,
self.white) self.gameDisplay.blit(text, (0, 0))

def display_credit(self):
font = pygame.font.SysFont("lucidaconsole", 14)
text = font.render("Thanks for playing!", True,
self.white) self.gameDisplay.blit(text, (600, 520))

if name == ' main ':


car_racing = CarRacing()
car_racing.racing_window(
)
OUTPUT:
12 c. Simulate Elliptical Orbits in Pygame
Aim Algorithm
To write a python program to simulate elliptical orbits in
pygame.
Step 1: Start the program
Step 2: Import pygame module
Step 3: Call pygame.init() to initiate all imported pygame module

Step 4: Define the parameters to simulate elliptical


orbits. Step 5: Display the created orbits.
Step 6: Stop the program

Program

import

pygame

import math

import sys

pygame.init()

screen = pygame.display.set_mode((600,

300)) pygame.display.set_caption("Elliptical

orbit") clock = pygame.time.Clock()

while(True):

for event in pygame.event.get(): if

event.type == pygame.QUIT:

sys.exit()

xRadius = 250

yRadius = 100

for degree in range(0,360,10):

x1 = int(math.cos(degree * 2 * math.pi / 360) * xRadius) + 300


y1 = int(math.sin(degree * 2 * math.pi / 360) * yRadius) +

150 screen.fill((0, 0, 0))

pygame.draw.circle(screen, (255, 0, 0), [300, 150], 35)

pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)

pygame.draw.circle(screen, (0, 0, 255), [x1, y1], 15)

pygame.display.flip()

clock.tick(5)
OUTPUT:

Result
Thus the above Python program using exception handling are executed and verified successfully.

You might also like