[go: up one dir, main page]

0% found this document useful (0 votes)
66 views33 pages

PSP Lab Manual Last Edit

Python

Uploaded by

sathibhalaji
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)
66 views33 pages

PSP Lab Manual Last Edit

Python

Uploaded by

sathibhalaji
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/ 33

EXCEL ENGINEERING COLLEGE (AUTONOMOUS)

KOMARAPALAYAM-637 303

Department of Computer Science and Engineering


I Semester

23CS103 - Problem Solving Using Python Programming Laboratory

LABORATORY MANUAL
ENGINEERING COLLEGE (AUTONOMOUS)

KOMARAPALAYAM-637 303

DEPARTMENT OF Computer Science and Engineering


LABORATORY RECORD NOTEBOOK

This is to certify that bonafide record of work done by

Register No. _1st semester of COMPUTER SCIENCE AND Engineering

branch during the year 2024-2025 in the

LABORATORY.

Staff In-charge Head of the Department

Submitted for the Practical Examination held on:

Internal Examiner External Examiner


EXCEL ENGINEERING COLLEGE
(Autonomous)

VISION

To create competitive human resources in the fields of engineering for the benefit of society to
meet global challenges.

MISSION

 To provide a conducive ambience for better learning and to bring creativity in the students.
 To develop sustain able environment for in no active learning to serve the needy.
 To meet global demands for excellence in technical education.
 To train young minds with values, culture, integrity, innovation and leadership.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VISION

To create better quality technical engineers in Computer Science and Enginerring with ethically
strong values which cater local and global needs of the society.

MISSION

 To instill quality in engineering education that demands excellence.


 To initiate desire among the students to work in close cooperation and collaboration with
industry and professional bodies.
 To train the students for developing software and novel software systems.
 To create ambience for taking initiatives towards entrepreneurship and lifelong learning.
Program Educational Objectives (PEOs)

PEO1: To provide fundamental knowledge to formulate, solve and analyze engineering Problems and pursue
higher studies.

PEO2: To develop the ability of the students in comprehending, analyzing and synthesizing data in order to
design software and create novel software systems.

PEO3: To inculcate effective communication skills, team skills, professional and ethical attitude in the students for enabling
them to relate engineering issues with social issues in a broader context.

PEO4: To provide students managerial and leadership skills so as to make them successfully employed and to
demonstrate a pursuit of lifelong learning in multidisciplinary environment
Program 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 large, 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: Lifelong 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.
LIST OF EXPERIMENTS

1. Write a algorithm & draw flowchart for simple computational problems

2. Write a program to perform different arithmetic operations on numbers in python.

3. Write a python program to implement the various control structures

4. Write a python program for computational problems using recursive function.

5. Demonstrate use of list for data validation.

6. Develop a python program to explore string Functions

7. Implement linear search and binary search.

8. Develop a python program to implement sorting Methods

9. Develop python programs to perform operations on dictionaries.

10. Write a python program to read and write into a file

11. Create a game activity using Pygame like bouncing ball, car race, etc.
Exp No.1 Algorithm & flowchart for simple computational
problems
Date:

Aim:
To write Algorithm and draw flowchart for simple computational problems

Algorithms and flowcharts

1. Algorithm and flowchart to find the sum of two numbers:


Algorithm:
Step 1: Start the program
Step 2: Get the input values for variables num1, num2
Step 3: Add num1 and num2 and assign the result to a variable sum.
Step 4: Step 5: Display sum
Step 6: Stop the program
Flowchart:

2. Algorithm and flowchart to find the greatest number among two numbers:
Algorithm:
Step 1: Start the program
Step 2: Get the input values for variables a and b
Step 3: If a > b go to step 4 otherwise go to step 5
Step 4: Print "A is the Biggest number"
Step 5: else print "B is the Biggest number"
Step 6: Stop the program
Flowchart:

3. Algorithm and flowchart to find the greatest number among three numbers:
Algorithm:
Step 1: Start the program
Step 2: Read three numbers x, y, and z
Step 3: If x is greater than y and x is greater than z, then print x as the greatest number and go
to step 6
Step 4: If y is greater than z, then print y as the greatest number and go to step 6
Step 5: Else print z as the greatest number
Step 6: Stop the program
Flowchart:

4. Algorithm and flowchart to find the given number is odd or even:


Algorithm:
Step 1: Start the program
Step 2: Get the input number
Step 3: Calculate number %2
Step 4: If the result = = 0, then print "It is a even number"
Step 5: else print "It is a odd number"
Step 6: Stop the program
Flowchart:

Result:

Thus Algorithm and flowchart for simple computational problems has been completed successfully.
Exp No.2 Program to perform different arithmetic operations on
numbers in python
Date:

Aim:
To write a python program for performing different arithmetic operations on numbers
Algorithm:
Step 1: Start the program
Step 2: Get the input values for variables num1, num2
Step 3: Perform the various arithmetic operations on the given two input values
Step 4: Store the result of all operations in different variables
Step 5: Display the result
Step 6: Stop the program
Program 1:
a=int(input("Enter the First number"))
b=int(input("Enter the Second number"))
x = a+b
print("The sum of two numbers is", x)
y = a-b
print("The difference between of two numbers is", y)
z=a*b
print("The product of two numbers is", z)
c=a/b
print("The result of division operation is", c)
d = a // b
print("The result of floor division operation is", d)
e=a%b
print("The result of modulus operation is", e)
f = a ** b
print("The result Exponent operation is", f)
Output:
Enter the First number 15
Enter the Second number 6
The sum of two numbers is 21
The difference between of two numbers is 9
The product of two numbers is 90
The result of division operation is 2.5
The result of floor division operation is 2
The result of modulus operation is 3
The result Exponent operation is 11390625
Program 2:
num1 = float(input(" Please Enter the First Value Number 1: "))
num2 = float(input(" Please Enter the Second Value Number 2: "))
add = num1 + num2
sub = num1 - num2
multi = num1 * num2
div = num1 / num2
mod = num1 % num2
expo = num1 ** num2
print("The Sum of {0} and {1} = {2}".format(num1, num2, add))
print("The Subtraction of {0} from {1} = {2}".format(num2, num1, sub))
print("The Multiplication of {0} and {1} = {2}".format(num1, num2, multi))
print("The Division of {0} and {1} = {2}".format(num1, num2, div))
print("The Modulus of {0} and {1} = {2}".format(num1, num2, mod))
print("The Exponent Value of {0} and {1} = {2}".format(num1, num2, expo))

Output:
Please Enter the First Value Number 1: 10
Please Enter the Second Value Number 2: 14
The Sum of 10.0 and 14.0 = 24.0
The Subtraction of 14.0 from 10.0 = -4.0
The Multiplication of 10.0 and 14.0 = 140.0
The Division of 10.0 and 14.0 = 0.7142857142857143
The Modulus of 10.0 and 14.0 = 10.0
The Exponent Value of 10.0 and 14.0 = 100000000000000.0

Result:

Thus the python program for performing different arithmetic operations on numbers has been
executed successfully
Exp No.3 Python program to implement the various control
structures
Date:

Aim:
To write a python program to implement the various control structures
Algorithm:
Step 1: Create an empty list named l
Step 2: Read the value of n
Step 3: Read the elements of the list until n
Step 4: Assign l[0] as maxno
Step 5: If l[i]>maxno then set maxno=l[i]
Step 6: Increment i by 1
Step 7: Repeat steps 5-6 until i
Program 1 :
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
print("The maximum element in the list is:")
print(max)
size=int(input("Enter the number of elements:"))
lst=[]
print("Enter the elements")
for i in range (0, size):
lst.append(int(input()))
print("The elements of the list are", lst)
max_num_in_list(lst)
Output:
Enter the number of elements:8
Enter the elements
4
15
12
8
3
14
10
9
The elements of the list are [4, 15, 12, 8, 3, 14, 10, 9]
The maximum element in the list is:
15

Program 2:
n=int(input("Enter no of terms:"))
list1=[]
print("Enter the Numbers\n")
for i in range(n):
list1.append(int(input ()))
Max =0
for i in range(n):
if list1[i]>Max:
Max=list1[i]
print("Greatest Number is ", Max)
Output:
Enter no of terms: 5
5
Enter the Numbers
17
5
6
8
10
Greatest Number is 17
Result:

Thus the python program to implement the various control structures has been executed successfully
Exp No.4 Python program for computational problems using
recursive function
Date:

Aim:
To write a python program for computational problems using recursive function
Algorithm:
Step 1: Start the program.
Step 2: Read the number to find the factorial.
Step 3: Get a number for a user for num.
Step 4: Check if the number is negative, positive or zero, ie.:num<0
Step 5: If num is equal to zero print a factorial of 0 is1,
Step 6: now check given number is factorial for i in range(1,num+1)
Step 7: factorial = factorial*i
Step 8: print factorial of num

Program:
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
Output:
The factorial of 7 is 5040
Result:
Thus the program for computational problems using recursive function is executed successfully and
output is verified.
Exp No.5 Use of list for data validation
Date:

Aim:
To write a python program for demonstrating the use of list for data validation

Algorithm:
1. Startthe program.
2. Create a list with the data

3. Print the list for data validation..


4. It checks the lists if it is not equal, it returns flase.

Program:

list1 = [1, 2, "Python", "Program", 15.9]


list2 = ["Amy", "Ryan", "Henry", "Emma"]
print(list1)
print(type(list2))
print(list1 == list2)
list = [1,2,3,4,5,6,7]

Output:

[1, 2, 'Python', 'Program', 15.9]


< class ' list ' >
False

Result:
Thus the program to use of list for data validation is executed successfully and output is verified.
Exp No.6 Develop a python program to explore string functions to print reverse words of
string
Date:

Aim:
To develop a python program to explore string functions to print reverse words of string.

Algorithm:
4. Initializethe string.
5. Split the string on space and store the resultant list in a variable called
word. 3.Reverse the list words using reversed function.
5. Convert the result to list.

Program:

#Function to reverse words of

string def rev_sentence(sentence):

# first split the string into words


words = sentence.split(' ')

# then reverse the split string list and join using


space reverse_sentence = ' '.join(reversed(words))

# finally return the joined


string return reverse_sentence

if name == " main ":


input = 'geeks quiz practice
code' print (rev_sentence(input))
Output:

Result:
Thus the program for the use of list for data validation is executed successfully and
output is verified.
Exp No.7a Implement linear search and binary search
Date:

Aim:

To write a Python Program to perform Linear Search.

Algorithm:

1. Read n elements into the list

2. Read the element to be searched

3. If a list[pos]==item, then print the position of the item

4. Else increment the position and repeat step 3 until pos reaches the length of the list

Program:
lst = []

# number of elements as input


n = int(input("Enter number of elements : "))

# iterating till the range


for i in range(0, n):
ele = int(input(“Enter a elements:))

lst.append(ele) # adding the element

print(lst)
x=int(input("Enter your number"))
i=flag=0
while i<len(lst):
if lst[i]==x:
flag=1
break
i=i+1

if flag==1:
print(i+1)
else:
print("this Items not in the list")
Output:

Enter upper limit 5

Enter the elements 6

Enter the elements 45

Enter the elements 2

Enter the elements 61

Enter the elements 26


Enter element to search 6
Element found in position 1

Result:

Thus the Python Program to perform linear search is executed successfully and the
output is verified.
Exp No.7b Implement binary search
Date:

Aim:

To write a Python Program to perform binary search.

Algorithm:

1. Read the search element

2. Find the middle element in the sorted list

3. Compare the search element with the middle element

i.if both are matching, print element found


ii. else then check if the search element is smaller or larger than the middle element
4. If the search element is smaller than the middle element, then repeat steps 2 and 3
for the left sublist of the middle element
5. If the search element is larger than the middle element, then repeat steps 2 and
3 for the right sublist of the middle element
6. Repeat the process until the search element if found in
the list
7. If element is not found, loop terminates

Program:

def search(list1,key):
low=0
high=len (list1)-1
found=False
while low<=high and not found:
mid = (low +high)//2
if key== list1[mid]:
found = True
elif key>list1[mid]:
low = mid+1
else:
high = mid-1
if found ==True:
print("key is found")
else:
print("key is not found")
list1=[23,1,4,2,3]
list1.sort()
print(list1)
key=int(input("enter a key element"))
search(list1,key)

Output:

[1, 2, 3, 4, 23]
enter a key element: 3
key is found

Result:
Thus the Python Program to perform binary search is executed successfully and the
output is verified.
Exp No.8 Develop a python program to implement sorting
methods
Date:

Example 1
Aim:

To write a Python Program to perform selection sort.

Algorithm:

1. Create a function named selection sort

2. Initialise pos=0

3. If alist[location]>alist[pos] then perform the following till i+1,

4. Set pos=location

5. Swap alist[i] and alist[pos]

6. Print the sorted list

Program:

list1=[23,1,4,2,3]

print(list1)

for i in range(len(list1)):

min_val = min(list1[i:])

min_ind = list1.index(min_val)

temp= list1[i]

list1[i]=list1[min_ind]

list1[min_ind]=temp

print(list1)
Output:
[1,2,3,4,23]

Result:

Thus the Python Program to perform selection sort is successfully executed and the
output is verified.
Example 2
Aim:

To write a Python Program to perform Insertion sort.

Algorithm:

1. Consider the first element to be sorted and the rest to be unsorted..


2. Take the first element in the unsorted part(u1) and compare it with sorted part
elements(s1).
3. If u1 < sl then insert u1 in the correct index , else leave it as it is.
4. Take next element in the unsorted part and compare with sorted elements.
5. Repeats 3 and 4 until all the elements are sorted

Program:
def Insertion(my_list):
for index in
range(1,len(my_list)):
current_element =
my_list[index] pos = index
while current_element<my_list[pos-1] and
pos>0: my_list[pos] = my_list[pos-1]
pos = pos-1
my_list[pos] = current_element

list1 = [2,4,3,5,1]
Insertion(list1)
print(“The Insertion Sorted elements is”, list1)

Output:

The Insertion Sorted elements is [1,2,3,4,5]

Result:
Thus the Python Program to perform Insertion sort is successfully executed and the output is
verified
Exp No.9 Develop python programs to perform operations on dictionaries
Date:

Aim:
To develop python programs to perform operations on dictionaries.

Algorithm:

1. Start the pogram


2. Create an empty Dictionary
3. Add the elements to a dictionary
4. Add the set of values to the list
5. Stop the program.

Program:

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements one at a time


Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding set of values


# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome' print("\
nUpdated key value: ")
print(Dict)

# Adding Nested Key value to Dictionary


Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}}
print("\nAdding a Nested Key: ")
print(Dict)

Output:

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Geeks', 2: 'For', 3: 1}

Dictionary after adding 3 elements:


{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}

Updated key value:


{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}

Adding a Nested Key:


{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}}

Result:
Thus the program to perform operations on dictionaries is executed successfully and
output is verified.
Exp No.10 Write a python program to read and write into a file
Date:

Aim:

To write a Python program to find the most frequent words in a text read from a file.

Algorithm:

1. Read the filename

2. Open the file in read mode

3. Read each line from the file to count the words

4. Write each line from the file to replace the punctuations

5. Close the file

6. Print the words

Program:
# Program to show various ways to read and
# write data in a file.

L = ["This is Delhi \n","This is Paris \n","This is London \n"]

# \n is placed to indicate EOL (End of Line)

file1.write("Hello \n")

file1.writelines(L)

file1.close()

#to change file access modes

file1 = open("myfile.txt","r+")

print ("Output of Read function is ")

print (file1.read())

print
# seek(n) takes the file handle to the nth

# bite from the beginning.

file1.seek(0)

print ("Output of Readline function is ")

print (file1.readline())

print

file1.seek(0)

# To show difference between read and readline

print ("Output of Read(9) function is ")

print (file1.read(9))

print

file1.seek(0)

print ("Output of Readline(9) function is ")

print (file1.readline(9) )

file1.seek(0)

# readlines function

print ("Output of Readlines function is ")

print (file1.readlines() )

print

file1.close()
Output:

================= RESTART: C:/Users/students/Desktop/dict.py

================= Output of Read function is

Hello

This is Delhi

This is Paris

This is

London

Output of Read line

function is Hello

Output of Read(9) function

is Hello

Th

Output of Readline(9) function

is Hello

Output of Readlines function is

['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

>>>

Result:
Thus the program to read and write into a file is executed successfully and
output is verified.
Exp No.11 Create a game activity using Pygame
Date:

Aim: To Write a python program to implement pygame

Algorithm:
1. start the program
2. Import Pygame and initialize it.
3. Define the width and height of the window and create a game window.
4. Define colors in RGB format. We will use these colors in our game.
5. Define the ball and the speed by which it will move
6. Define the game loop.
7. Execute the event loop to run.

Progam:

import pygame
# initialize pygame
pygame.init()

# define width of screen


width = 1000
# define height of screen
height = 600
screen_res = (width, height)

pygame.display.set_caption("GFG Bouncing game")


screen = pygame.display.set_mode(screen_res)

# define colors
red = (255, 0, 0)
black = (0, 0, 0)

# define ball
ball_obj = pygame.draw.circle(
surface=screen, color=red, center=[100, 100], radius=40)
# define speed of ball
# speed = [X direction speed, Y direction speed]
speed = [1, 1]
# game loop
while True:
# event loop
for event in pygame.event.get():
# check if a user wants to exit the game or not
if event.type == pygame.QUIT:
exit()

# fill black color on screen


screen.fill(black)

# move the ball


# Let center of the ball is (100,100) and the speed is (1,1)
ball_obj = ball_obj.move(speed)
# Now center of the ball is (101,101)
# In this way our wall will move

# if ball goes out of screen then change direction of movement


if ball_obj.left <= 0 or ball_obj.right >= width:
speed[0] = -speed[0]
if ball_obj.top <= 0 or ball_obj.bottom >= height:
speed[1] = -speed[1]

# draw ball at new centers that are obtained after moving ball_obj
pygame.draw.circle(surface=screen, color=red,
center=ball_obj.center, radius=40)

# update screen
pygame.display.flip()
Output:

Result:
Thus the python program to implement pygame was successfully executed and verified.

You might also like