2302cs303-Problem Solving Using Python-Lab Manual
2302cs303-Problem Solving Using Python-Lab Manual
LAB MANUAL
REGULATION 2023
AIM
ALGORITHM
Step1: Start
Step2: Read the variables x,y
Step3: Assign the values to variables
Step4: Perform swapping operations
Step5: print the value of after swapping
Step 6: Stop
PROGRAM
x=5
y=10
temp=x
x=y
y=temp
print('The value of x after swapping:',x)
print('The value of y after swapping:',y)
OUTPUT
RESULT
Thus the exchange of two values has been executed and verified successfully.
EX NO: 1B
CIRCULATE THE VALUE OF N VARIABLES
DATE:
AIM
PROGRAM
no_of_terms = int(input("Enter number of values : "))
list1 = []
forval in range(0,no_of_terms,1):
[Link](ele)
print("Circulating the elements of list ", list1)
forval in range(0,no_of_terms,1):
ele = [Link](0)
[Link](ele)
print(list1)
OUTPUT
Enter number of values : 3
Enter integer : 6
Enter integer : 7
Enter integer : 8
[7, 8, 6]
[8, 6, 7]
[6, 7, 8]
RESULT
Thus the program for circulate the value of n variables has been executed and verified successfully
EX NO: 1C
DISTANCE BETWEEN TWO POINTS
DATE:
AIM
ALGORITHM
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)
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 program for distance between two points has been verified successfully.
EX NO: 2A
NUMBER SERIES
DATE:
AIM
ALGORITHM
PROGRAM
OUTPUT
Enter a number: 6
1 + 2 + 3 + 4 + 5 + 6 = 21
RESULT
Thus the program for number series has been verified successfully
EX NO: 2B
NUMBER PATTERN
DATE:
AIM
ALGORITHM
Step1: Start
Step3: Inner for loop is used to print the pattern upto n values.
Step5: Stop.
PROGRAM
for i in range(5):
for j in range(5):
print(j+1, end=' ')
print()
OUTPUT
12345
12345
12345
12345
12345
RESULT
Thus the program for number pattern has been verified successfully.
EX NO: 2C
PYRAMID PATTERN
DATE:
AIM
ALGORITHM
Step1: Start
Step2: Using two for loops print the number pattern in pyramid structure.
Step3: For loop is used to print numbers upto 2*i+1 values.
Step4: Print the numbers upto k+1 till end
Step5: Stop.
PROGRAM
for i in range(n):
for j in range(n - i - 1):
print(' ', end='')
for k in range(2 * i + 1):
print(k + 1, end='')
print()
OUTPUT
1
123
12345
1234567
123456789
RESULT
Thus the program for pyramid pattern has been verified successfully
EX NO:3A
IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
LISTS ITEMS PRESENT IN A LIBRARY
DATE:
AIM
To write a python program items present in library using list.
PROGRAM
list=["phy","che","mat","eng","tam"]
for i in range(0,4,1):
print(list[i])
[Link](3,"computer")
print(list)
print("computer" not in list)
[Link]("eng")
print(list)
print([Link]("mat"))
print([Link]("eng"))
print("tam" in list)
OUTPUT
phy
che
mat
eng
['phy', 'che', 'mat', 'computer', 'eng', 'tam']
False
['phy', 'che', 'mat', 'computer', 'tam']
2
0
True
RESULT
Thus the program for List items present in the Library has been verified successfully.
EX NO:3B
COMPONENTS OF A CAR
DATE:
AIM
To write a python program Components of a car using List.
PROGRAM
car_components=["Engine","battery","light","frontaxle","brakes"]
print(car_components)
car_components.insert(4,"radiator")
car_components.insert(3,"alternator")
print(car_components)
car_components.append("trunk")
car_components.append("air filter")
print(car_components)
car_components.pop(1)
print(car_components)
print(car_components[:-4])
car_components.extend("seat","windowframe","mirror")
print(car_components)
OUTPUT
RESULT
Thus the Components of a car has been executed and verified successfully
EX NO:3C
CONSTRUCTION FOR BUILDING
DATE:
AIM
To write a python program items present in library using list.
PROGRAM
materials=("Cement bags","sand","aggregates","bricks")
material2=("steel bars","paint")
print(materials)
mat3 = (materials+material2)
print(mat3)
print(materials[:3])
print(material2[1])
print(len(materials))
print(len(material2))
print(max(materials))
print(min(materials))
print(cmp(materials,material2))
OUTPUT
RESULT
Thus the Construction of a building has been executed and verified successfully
EX NO:4A
LANGUAGES
DATE:
AIM
To write a python program Languages using dictionary.
PROGRAM
language1={"tamil","english","telgu"}
language2={"hindi","urudu","malayalam","telgu"}
print(language1)
print(language2)
[Link]("spanish")
print(language1)
[Link]("kanada")
print(language2)
print(language1&language2)
print(language1|language2)
lang3=[Link](language2)
print(lang3)
OUTPUT
set(['tamil', 'telgu', 'english'])
set(['malayalam', 'hindi', 'urudu', 'telgu'])
set(['spanish', 'tamil', 'telgu', 'english'])
set(['malayalam', 'kanada', 'hindi', 'urudu', 'telgu'])
set(['telgu'])
set(['urudu', 'telgu', 'kanada', 'spanish', 'hindi', 'english', 'malayalam', 'tamil'])
set(['english', 'tamil', 'spanish'])
RESULT
AIM
PROGARAM
com1={"steering wheel","gear","tyre","radiator"}
com2={"sensor","wheel","brake"}
print(com1)
print(com2)
print(com1|com2)
com3=[Link](com2)
[Link]("light")
print(com2)
OUTPUT
RESULT
Thus the Components of Automobile has been executed and verified successfully
EX NO:4C
ELEMENTS OF A CIVIL STRUCTURE
DATE:
AIM
PROGRAM
ele1={1:"foundation",2:"floor"}
ele2={1:"walls",2:"beams",3:"roof",4:"stair"}
print(ele1)
print(ele2)
print(ele1[1])
print(ele2[3])
print([Link](2))
ele1[2]="cement"
print(ele1)
print([Link](2))
OUTPUT
RESULT
Thus the Elements of a Civil structure has been executed and verified successfully
EX NO:5A
FACTORIAL
DATE:
AIM
ALGORITHM
Step1: Start
Step2: Use factorial function to calculate the value.
Step3:If n==1 and n==0 return 1.
Step4:Get the value of num to print the values of factorial.
Step4:Call the factorial function.
Step5:Stop
PROGRAM
def factorial(n):
# Driver Code
num = 5;
print("Factorial of",num,"is",
factorial(num))
OUTPUT
Factorial of 5 is 120
RESULT
Thus the Factorial program has been executed and verified successfully
EX NO:5B
LARGEST NUMBER IN LIST
DATE:
AIM
PROGRAM
#list
list=[3, 9, 7, 3, 6, 5, 7, 24, 6]
print("largest in ",list,"is")
print(largest(list))
OUTPUT
RESULT
Thus the program for largest number in list has been verified successfully.
EX NO:5C
AREA OF SHAPE
DATE
AIM
PROGRAM
deffindArea(r):
PI = 3.142
return PI * (r*r);
# Driver method
num=float(input("Enter r value:"))
print("Area is %.6f" % findArea(num));
OUTPUT
Enter r value:5
Area is 78.550000
RESULT
Thus the program for area of shape has been verified successfully.
EX NO:6A
STRING REVERSE
DATE:
AIM
PROGRAM
defreverse(s):
str=""
fori ins:
str=i +str
returnstr
s ="Pavithra"
OUTPUT
RESULT
Thus the program for string reverse has been verified successfully.
EX NO:6B
STRING PALINDROME
DATE:
AIM
PROGRAM
string=input(("Enter a letter:"))
if(string==string[::-1]):
print("The letter is a palindrome")
else:
print("The letter is not a palindrome")
OUTPUT
Enter a letter:COMPUTER
The letter is not a palindrome
Enter a letter:MALAYALAM
The letter is a palindrome
RESULT
Thus the program for string palindrome has been verified successfully.
EX NO:6C
COUNT THE CHARACTERS IN STRING
DATE:
AIM
To write a program for count the characters in string operation.
PROGRAM
# using split()
# to count words in string
res =len(test_string.split())
# printing result
print("The number of words in string are : "+str(res))
print("The number of words in string are : ", len(test_string))
OUTPUT
RESULT
Thus the program for count the characters in string has been verified successfully.
EX NO:6D
REPLACE CHARACTERS
DATE:
AIM
PROGRAM
input_string = "This is [Link]. Here, you can read python tutorials for free."
new_string = input_string.replace('i', "I")
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)
OUTPUT
RESULT
Thus the program for replace characters in string has been verified successfully.
EX NO:7A
PANDAS
DATE:
AIM
PROGRAM
import pandas as pd
df = [Link]({'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]});
print(df)
OUTPUT
X Y Z
0 78 84 86
1 85 94 97
2 96 89 96
3 80 83 72
4 86 86 83
RESULT
AIM
PROGRAM
importnumpy as np
print(a)
#Slicing in array
print([Link])
b = a[1:, 2:]
print(b)
OUTPUT
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
(3, 4)
[[ 7 8]
[11 12]]
RESULT
Thus the program for numpy has been verified successfully.
EX NO:7C
MATPLOT
DATE:
AIM
PROGRAM
[Link] as plt
OUTPUT
RESULT
AIM
PROGRAM
defeqn(x):
return x + cos(x)
myroot = root(eqn, 0)
print(myroot.x)
OUTPUT
[-0.73908513]
RESULT
To write a python program for copy the contents of one file to another file.
ALGORITHM
Step1: Start
Step2: Read the existing file.
Step3: Copy the contents of file from first file to second file by using write keyword.
Step4: View the contents of second file.
Step5: Stop
PROGRAM
print("Enter the Name of Source File: ")
sFile = input()
print("Enter the Name of Target File: ")
tFile = input()
RESULT
AIM
ALGORITHM
Step1: Start
Step2: Open the existing file to read in read mode.
Step3: Split the lines in a file using split( ) method.
Step4: Calculate the number of words in a file by performing,
number_of_words += len(lines)
Step5: Print the total number of words in a file.
Step6: Stop.
PROGRAM
number_of_words = 0
OUTPUT
RESULT
Thus, the python program to count the words in file has been created and executed
successfully.
EX:NO: 8C
LONGEST WORD
DATE:
AIM
To write a python program to find the longest word in a file.
ALGORITHM
Step1: Start.
Step2: Open the existing file to read the contents of file.
Step3: The words in the lines are splitted using function split( ).
Step4: Maximum length of word in each line will be calculated,
max_len=len(max(words, key=len))
Step5: Check the length of word is equal to maximum length,
return[word for word in words iflen(word)==max_len]
Step6: Print the longest word in a file.
Step7. Stop.
PROGRAM
deflongest_word(filename):
withopen(filename,'r')asinfile:
words=[Link]().split()
max_len=len(max(words, key=len))
return[word for word in words iflen(word)==max_len]
print(longest_word('[Link]'))
OUTPUT
['[Link].']
RESULT
Thus the Longest word in a file has been executed and verified successfully.
EX:NO: 9A IMPLEMETING REAL TIME APPLICATION USING EXCEPTION HANDLING
DATE: DIVIDE BY ZERO
AIM
ALGORITHM
Step1: Start.
Step2: Get the two values by using variables num1 and num2.
Step3: Calculate the result by performing division operation.
Result= num1/num2
Step4: Print the result.
Step5: Otherwise if any invalid input print “Input Please Input Integer..."
Step6: If any value is divided by zero it throws zero division error.
Step7: Stop.
PROGRAM
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
print(result)
exceptValueError as e:
print("Invalid Input Please Input Integer...")
exceptZeroDivisionError as e:
print(e)
OUTPUT
Enter First Number: 45
Enter Second Number: 0
divisions by zero
RESULT
Thus the python program for exception handling to perform divide by zero has been created and
executed successfully.
EX:NO: 9B
VOTERS AGE VALIDITY
DATE:
AIM
To write a python program for check the Voters age validity.
ALGORITHM
Step1: Start
Step2: Get the value of age.
Step3: Check if age is greater than 18.
Step4: Print eligible to vote.
Step5: Otherwise print not eligible to vote.
Step6: If any error occur means print an error occurred.
Step7: Stop
PROGRAM
def main():
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
#display exception's default error message
exceptValueError as err:
print(err)
except:
print("An Error occured")
print("rest of the code...")
main()
OUTPUT
rest of the code...
Enter your ageTHIRTY
> THIRTY
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RESULT
Thus the python program to check the Voters age validity has been
created and executed successfully.
EX:NO: 9C
STUDENT MARK RANGE VALIDATION
DATE:
AIM
To write a python program to check the validation of student marks using exception
Handling.
ALGORITHM
Step1: Start.
Step2: Read the values of s1,s2,s3,s4.
Step3: Calculate total and average using formula,
avg=(s1+s2+s3+s4)/4
Step4: Check if average greater than 50 print pass.
Step5: Otherwise print fail.
Step6: If any error occur means print value error.
Step7: Stop.
ROGRAM
s1=int(input("enter s1"))
s2=int(input("enter s2"))
s3= int(input("enter s3"))
s4=int(input("enter s4"))
avg=(s1+s2+s3+s4)/4
try:
if(avg>50):
print("pass")
else:
print("fail")
except:
print("valueerror")
OUTPUT
enter s18
enter s20
enter s37 enter s48.9
Trace back (most recent call last):
File "<string>", line 4, in <module>
Value Error: invalid literal for int() with base 10: '8.9'
RESULT
Thus the python program for student mark validation has been created and executed successfully.
EX:NO: 10
EXPLORING PYGAME TOOL
DATE:
AIM
To develop the games using python installation package by exploring Pygame tool.
PYGAME
Pygame is a set of Python modules designed to make games. It uses SDL which is a
cross-platform library that abstracts the multimedia components of a computer as audio and
video and allows an easier development of programs that uses this resources.
INSTALLATION
Before starting the installation process you must have python installed at your system. In
case you don‟t have it check this installation guide first.
The pygame installation itself can be different from an OS and can be checked for more
details at its [official install guide]
([Link] Installation).
But, to install it into a Debian based system such as Ubuntu you must first make sure its
dependencies are installed:
$ sudo apt-get build-dep python-pygame
Hello World
As usual, when we are learning something new in programming we start as small as possible to
check it everything is working properly before proceeding with the studies.
To make that let’s create a file called [Link] with the following content:
-*- coding: utf-8 -*-
import time
importpygame
[Link]()
[Link].set_caption('Hello World')
[Link]([0, 0, 0])
[Link]()
[Link](5)
Then we just need to run it:
$ python [Link]
So the result will be this:
The three first lines are common to the most programs written in python. At the first line,
we define the file encoding used by the python interpreter which was utf-8. This line is most
common at codes written in python 2 that has non ASCII characters, if you are using python 3
you probably won‟t use it because utf-8 is the default encoding already. The second and third
code lines are importing the python libraries that will be responsible for all the magic.
The command [Link]() starts all modules that need initialization inside pygame.
At [Link].set_mode we create an area for the game window at the size of
640x480 pixels, followed by [Link].set_caption were we set the value “Hello World” to
our window title.
With the window created we can use the command fill from screen to fill it with the black
color. The colors are passed on a list of three elements that represent the values from RGB. Each
value can go from 0 to 255. You can change the values to see by yourself the window changing
its color.
The command [Link] represents an important concept to pygame and game
development itself. When we use commands to draw at the screen, we are actually drawing a
virtual surface at the memory that represents a portion of our actual screen. To make that
drawing visible to the user we need to send it to the actual screen, and we do it in these two
separate steps to prevent from displaying incomplete frames to the user. It is like drawing at a
board and then “flipping it” to people see what we drew.
And then, to finish the command sleep from the library time makes the program to wait 5
seconds before finish the execution. Otherwise, the program would close before we see the
result.
RESULT
Thus the Pygame tool for development of gaming application using python has been explored
and developed successfully.
EX NO:11 A
DEVELOPING A GAME ACTIVITY USING PYGAME LIKE BOUNCING BALL
DATE :
AIM
To write a python program to simulate bouncing ball using pygame tool.
ALGORITHM
PROGRAM
importpygame
[Link] import *
[Link]()
screen = [Link].set_mode((400, 300))
done = False
while not done:
for event in [Link]():
[Link] == [Link]:
done = True
[Link](screen, (255,255,255), [100, 80], 10, 0)
[Link]()
[Link](screen, (0,0,0), [100, 80], 10, 0)
[Link]()
[Link](screen, (255,255,255), [150, 95], 10, 0)
[Link]()
[Link](screen, (0,0,0), [150, 95], 10, 0)
[Link]()
[Link](screen, (255,255,255), [200, 130], 10, 0)
[Link]()
[Link](screen, (0,0,0), [200, 130], 10, 0)
[Link]()
[Link](screen, (255,255,255), [250, 150], 10, 0)
[Link]()
[Link]()
for event in [Link]():
[Link] == QUIT:
[Link]()
[Link]()
OUTPUT
RESULT
Thus, the python program for bouncing ball in Pygame has been executed
successfully.
EX NO:11 B
DEVELOPING A GAME ACTIVITY USING PYGAME LIKE CAR GAME
DATE
AIM
ALGORITHM
Step1: Start.
Step2: Install pip pygame, py-m pip install-U pygame-user",py-m pip install pygame.
Step3: Intializes all the imported pygame modules.
Step4: Takes a tuple or a list as its parameter to create a surface (tuple preferred)
Step5: By using update( ),quit( ),Surface fill( ) functions used to develop the gaming
applications with its parameters.
Step6: Time clock and event get functions used to perform the action on time.
Step7: Stop.
PROGRAM
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
BADDIEMINSIZE = 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 8
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 6
PLAYERMOVERATE = 5
count=3
def terminate():
[Link]()
[Link]()
defwaitForPlayerToPressKey():
while True:
for event in [Link]():
[Link] == QUIT:
terminate()
[Link] == KEYDOWN:
[Link] == K_ESCAPE: #escape quits
terminate()
return
defplayerHasHitBaddie(playerRect, baddies):
for b in baddies:
[Link](b['rect']):
return True
return False
defdrawText(text, font, surface, x, y):
textobj = [Link](text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
[Link] = (x, y)
[Link](textobj, textrect)
# set up pygame, the window, and the mouse cursor
[Link]()
mainClock = [Link]()
windowSurface = [Link].set_mode((WINDOWWIDTH, WINDOWHEIGHT))
[Link].set_caption('car race')
[Link].set_visible(False)
# fonts
font = [Link](None, 30)
# sounds
gameOverSound = [Link]('music/[Link]')
[Link]('music/[Link]')
laugh = [Link]('music/[Link]')
# images
playerImage = [Link]('image/[Link]')
car3 = [Link]('image/[Link]')
car4 = [Link]('image/[Link]')
playerRect = playerImage.get_rect()
baddieImage = [Link]('image/[Link]')
sample = [car3,car4,baddieImage]
wallLeft = [Link]('image/[Link]')
wallRight = [Link]('image/[Link]')
# "Start" screen
drawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH / 3) - 30,
(WINDOWHEIGHT / 3))
drawText('And Enjoy', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT /
3)+30)
[Link]()
waitForPlayerToPressKey()
zero=0
if not [Link]("data/[Link]"):
f=open("data/[Link]",'w')
[Link](str(zero))
[Link]()
v=open("data/[Link]",'r')
topScore = int([Link]())
[Link]()
while (count>0):
# start of the game
baddies = []
score = 0
[Link] = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
[Link](-1, 0.0)
while True: # the game loop
score += 1 # increase score
for event in [Link]():
[Link] == QUIT:
terminate()
[Link] == KEYDOWN:
[Link] == ord('z'):
reverseCheat = True
[Link] == ord('x'):
slowCheat = True
[Link] == K_LEFT or [Link] == ord('a'):
moveRight = False
moveLeft = True
[Link] == K_RIGHT or [Link] == ord('d'):
moveLeft = False
moveRight = True
[Link] == K_UP or [Link] == ord('w'):
moveDown = False
moveUp = True
[Link] == K_DOWN or [Link] == ord('s'):
moveUp = False
moveDown = True
[Link] == KEYUP:
[Link] == ord('z'):
reverseCheat = False
score = 0
[Link] == ord('x'):
slowCheat = False
score = 0
[Link] == K_ESCAPE:
terminate()
[Link]()
# Check if any of the car have hit the player.
ifplayerHasHitBaddie(playerRect, baddies):
if score >topScore:
g=open("data/[Link]",'w')
[Link](str(score))
[Link]()
topScore = score
break
[Link](FPS)
# "Game Over" screen.
[Link]()
count=count-1
[Link]()
[Link](1)
if (count==0):
[Link]()
drawText('Game over', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press any key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80,
(WINDOWHEIGHT / 3) + 30)
[Link]()
[Link](2)
waitForPlayerToPressKey()
count=3
[Link]()
OUTPUT
RESULT
Thus, the program for Car game using Pygame has been executed successfully.
MINI PROJECT
SOURCE CODE
OUTPUT
Tie!
Rock, Paper or Scissors?Paper
Tie!
Rock, Paper or Scissors?Scissors
You win! Scissors cut Paper
Rock, Paper or Scissors?