0% found this document useful (0 votes)
30 views80 pages

PSPP Lab Manual-Final

The document outlines the GE3171 - Problem Solving and Python Programming Laboratory course at CMS College of Engineering and Technology, detailing its objectives, outcomes, and a syllabus that includes various programming exercises. It emphasizes the development of problem-solving skills using Python and includes practical applications such as flowchart creation, data structure usage, and file handling. The course aims to prepare students for real-world engineering challenges through hands-on programming experience.

Uploaded by

vidhyasukumar6
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)
30 views80 pages

PSPP Lab Manual-Final

The document outlines the GE3171 - Problem Solving and Python Programming Laboratory course at CMS College of Engineering and Technology, detailing its objectives, outcomes, and a syllabus that includes various programming exercises. It emphasizes the development of problem-solving skills using Python and includes practical applications such as flowchart creation, data structure usage, and file handling. The course aims to prepare students for real-world engineering challenges through hands-on programming experience.

Uploaded by

vidhyasukumar6
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/ 80

CMS COLLEGE OF ENGINEERING AND TECHNOLOGY

Coimbatore- 641 032

GE3171 – PROBLEM SOLVING AND PYTHON PROGRAMMING


LABORATORY

I SEMESTER - R 2021

NAME

REGISTER NUMBER

BRANCH
CMS COLLEGE OF ENGINEERING AND
TECHNOLOGY

DEPARTMENT:…………………………………………………………………

This is to Certify that this...................................................................record work


done by Mr./Ms ………………………………….…………………for the
course…………….……………………..……………………………….……….
during………………………................... of Academic year20...........................is
Bonafide.

Staff In-charge H.O.D

REGISTER No…………………

The record is submitted for......................................................Semester B.E/B.Tech

practical Examination of Anna University, Chennai conducted


on………………….

Internal Examiner External Examiner


CMS COLLEGE OF ENGINEERING AND
TECHNOLOGY

VISION
A centre of excellence, capable of empowering seekers of knowledge

through holistic education.

MISSION
Create worthy citizens by providing holistic, qualitative, value based education and
makes them creative members of global society.

M1: To establish a continuous Industry Institute Interaction to make students


ready for the industrial environment.
M2: To enhance talents of the students in the field of Software and Service
industries for getting employment and to establish Industries.
M3: To create center of Excellence by establishing the Incubation Centers to meet
global research Challenges.
M4: Imparting education that encourages rapport building with other professionals
to cater the needs of the society.
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

1. Graduates will adapt to the changes emerging in science and technology.

2. Graduates will apply their knowledge and skills to the problems in engineering
and technology and contribute to the society at large.

PROGRAMME OUTCOMES (POs)

PO1 : Engineering knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.
PO2 : Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
PO3 : Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
PO4 : Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
PO5 : Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and modeling to
complex engineering activities with an understanding of the limitations.
PO6 : The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
PO7 : Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
PO8 : Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9 : Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10 : Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at la rge, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
PO11 : Project management and finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply these to one’s
own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.
PO12 : Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life- long learning in the broadest context of
technological change.
GE3171 – PROBLEM SOLVING AND PYTHON PROGRAMMING
LABORATORY

SYLLABUS

COURSE OBJECTIVES
 To understand the problem solving approaches

 To learn the basic programming constructs in Python

 To practice various computing strategies for Python-based solutions to real world problems.

 To use Python data structures - lists, tuples, dictionaries.

 To do input/output with files in Python.

SUGGESTED DOMAINS

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..,
COURSE OUTCOMES

CO1: Develop algorithmic solutions to simple computational


problems CO2: Develop and execute simple Python programs.
CO3: Implement programs in Python using conditionals and loops for solving
problems. CO4: Deploy functions to decompose a Python program.
CO5: Process compound data using Python data structures.
CO6: Utilize Python packages in developing software applications.
CMS COLLEGE OF ENGINEERING AND TECHNOLOGY
COIMBATORE-641032
INDEX

Ex. Marks
Date Experiment Name Signature
No.
Developing flow charts
a. Electricity billing,
b. Gross salary of an employee
c. Compute electrical current in three phase
1.
AC circuit.
d. Retail shop billing,

Programs using simple statement


a. exchange the values of two variables,
2. b. circulate the values of n variables
c. Distance between two points.

Programs using conditionals and iterative


statements
a. Number series
3. b. Number patterns
c. Pyramid pattern

Operation of list and tuples (items present in a


library/components of a car /materials required for
4. construction of a building)

Operations of sets &dictionaries(language


,components of an automobile ,elements of
5.
a civil structure )

Programs using functions


a. Factorial of a number
6. b. Largest number in a list
c. Area of shape

Programs using string,


a. Reversing a string,
7. b. Counting palindrome in a string
c. Counting characters in a string
d. Replacing characters in a string

Programs using modules and python standard


8. libraries (pandas , numpy . matplotlib , scipy)

Programs using file handling


a. Copy from one file to another ,
9. b. Word count,
c. Longest word

Programs using files handling.


a. Divide by zero error,
10 b. Voter’s age validity,
c. Student mark range validation

Exploring Pygame tool.


11
Developing a game activity using Pygame
12 like bouncing ball, car race etc.

Exp No : 1) a.
Flowchart for Electricity Bill Calculation

AIM:

To design a flow chart for calculating the electricity bill by getting the different range
of units from the user.

No. of unit consumed Charges/unit (RM) 1-


200 2.50
201 - 500 3.50
over 501 5.00

Algorithm :

Step 1 : Start
Step 2 : Read the unit values

Step 3 : Check 1<=unit<=200


Then calculate total_charges=unit*2.50
Step 4 : Check 201<=unit<=500
Then calculate total_charges=unit*3.50
Step 5 : Check unit>500
Then calculate total_charges=unit*5.0
Step 6 : print total_charges
Step 7 : Stop
FLOW CHART:
RESULT:

Thus the flowchart for the electricity bill by getting the different range of units from
the user has been done and the output has been verified.
Exp No : 1) b.
Flowchart for calculation of gross salary of an employee

AIM:

To draw a flowchart for calculating the gross salary of an employee

Algorithm :
Step 1: Start
Step 2: Read basic salary of an employee
Step 3: Use the formula hra = basic_salary * 0.2 and da = basic_salary *0.7.
Step 4: Calculate gross salary by using formula gross_salary = basic_salary + hra+da.
Step 5: Print gross salary.
Step 6: End

FLOW CHART
RESULT:

Thus the program for designing flowchart for calculating the gross salary of an employee
has been drawn and verified.
Exp No : 1) c.
Flowchart for calculating the current in three phase AC circuit

AIM:

To design a flow chart for calculating the current in three phase AC circuit by getting
the input voltage and power factor.
ALGORITHM :

Step 1: Start
Step 2: Read kva,voltage
Step 3: Compute current=kva/voltage
Step 4: Print current
Step 5: Stop

FLOW CHART
RESULT:
Thus the program for designing flowchart for finding current in three phase AC
circuit has been drawn and verified.
Exp No : 1) d.
Flowchart for calculating the for retail bill preparation

Aim :
To draw a flowchart for retail bill preparation.

Algorithm :
Step 1: Start
Step 2: Read item name
Step 3: Read price per unit
Step 4: Read No of Quantity
Step 5: Compute Totalcost=Quantity*price per unit
Step 6: Display total
Step 7: Read payment
Step 8: Compute paychange=payment-Totalcost
Step 9: Display the items,payment and paychange
Step 10: Stop
FLOW CHART:

RESULT:
Thus the program for designing flowchart for finding current in three phase AC circuit
has been drawn and verified
15
Ex No: 2(a) EXCHANGE THE VALUES OF TWO VARIABLES

AIM:

To write a python program to swap or exchange two values using temporary variable.

ALGORITHM:
STEP 1: Declare a variable a,b and c as integer
STEP 2: Read two number a and b
STEP 3: c=a
STEP 4: a=b
STEP 5: b = a (or) Use the logic a,b=b,a in
python STEP 6: print a and b

FLOWCHART:

17
PROGRAM:
a = 10
b = 50
# Swapping of two variables
# Using third variable
c=a
a=b
b=c
print("Value of a:", a)
print("Value of b:", b)

OUTPUT:

Value of a: 50
Value of b: 10

RESULT:

Thus the python program to exchange the two values has been done and the output has
been verified.

18
Exp n
CIRCULATE THE VALUES OF N VARIABLES

AIM:

To write a python program to circulate the values of values of ‘N’ numbers.


ALGORITHM:
STEP 1: Start the program
STEP 2: Get the number of values from the user
STEP 3: Using list get the elements from the user using append
function. STEP 4: Using the pop function remove the first element
and add the element at the end using append function.
STEP 5: Print the list for each
iteration STEP 6: Stop the program
FLOWCHART:

19
PROGRAM:
# Circulate the values of n variables
no_of_terms = int(input("Enter number of values : "))
list1 = []
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: 5


Enter integer: 23
Enter integer: 45
Enter integer: 56
Enter integer: 67
Enter integer: 78
Circulating the elements of list [23, 45, 56, 67, 78]
[45, 56, 67, 78, 23]
[56, 67, 78, 23, 45]
[67, 78, 23, 45, 56]
[78, 23, 45, 56, 67]
[23, 45, 56, 67, 78]

RESULT:

Thus the python program to circulate the values of values of ‘N’ numbers has been done
and the output has been verified.

20
Ex No: 2(c) DISTANCE BETWEEN TWO POINTS
09.12.2021
AIM:

To write a python program to find the distance between two points.


ALGORITHM:
STEP 1: Start the program
STEP 2: Get the values of x1, x2, y1 and y2.
STEP 3: Find the difference between the two points and find square of
the values using ** (For both x1,x2,y1,y2).
STEP 4: Now find the square root of the above result using
**2. STEP 5: Print the result.
STEP 6: Stop the program

FLOWCHART:

PROGRAM:

x1=int(input("Enter x1 : "))
x2=int(input("Enter x2 : "))
y1=int(input("Enter y1 : "))
y2=int(input("Enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("Distance between",(x1,x2),"and",(y1,y2),"is : ",result)

21
OUTPUT
Enter x1 : 4
Enter x2 : 6
Enter y1 : 0
Enter y2 : 6
Distance between (4, 6) and (0, 6) is: 6.324555320336759

RESULT:

Thus the python program to the distance between two points has been done and the
output has been verified.

22
Ex No: 3(a) NUMBER SERIES USING CONDITIONALS AND ITERATIVE
14.12.2021 LOOPS

AIM:

To write a python program to display number series using conditionals and iterative
loops.
ALGORITHM:
Step 1 : Start the program
Step 2 : Read the “num”
value
Step 3 : Create for loop, initialize the value and print the number
series Step 4 : If the number series equal to the “num” then stop the
program
FLOWCHART:

23
Ex No: 3(a) NUMBER SERIES USING CONDITIONALS AND ITERATIVE
PROGRAM:
for x inrange(6):
if(x ==3or x==6):
continue
print(x,end=' ')
print("\n")

SAMPLE OUTPUT:

01245

RESULT:

Thus the python program to display number series using conditionals and iterative
loops has been done and the output has been verified.

24
Ex No: 3(b) NUMBER PATTERNS USING CONDITIONALS AND
14.12.2021 ITERATIVE LOOPS

AIM:

To write a python program to display number patterns using conditionals and iterative
loops.
ALGORITHM:
Step 1 : Start the Program
Step 2 : Initialize the no of
rows
Step 3 : Create loop, In the First Loop , we iterate from i = 1 to i = rows+1
Step 4 : In the Second loop , we print numbers Starting from 1 to j, where j
ranges from rows+1.
Step 5 : After each Iteration of the first loop, we print new line according
to the if condition.
Step 6: Number pattern printed in a new pattern.
Step 7: Stop the program
FLOWCHART:

25
PROGRAM:
rows = 5
for i in range(1, rows + 1):
for j in range(1, rows + 1):
if j <= i:
print(i, end='
')
else:
print(j, end=' ')
print()

OUTPUT:
12
3
4
5
223
4
5
3334
5
44445
55555

RESULT:
Thus the python program to display number patterns using conditionals and iterative loops has
been done and the output has been verified.

26
PROGRAM:
Ex No: 3(c) PYRAMID PATTERN USING CONDITIONALS AND
14.12.2021 ITERATIVE LOOPS

AIM:

To write a python program to display pyramid patterns using conditionals and iterative
loops.
ALGORITHM:
Step 1: Start the Program
Step 2: Get the Height of the Pyramid from the User
Step 3: Create loop, In the First Loop, we iterate from i = 0 to i = rows
Step 4: In the Second loop, we print numbers Starting from 1 to j, where
j
ranges from 0 to i
Step 5: After each Iteration of the first loop, we print new line.
FLOWCHART:

27
PROGRAM:
rows = 5
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(j, end=' ')
print('')

OUTPUT:
1
1
2
1
2
3
1
2
3
4
1
2
3
4
5

RESULT:
Thus the python program to display pyramid patterns using conditionals and iterative
loops has been done and the output has been verified.

28
Ex No:4(a) ITEMS PRESENT IN A LIBRARY USING LIST, TUPLES
16.12.2021

AIM:

To write a python program Items present in a library using lists, tuples.


ALGORITHM:

STEP 1: Start

STEP 2: Read list from the user.

STEP 3: Add an element at the end of the list by using append () and print the list.

STEP 4: Insert an element by using insert() and print it.

STEP 5: Count a letter in list by using count() and print it.

STEP 6: Stop

FLOWCHART:

29
PROGRAM:
list1=['maths','english','physics']

list1.append('python')

print('Number of book in the rack: ',list1)

list1.insert(2,'social')

print('Number of book there: ',list1)

list1.count('a')

print('Number of terms in there: ',list1)

OUTPUT:

Number of book in the rack: ['maths', 'english', 'physics', 'python']

Number of book there: ['maths', 'english', 'social', 'physics', 'python']

Number of terms in there: ['maths', 'english', 'social', 'physics', 'python']

RESULT:

Thus the python program to find items present in the library has been done and the
output has been verified.

30
Ex no: 4(b)(i) TO IMPLEMENT COMPONENTS OF A CAR
16.12.2021

AIM:

To write a python program to implement components of a car using lists.

ALGORITHM:

STEP 1: Start

STEP 2: Read components of a car list from the user.

STEP 3: Add an element at the end of the list by using append() and print the list.

STEP 4: Display the number of elements using len() function.

STEP 5: Display the index for any mentioned element using index() function.

STEP 6: Stop

FLOWCHART:

31
PROGRAM
list1=['headlight','brake','clutch','accelerator','window']

list1.append('gear')

print(list1)

print(len(list1))

index = list1.index('brake')

print(index)

OUTPUT:

['headlight', 'brake', 'clutch', 'accelerator', 'window', 'gear']

RESULT:

Thus the python program to implement components of a car using list has been
done and the output has been verified.

32
Ex No: 5(a) TO IMPLEMENT COMPONENTS OF AN AUTOMOBILE
23.12.2021 USING SETS

AIM:

To write a python program for displaying components of an automobile using sets.

ALGORITHM:

STEP 1: Start

STEP 2: Read components of a car using set from the user.

STEP 3: Using the type() function we identify these elements belong to the set.

STEP 4: Using the add() function we add a new element to the set.

STEP 5: Using len() function we count how many elements present in the set.

STEP 6: Using remove function we delete a particular item in the set

FLOWCHART:

38
PROGRAM:
set1={'ENGINE','RADIATOR','SILENCER','TYRE','PISTON'}
print(set1)
print(type(set1))
set1.add('suspension')
print(set1)
print(len(set1))
set1.remove('TYRE')
print(set1)
OUTPUT:
{'ENGINE', 'RADIATOR', 'PISTON', 'TYRE', 'SILENCER'}
<class 'set'>
{'ENGINE', 'RADIATOR', 'suspension', 'PISTON', 'TYRE','SILENCER'}
6
{'ENGINE', 'RADIATOR', 'suspension', 'PISTON', 'SILENCER'}

RESULT:
Thus the python program for displaying components of an automobile using
sets has been done and the output has been verified.

39
Ex No: 5(b) ELEMENTS OF A CIVIL STRUCTURE USING
23.12.2021 DICTIONARIES

AIM:

To write a python program for displaying Elements of a civil structure using lists.

ALGORITHM:
STEP 1: Start
STEP 2: Declare elements of a civil structure using Dictionary
STEP 3: Using the keys() function display the keys present in the
Dictionary
STEP 4: Using the values() function display the values in the dictionary.
STEP 5: Using the copy() function copy the elements into another
Dictionary.
STEP 6: Using pop function we delete a particular item in the dictionary.
FLOWCHART:

40
PROGRAM:

materials = {1: "cement",

2: "steel",

3: "sand",

4: "bricks"}

print ("Keys : ", materials.keys())

print ("Values :", materials.values())

print ("copied :", materials.copy())

print (materials.pop(3),"is removed from library")

print("Created Dictionary :", materials)

OUTPUT:

Keys :dict_keys([1, 2, 3, 4])

Values :dict_values(['cement', 'steel', 'sand', 'bricks'])

copied : {1: 'cement', 2: 'steel', 3: 'sand', 4: 'bricks'}

sand is removed from library

Created Dictionary : {1: 'cement', 2: 'steel', 4: 'bricks'}

RESULT:
Thus the program for displaying Elements of a civil structure using dictionaries has
been displayed and the output has been verified.

41
Ex No: 6(a) IMPLEMENTING PROGRAMS FOR FACTORIAL
30.12.2021 USING FUNCTION
AIM:
To write python program for factorial using function.

ALGORITHM:

Step 1: Start
Step 2: Read a number n
Step 2: Initialize variables i = 1, fact = 1
Step 3: if i<= n go to step 4 otherwise go to step 7
Step 4: Calculate fact = fact * i
Step 5: Increment the i by 1 (i=i+1) and go to step 3
Step 6: Print fact
Step 7: Stop the program
FLOWCHART

44
PROGRAM:

def fact(n):
if n ==0:
return 1
else:
return n*fact(n-1)
n = int(input("Enter an interger: "))
result = fact(n)
print("Factorial of",n,"is",result)

OUTPUT:

Factorial of 5 is 120

RESULT:
Thus the program for factorial using function has been displayed and the output has
been verified.

45
Ex No: 6(b) IMPLEMENTING PROGRAMS FOR LARGEST
30.12.2021 NUMBER IN A LIST FUNCTION

AIM:

To write python program for finding largest number using function.

ALGORITHM:

Step 1:Start the program


Step 2:Using a function declare a list list1.
Step 3:Let the starting element be max element.
Step 4:Using for loop check x > max.
Step 5:Assign x to max value.
Step 6:Initialize the list and call the function.
Step 7:Largest element is displayed.
Step 8:Stop the program.

FLOWCHART:

46
PROGRAM:

def maximum(a, b, c):

if (a >= b) and (a >= c):


largest = a

elif (b >= a) and (b >= c):


largest = b
else:
largest = c

return largest

# Driven code
a = 10
b = 14
c = 12
print(maximum(a, b, c))

OUTPUT:

14

RESULT:
Thus the program for finding largest number using function has been displayed and
the output has been verified.

47
Ex No: 6(c) IMPLEMENTING PROGRAMS FOR FINDING AREA OF
01.02.2022 SHAPE USING FUNCTION

AIM:

To write python program for finding area of shape using function.

ALGORITHM:

Step 1:Start the program


Step 2:Using a function declare area for any
shape. Step 3:Get the shape name in lower case .
Step 4:Get the inputs length and breadth from the user.
Step 5:Area=length* breadth.
Step 6:now call the declared function.
Step 7:Now the area for the rectangle will be displayed.
Step 8:Stop the program.

FLOWCHART:

48
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(f"The area of rectangle is {rect_area}.")
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)

OUTPUT:

Enter the name of shape whose area you want to find: rectangle
Enter rectangle's length: 5
Enter rectangle's breadth: 4
The area of rectangle is 20.
Calculate Shape Area

RESULT:
Thus the program for finding for finding area of shape using function has been done
and the output has been verified.

49
Ex No: 7(a) IMPLEMENTING PROGRAMS FOR REVERSING USING
02.02.2022 STRINGS

AIM:

To write python program for reversing using Strings.

ALGORITHM:
Step 1:Start the program
Step 2:Define a string x
.
Step 3:Use slice operation x[::-1] .
Step 4:Get the input string from the user and call the function.
Step 5 :Display the reversed string.
Step 6:Stop the program.

FLOWCHART:

50
Ex No: 7(a) IMPLEMENTING PROGRAMS FOR REVERSING USING
PROGRAM:

def my_string(x):
return x[::-1]

reverse_string = my_string(input("Enter a sentence: "))


print(reverse_string)

OUTPUT:

Enter a sentence: Kathir college


egelloc rihtaK

RESULT:
Thus the program for finding for reversing using Strings has been done and the output
has been verified.

51
Ex No: 7(b) IMPLEMENTING PROGRAM FOR PALINDROME USING
02.02.2022 STRINGS

AIM:
To write python program for palindrome using Strings.

ALGORITHM:
Step 1: Start the program
Step 2: Get the string from the user.
Step 3: Using the if condition check given string is equal to x[::-1] .
Step 4: If true print it is palindrome
Step 5: If not true print it is not palindrome.
Step 6: Stop the program.

FLOWCHART:

52
PROGRAM:

string = input("Please enter your own string: ")

if (string == string[::-1]):

print('This is a Palindrome string')

else:

print('This is Not a palindrome String')

OUTPUT :

Please enter your own string: Madam

This is a Palindrome string

RESULT:
Thus the program for finding palindrome using Strings has been done and the output
has been verified.

53
Ex No: 7(c) IMPLEMENTING PROGRAM FOR CHARACTER COUNT
03.02.2022 STRINGS

AIM:

To write python program for character count using Strings.

ALOGORITHM:

Step 1: Start the program


Step 2: Using the len() function for the given string
Step 3: Print the length of the string
Step 4: Stop the program

FLOWCHART:

54
PROGRAM:

string = input("Enter a desired string: ")

count = len(string)

print (count)

OUTPUT:

Enter a desired string: Kathir College

14

RESULT:
Thus the program for counting the characters using Strings has been done and the
output has been verified.

55
Ex No: 7(d) IMPLEMENTING PROGRAM FOR REPLACING

03.02.2022 CHARACTERS USING STRINGS

AIM:

To write python program for replacing characters using Strings.

ALGORITHM:

Step 1: Start the program


Step 2: Using the replace () function replace the old string with the new string.
Step 3: Print the replaced string
Step 4: Stop the program

FLOWCHART:

56
PROGRAM:

string = "I am a Student"

replace = string.replace("Student","Teacher")

OUTPUT:

Given String: I am a Student


Replaced string I am a Teacher

RESULT:
Thus the program for finding for replacing characters using Strings has been done
and the output has been verified.

57
Ex No: 8(a) IMPLEMENTING PROGRAM FOR PANDAS USING
04.02.2022 WRITTEN MODULES AND PYTHON STANDARD
LIBRARIES
AIM:

To implement program for pandas using written modules and Python Standard
Libraries.
ALGORITHM:

Step 1:Start the program


Step 2: Import pandas.
Step 3:Initialize data and
index. Step 4:Print the replaced
string
Step 5:Call the function series using panda
variable Step 6: Print series
Step 7: Stop the program

58
FLOWCHART:

58
PROGRAM:

import pandas as pd

data =

[1,3,4,5,6,9,2]

s=pd.Series(data)

index=['a','b','c','d','e','f','g']

si=pd.Series(data,index)

print(si)

OUTPUT:

a 1

b 3

c 4

d 5

e 6

f 9

g 2

dtype: int64

RESULT:
Thus the program using pandas has been done and the output has been verified.
59
Ex No: 8(b) IMPLEMENTING PROGRAM FOR NUMPY USING WRITTEN

04.02.2022 MODULES AND PYTHON STANDARD LIBRARIES

AIM:
To implement program for numpy using written modules and Python Standard Libraries.

ALGORITHM:
Step 1:Start the program
Step 2:import Numpy
Step 3:Initialize array([[1,2,3],[4,2,5]]).
Step 4:print type(arr), arr.ndim, arr.shape, arr.size, arr.dtype
Step 5: Stop the program
FLOWCHART:

60
PROGRAM:
import numpy as np

arr=np.array([[1,2,3],[4,2,5]])

print("array is of type",type(arr))

print("no of

dimensions",arr.ndim)

print("Shape of array",arr.shape)

print("Size of array",arr.size)
print("Array stores elements of type",arr.dtype)

OUTPUT:
array is of type <class

'numpy.ndarray'> no of dimensions 2

Shape of array (2, 3)

Size of array 6

Array stores elements of type int32

RESULT:

Thus the program using numpy has been done and the output has been verified.
Ex No: 8(c) IMPLEMENTING PROGRAM FOR MATPLOTLIB USING
05.02.2022 WRITTEN MODULES AND PYTHON STANDARD LIBRARIES

AIM:
To implement program for matplotlib using written modules and Python Standard
Libraries.

ALGORITHM:

Step 1:Start the program


Step 2: import matplotlib.pyplot
Step 3:Initialize x=[1,2,3]
y=[2,4,1]
Step 4: i) Call the function plt.xlabel('x-axis')
ii) Call the function plt.ylabel('y-axis')
iii) Call the function plt.title('my first graph')
iv) Call the function plt.show()
Step 5: Line will be drawn in the graph.
Step 6: Stop the program
FLOWCHART:

62
PROGRAM:

import matplotlib.pyplot as

plt x=[1,2,3]

y=[2,4,1]

plt.plot(x,y)

plt.xlabel('x-axis')

plt.ylabel('y-axis')

plt.title('my first

graph') plt.show()

OUTPUT:

RESULT:
Thus the program using matplotlib has been done and the output has been verified.

63
Ex No: 8(d) IMPLEMENTING PROGRAM FOR SCIPY USING WRITTEN
05.02.2022 MODULES AND PYTHON STANDARD LIBRARIES

AIM:
To implement program for scipy using written modules and Python Standard Libraries.
ALGORITHM:
Step 1:Start the program
Step 2: import exp10
Step 3:Initialize exp10([1,10])
Step 4:Print the exponent value.
Step 5: Stop the program
FLOWCHART:

64
PROGRAM:

from scipy .special import

exp10 exp=exp10([1,10])

print(exp)

OUTPUT:

[1.e+01 1.e+10]

RESULT:
Thus the program using scipy has been done and the output has been verified.

65
Ex No: 9(a) TO IMPLEMENT PYTHON PROGRAM TO COPY FROM ONE
08.02.2022 FILE TO ANOTHER USING FILE HANDLING

AIM:

To implement python program to copy from one file to another using File handling.

ALGORITHM:
Step 1: Start the program
Step 2: Create first file and second file using notepad.
Step 3: Using the open function open first file in read mode
Step 4: Using the open function open second file in write
mode.
Step 5: Using for loop copy the content from first file to second file using append
Function
Step 6: Stop the program
FLOWCHART:

66
PROGRAM:
# open both files with open('first.txt','r') as firstfile, open('second.txt','a') as secondfile:
# read content from first file
for line in firstfile:
# append content to second file
secondfile.write(line)

OUTPUT:

RESULT:
Thus the program to copy from one file to another using File handling has been done
and the output has been verified.

67
Ex No: 9(b) TO IMPLEMENT PYTHON PROGRAM FOR WORD
08.02.2022 COUNT USING FILE HANDLING

AIM:
To implement python program for word count using File handling.

ALGORITHM:

Step 1:Start the program


Step 2:Initialize no of words to 0.
Step 3:Using the open function open file.txt in read mode
Step 4: Using the read() function read contents from the file.
Step 5: Using the split() function read contents from the file till the separator.
Step 6: Using the length() function count the no of words and print it.
Step 6: Stop the program
FLOWCHART:

68
PROGRAM:
number_of_words = 0
with open(r'second.txt','r') as file:
data = file.read()
lines = data.split()
number_of_words += len(lines)
print('Number of words: ', number_of_words)

OUTPUT:

Number of words: 2

RESULT:
Thus the program for word count using File handling has been done and the output has
been verified.

69
Ex No: 9(c) TO IMPLEMENT PYTHON PROGRAM FOR LONGEST
08.02.2022 WORD USING FILE HANDLING

AIM:
To implement python program for longest word using File handling.

ALGORITHM:

Step 1: Start the program


Step 2: Initialize a
function.
Step 3: Using the open function open file.txt in read mode
Step 4: Using the read() function read contents from the file.
Step 5: Using the split() function read contents from the file till the separator.
Step 6: Using the length() function and max () function read the contents of the
File is equal to the maximum length.
Step 7:Print the longest
word Step 8: Stop the
program

70
Ex No: 9(c) TO IMPLEMENT PYTHON PROGRAM FOR LONGEST
FLOWCHART:

70
PROGRAM:

deflongest_word(filename):

withopen(filename,'r')asinfile:

words =infile.read().split()

max_len=len(max(words, key=len))

return[word for word in words iflen(word)==max_len]

print(‘Longest word in this file: ’,longest_word('second.txt'))

OUTPUT:

Longest word in this file: ['Python']

RESULT:
Thus the program for longest word using File handling has been done and the output

has been verified.

71
Ex No: 10(a) TO IMPLEMENT DIVIDE BY ZERO ERROR USING
14.02.2022 EXCEPTION HANDLING

AIM:
To implement python program for division by zero error using Exception handling.

ALGORITHM:
Step 1:Start the program
Step 2: Get the n,d and c values from the user.
Step 3:Using the try clause calculate q=n/(d-c)
Step 4: print the q value
Step 5: Using the except clause display zero division error and print
it. Step 6: Stop the program
FLOWCHART:

72
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)
exceptZeroDivisionError:
print("Division by Zero!")

OUTPUT:
Enter the value of n:5

Enter the value of d:4

Enter the value of c:4

Division by Zero!

RESULT:
Thus the program for division by zero error using Exception handling has been done
and the output has been verified.

73
Ex No: 11 TO EXPLORE PYGAME TOOL
15.02.2022

AIM:

To explore Pygame tool.

Python Pygame (Game Development Library)

Python is the most popular programming language or nothing wrong to say that it is
the next-generation programming language. In every emerging field in computer
science, Python makes its presence actively. Python has vast libraries for various
fields such as Machine Learning (Numpy, Pandas, Matplotlib), Artificial
intelligence (Pytorch, TensorFlow), and Game development (Pygame,Pyglet).

Pygame
o Pygame is a cross-platform set of Python modules which is used to create video games.
o It consists of computer graphics and sound libraries designed to be used with the
Python programming language.
o Pygame was officially written by Pete Shinners to replace PySDL.
o Pygame is suitable to create client-side applications that can be potentially wrapped in
a standalone executable.

Prerequisites for Pygame:

Before learning about pygame, we need to understand what kind of game we want to develop.

o To learn pygame, it is required to have basic knowledge of Python.

Install pygame in Windows

Before installing Pygame, Python should be installed in the system, and it is good to have
3.6.1 or above version because it is much friendlier to beginners, and additionally runs faster.
There are mainly two ways to install Pygame, which are given below:

1. Installing through pip: The good way to install Pygame is with the pip tool (which is
what python uses to install packages). The command is the following:

py -m pip install -U pygame --user

2. Installing through an IDE: The second way is to install it through an IDE and here we
are using Pycharm IDE. Installation of pygame in the pycharm is straightforward. We can
install it by running the above command in the terminal or use the following steps:

o Open the File tab and click on the Settings option.


79
o Select the Project Interpreter and click on the + icon.
o It will display the search box. Search the pygame and click on the install
package button.

o check whether the pygame is properly installed or not, in the IDLE interpreter, type the
following command and press Enter:

import pygame

If the command runs successfully without throwing any errors, it means we have successfully
installed Pygame and found the correct version of IDLE to use for pygame programming.

Simple program in pygame(To open Hello world screen)

import time

import pygame

pygame.init()

screen=pygame.display.set_mode([640,480])

pygame.display.set_caption('Hello world')

screen.fill([0,0,0])

pygame.display.flip()

time.sleep(5)

Let's understand the basic syntax of the above program line by line:
80
import pygame - This provides access to the pygame framework and imports all functions
of pygame.

pygame.init() - This is used to initialize all the required module of the pygame.

pygame.display.set_mode((width, height)) - This is used to display a window of the desired


size. The return value is a Surface object which is the object where we will perform graphical
operations.

pygame.event.get()- This is used to empty the event queue. If we do not call this, the
window messages will start to pile up and, the game will become unresponsive in the opinion
of the operating system.

pygame.QUIT - This is used to terminate the event when we click on the close button at the
corner of the window.

pygame.display.flip() - Pygame is double-buffered, so this shifts the buffers. It is essential to


call this function in order to make any updates that you make on the game screen to make
visible.

OUTPUT:
pygame 2.1.2 (SDL 2.0.18, Python 3.10.2)

Hello from the pygame community. https://www.pygame.org/contribute.html

RESULT:
Thus the program to explore pygame has been done and the output has been verified.

81
Ex No: 12(a) PYGAME FOR BOUNCING A BALL
23.02.2022
AIM:
To exploring Pygame tool for bouncing a ball.

PROGRAM:

import os

os.environ['Pygame_hide']="hide"

import sys, pygame

from pygame.locals import *

pygame.init()

speed = [10,10]

color = (255,250,250)

width = 550

height = 300

screen = pygame.display.set_mode((width, height))

pygame.display.set_caption("Pygame bouncing ball")

ball = pygame.image.load(r"C:\Users\exam\Documents\Fenix\ball2.jpg")

rect_boundary = ball.get_rect()

while True:

for event in pygame.event.get():

rect_boundary = rect_boundary.move(speed)

if rect_boundary.left<0 or rect_boundary.right>width:

speed[0]=-speed[0]

if rect_boundary.top<0 or rect_boundary.bottom>height:

speed[1] = -speed[1]

screen.fill(color)
82
screen.blit(ball,rect_boundary)

pygame.display.flip()

if event.type==QUIT:

pygame.quit()

sys.exit()

OUTPUT:

pygame 2.1.2 (SDL 2.0.18, Python 3.10.2)

Hello from the pygame community. https://www.pygame.org/contribute.html

RESULT:

Thus the program to explore pygame for bouncing a ball has been done and the
output has been verified.

83

You might also like