Python Final Lab Manual (1)
Python Final Lab Manual (1)
CLASS : AI & ML - B
SEMESTER : II
SUBJECT : AI24221/PYTHON PROGRAMMING LABORATORY
OBJECTIVES:
To understand the problem solving approaches.
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.
LISTOFEXPERIMENTS:
1. Identification and solving of simple technical problems, and developing flowcharts for
the same.
2. Python programming using simple statements and expressions.
3. Scientific problems using Conditionals and Iterative loops.
4. Implementing real-time applications using Lists, Tuples.
5. Implementing technical applications using Sets, Dictionaries.
6. Implementing programs using Functions.
7. Implementing programs using Strings.
8. Implementing programs using written modules and Python Standard Libraries.
9. Implementing technical applications using File handling.
10. Implementing real-time applications using Exception handling.
AI24221–PYTHON PROGRAMMING LABORATORY
S.NO. NAMEOFTHEPROGRAM
1 Identification and solving of simple real life or scientific or technical
Problems developing flowchart for the same.
1.1 Electricity Billing
1.2 Python program for sin series
2 Python programming using simple statements and expressions
2.1 Exchanging the values of two variables in python
2.2 Circulate the values of n variables
3 Scientific problems using Conditionals and Iterative loops.
3.1 Number Series-Fibonacci Series
3.2 Number Series-Odd Numbers
4 Implementing real-time applications using Lists, Tuples.
4.1. Basic operations of List
4.2. Library functions using list.
4.3 Components of a car using tuples.
5. Implementing technical applications using Sets, Dictionaries.
5.1 Languages using dictionaries
5.2 Components of Automobile using dictionaries
6 Implementing programs using Functions.
6.1 Square root of a given number using Newton’s method.
6.2 Factorial of a number using functions
7 Implementing programs using Strings.
7.1 Reverse of a string
7.2 Palindrome of a string
8 Implementing programs using written modules and Python
Standard Libraries.
8.1 Convert list into a Series using pandas
8.2 Finding the elements of a given array is zero using numpy
9 Implementing technical applications using File handling.
9.1 Command Line Arguments(Word Count)
9.2 Find the longest word(File handling)
10 Implementing real-time/technical applications using Exception
handling.
10.1 Divide by zero error–Exception Handing
10.2 Voter’s age validity
Ex:1.1
Date: ELECTRICITY BILLING
Aim:
To write a python program to print electricity bill.
Algorithm:
.
Flowchart:
Program:
Cr = int(input("Enter current month reading"))
pr=int(input("Enter previous month reading"))
consumed=cr - pr
if(consumed>=1andconsumed<=100):
amount=consumed * 2
print("your bill is Rs.", amount)
elif(consumed>100andconsumed<=200):
amount=consumed * 3 print("your bill is Rs.",amount)
elif(consumed>200andconsumed<=500):
amount=consumed * 4 print("your bill is Rs.",amount)
elif(consumed>500):
amount=consumed * 5 print("your bill is Rs.",amount)
else:
print("Invalid reading")
Output:
Enter current month reading 500
Enter previous month reading 200
your bill is Rs. 1200
Aim:
Algorithm:
Step1: Start
Step 2 : Read the values of x and
n Step 3 : Initialize sine=0
Step4: Define a sine function using for loop, first convert degrees to radians.
Step 5 : Compute using sine formula expansion and add each term to the sum variable.
Step 6 : Print the final sum of the expansion.
Step7: Stop.
Output:
Aim:
To write a python program to Exchanging the values of two variables taking input from the user.
Algorithm:
Step 1:Start
Step 2:Define a function named format()
Step 2 : Read the input values X and Y
Step 3 : Perform the following steps
Step3.1:temp=x
Step 3.2 : x = y
Step3.3:y=temp
Step 4 : Print the swapped value as result
Step 5 : End
Program:
Using Temporary variable
output:
Enter value of x:10
.
Enter value of y:20
The value of x after swapping:20
The value of y after swapping:10
output:
>>>x
10
>>>y
35
.
Result : Thus the Python program to exchange the values of two variables was executed successfully
and the output is verified.
Aim:
To write a python program to Circulate the values of n variables taking in put from the user.
Algorithm:
Step1: Start
Step2: Declare a list
Step 3: Read number of input value.
Step 4: Store the value of in put in list.
Step 5: Print the original list.
Step 6: Use range function with for loop to circulate the values
Step 7 : Print the result
Program:
EnterthelistValues:'0123'
['0','1', '2', '3']
['1','2','3','0']
['2','3','0','1']
['3','0','1','2']
Aim:
To write a python program to print Fibonacci series taking input from the user.
Algorithm:
Step 1: Start
Program:
# Fibonacci series
print("Fibonacci series")
Num_of_terms=int(input("Enter number of terms:"))
f1 = -1
f2 =1
for i in range(0,Num_of_terms,1): term
= f1+f2
print(term,end="") f1 =
f2
f2 =term
Output:
Fibonacci series :
Enter number of terms:5
01123
Aim:
To write a python program to print odd numbers by taking input from the user
Algorithm:
Step1: start
Step 2 : Declare the list of numbers using list.
Program:
#list of numbers
list1= [10,21, 4,45, 66, 93]
#iterating each number in list
for num in list1:
#checking condition
if num % 2 != 0:
print(num,end="")
Output:
Enter number of terms: 5
Number Patterns-Odd Numbers:
13579
Aim:
To write python programs using list functions to perform the operations of list library.
Algorithm:
Step1: Start
Step2: Declare a list
Step3: Read the input value.
Step4: Store the value of input in list.
Step 5 : Process the list functions present in library function.
Step 6 : Print the result
Step7: End
Program:
#creatingalist
Library=['OS','OOAD','MPMC']
print("Books in library are:")
print(Library)
OUTPUT:
Books in library are:
['OS','OOAD','MPMC']
OUTPUT:
Accessing a element from the list OS MPMC
OUTPUT:
Accessing a element from a Multi-Dimensional list OOAD TOC
#Negative indexing
Library=['OS','OOAD','MPMC']
print("Negative accessing a element from the list")
print(Library[-1])
print(Library[-2])
OUTPUT:
Negative accessing a element from the list MPMC OOAD
#Slicing
Library=['OS','OOAD','MPMC','TOC','NW']
print(Library[1][:-3])
print(Library[1][:4])
print(Library[2][2:4])
print(Library[3][0:4])
print(Library[4][:])
OUTPUT:
OS OOAD MC TOC NW
#append()
Library=['OS','OOAD','MPMC']
Library.append(“DS”)
Library.append(“OOPS”)
Library.append(“NWs”)
print(Library)
OUTPUT:
['OS','OOAD','MPMC','DS','OOPS','NWs']
OUTPUT:
['OS','OOAD','MPMC','TOC','DWDM']
#insert()
Library=['OS','OOAD','MPMC']
Library.insert(0,”DS”)
print(Library)
OUTPUT:
['DS','OS','OOAD','MPMC']
#del method
Library=['OS','OOAD','MPMC']
delLibrary[:2]
print(Library)
OUTPUT:
['MPMC']
#remove()
Library=['OS','OOAD','MPMC','OOAD']
Library.remove('OOAD')
print(Library)
OUTPUT:
['OS','MPMC','OOAD']
#reverse()
Library=['OS','OOAD','MPMC']
Library.reverse()
print(Library)
OUTPUT:
['MPMC','OOAD','OS']
#sort()
Library=['OS','OOAD','MPMC']
Library.sort()
print(Library)
#+concatenation operator
Library=['OS','OOAD','MPMC']
Books=['DS','TOC','DMDW']
print(Library+Books)
OUTPUT:
['OS','OOAD','MPMC','DS','TOC','DMDW']
# *replication operator
Library=['OS','OOAD','MPMC','TOC','NW']
print('OS' in Library)
print('DWDM' in Library)
print('OS' not in Library)
OUTPUT:
True
False
False
#count()
Library=['OS','OOAD','MPMC','TOC','NW']
x=Library.count("TOC")
print(x)
OUTPUT: 1
output is verified
Aim:
To write a python program to implement the library functionality using list.
Algorithm:
Step 1 : Start the program
Step 2 : Initialize the booklist
Step3: Get option from the user for accessing the library function
Add the book to list
Issue a book
Return the book
View the list of book
Step4: if choice is1 then get book name and add to book list
Step 5 : if choice is 2 then issue the book and remove from book list
Step6: if choice is 3 then return the book and add the book to list
Step 7 : if choice is 4 then the display the book list
Step 8 : otherwise exit from menu
Step 9 : Stop the program.
Program:
bk_list=["OS","MPMC","DS"]
print("Welcome to library”")
while(1):
ch=int(input("\n1.addthebooktolist\n2.issueabook\n3.returnthebook\n4.viewthe book list \n 5.
Exit \n"))
if(ch==1):
bk=input("enter the book name")
bk_list.append(bk)
print(bk_list)
elif(ch==2):
ibk=input("Enter the book to issue")
bk_list.remove(ibk)
print(bk_list)
elif(ch==3):
rbk=input("enter the book to return")
bk_list.append(rbk)
print(bk_list)
elif(ch==4):
print(bk_list)
else:
break .
Aim:
To write a python program to implement the operation of list for components of car.
Algorithm:
Program:
cc=['Engine','Frontxle','Battery','transmision']
com=input('Enter the car components:')
cc.append(com)
print("Components of car :",cc)
print("length of the list:",len(cc))
print("maximum of the list:",max(cc))
print("minimum of the list:",min(cc))
print("indexing(Value at the index 3):",cc[3])
print("Return 'True' if Battery is present in the list")
print("Battery" in cc)
print("multiplication of list element:",cc*2)
.
Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])
Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])
Output: Enter the car components : Glass
Components of car:['Engine','Frontxle','Battery','transmision','Glass'] length
of the list: 5
maximum of the list: transmission minimum of the list: Battery
indexing(Valueattheindex3):transmision
Return 'True' if Battery is present in the list True
Multiplication of list element:['Engine','Frontxle','Battery','transmision','Glass', 'Engine',
'Front xle', 'Battery', 'transmision', 'Glass']
Aim:
To write a python program to implement the languages using dictionaries.
Algorithm:
Step1 : Start the program
Step2: Create a empty dictionary using{}
Step 3 : dict() is used to create a dictionary.
Step 4 : To add a value, update() is used in key value pair.
Step 5 : Calculate the total values in the dictionary using len() .
Step 6 : Remove the particular key in the dictionary by using pop()
Step 7 : Print the keys in the dictionary by using key()
Step 8 : Print the values in the dictionary by using values()
Step 9 : Print the key value pair in the dictionary using items()
Step 10 : Clear the the key value pair by using clear()
Step11: Delete the dictionary by using del dictionary
Program:
Language={}
print("Empty Dictionary:",Language)
Language=dict({1: "english", "two": "tamil", 3: "malayalam"})
print(" Using dict() the languages are :",Language)
New_Language={4:"hindi",5:"hindi"}
#duplicate values can create
Language.update(New_Language)
print(" the updated languages are :",Language)
print("the length of the languages:",len(Language))
Language.pop(5)
print("key5hasbeenpoppedwithvalue:",Language)
print(" the keys are :",Language.keys())
print("the values are :",Language.values())
print("the items in languages are:",Language.items())
Language.clear()
.
print(Language)
OUTPUT:
Empty Dictionary:{}
Aim:
To write a python program to implement automobile using dictionaries.
Algorithm:
Step1: Start the program
Step2: Create a empty dictionary using{}
Step3: dict() is used to create a dictionary.
Step4: Get the value in the dictionary using get()
Step5: adding[key] with value to a dictionary using indexing operation.
Step 6: Remove a key value pair in dictionary using pop item().
Step7: To check whether key is available in dictionary by using membership operatorin.
Step 8: Stop the program.
Program:
auto_mobile={}
print(" Empty dictionary ",auto_mobile)
auto_mobile=dict({1:"Engine",2:"Clutch",3:"Gearbox"})
print(" Automobile parts :",auto_mobile)
print("Thevaluefor2is",auto_mobile.get(2))
auto_mobile['four']="chassis"
print("Updatedauto_mobile",auto_mobile)print(auto_mobile.popitem()) print("
The current auto_mobile parts is :",auto_mobile)
print("Is 2 available in automobile parts")
print(2 in auto_mobile)
OUTPUT:
Empty dictionary{}
Auto mobile parts:{1:'Engine',2:'Clutch',3:'Gearbox'}The value
for 2 is Clutch
Updatedauto_mobile{1:'Engine',2:'Clutch',3:'Gearbox','four':'chassis'}(1,'Engine') The
current auto_mobile parts is : {2: 'Clutch', 3: 'Gearbox', 'four': 'chassis'}
Is 2 available in automobile parts True
Aim:
To write a python program to find gcd of given numbers using Euclid’s algorithm.
Algorithm:
Program:
defgcd(a, b):
if(b==0):
return a
else:
return gcd(b, a % b)
a=int(input("Enter the value of a"))
b=int(input("Enter the value of b"))
result=gcd(a,b)
print("The greatest common divisor is",result)
Output:
Enter the value of a 24
Enterthevalueofb54
Thegreatestcommondivisoris6
Aim:
To write a python program to find to find square root of a given number using newtons method.
Algorithm:
Program:
approx= 0.5 * n
better=0.5*(approx+n/approx)
while(better != approx):
approx= better
better=0.5*(approx+n/approx) return
approx
n=int(input("Enter the number"))
result=newton Sqrt(n)
print("The Square root for the given number is", result)
OUTPUT:
Enter the number 25
The Square root for the given number is 5.0
Aim:
To write a python program for reversing a string.
Algorithm:
Program:
def reversed_string(text):
if len(text) == 1:
return text
return reversed_string(text[1:])+text[:1]
a=reversed_string("Hello, World!")
print(a)
Output:
dlroW,olleH
Aim:
Towriteapythonprogramforpalindromeofastring.
Algorithm:
Step1:Startthe program.
Step 2:Read the valueof a string value by using inputmethod.
Step3:ifstring==string[::-1],print“thestringispalindrome”. Step
4: else print “ Not a palindrome ”.
Step5:Stop the program
Program:
string=input(("Enterastring:"))
if(string==string[::-1]):
print("Thestringisapalindrome")
else:
print("Notapalindrome")
Output:
Enter a string: madam
Thestringisapalindrome
Enter a string: nice
Notapalindrome
Result:
Downloaded by SRIDEVI.M MIT-AP/AI&ML ([email protected])
areverified.
Thusthe pythonprogram forpalindromeofa stringisexecutedandthe results
.
Aim:
Towriteapythonprogramforcountingthecharactersof string.
Algorithm:
Step1:Starttheprogram. Step
2: Define a string.
Step2:Defineandinitializeavariablecountto 0.
Step3:Iteratethroughthestringtilltheendandforeachcharacterexceptspaces,increment the count
by 1.
Step4:Toavoidcountingthespaceschecktheconditioni.e.string[i]!=''.
Step5:Stopthe program.
Program:
a=input("enterthe
string") count = 0;
#Countseachcharacterexcept
space for i in range(0, len(a)):
if(a[i]!=''):
count = count+ 1;
#Displaysthetotalnumberofcharacterspresentinthegivenstring print("Total
number of characters in a string: " + str(count));
Output:
enterthestringhai
Totalnumberofcharactersinastring:3
Result:Thusthepythonprogramforcountingthecharactersofstringisexecutedandtheresultsare verified.
Aim:
Towriteapythonprogramforreplacingthecharactersofastring.
Algorithm:
Step1:Starttheprogram. Step 2:
Define a string.
Step3:Determinethecharacter'ch'throughwhichspecificcharacterneedtobereplaced. Step 4:
Use replace function to replace specific character with 'ch' character.
Step5:Stoptheprogram.
Program:
string="Onceinabluemoon" ch
= 'o'
#Replacehwithspecificcharacterch string
= string.replace(ch,'h')
print("Stringafterreplacingwithgivencharacter:")
print(string)
Output:
Stringafterreplacingwithgiven character:
Once in a blue mhhn
Result:
Thusthepython programforreplacing thegivencharactersofstringisexecuted
andtheresultsare verified.
60
Aim:
TowriteapythonprogramforconvertinglistintoaSeries.
Algorithm:
Program:
#Tousepandasfirstwehavetoimportpandas import
pandas as pd
#Herepdjustaobjectofpandas
#Defining a List
A=['a','b','c','d','e']
#Convertingintoaseries
df=pd.Series(A)print(df)
Output:
1 a
2 b
3 c
4 d
5 e
dtype: object
Result:
Thusthepythonprogramforconvertinglistintoaseriesisexecuted and the
results are verified.
Aim:
Towriteapythonprogramfortestingwhethernoneoftheelements ofagivenarrayis zero.
Algorithm:
Program:
import numpy as np
#Arraywithoutzerovalue x
= np.array([1, 2, 3, 4,])
print("Original array:")
print(x)
print("Testifnoneoftheelementsofthesaidarrayiszero:")
print(np.all(x))
#Array with zero value
x=np.array([0,1,2,3])
print("Original array:")
print(x)
print("Testifnoneoftheelementsofthesaidarrayiszero:")
print(np.all(x))
Output:
Originalarray:
[1 2 3 4]
Testifnoneoftheelementsofthesaidarrayis zero:
True
Originalarray:
[0 1 2 3]
Testifnoneoftheelementsofthesaidarrayis zero:
False
Result:
Thusthe pythonprogram fortesting whethernoneoftheelementsofagivenarrayiszerois
Aim:
Towriteapythonprogramforgeneratingasimplegraphusingmatplotlib.
Algorithm:
Program:
frommatplotlibimportpyplotasplt
#Plotting to our canvas plt.plot([1,2,3],
[4,5,1])
#Showingwhatweplotted
plt.show()
Output:
Result:
Thusthepythonprogramforgeneratingasimplegraphusingmatplotlibzeroisexecuted and the
results are verified.
Aim:
Towriteapythonprogramforfindingtheexponentsandsolvetrigonometricproblems using
scipy.
Algorithm:
Program:
fromscipyimportspecial a
= special.exp10(3)
print(a)
b=special.exp2(3)
print(b)
c=special.sindg(90)
print(c)
d=special.cosdg(45)
print(d)
Output:
1000.0
8.0
1.0
0.707106781187
Result:
Thusthepythonprogramforfindingtheexponentsandsolvetrigonometricproblemsusing scipy is
executed and the results are verified.
Aim:
TowriteaPythonprogramforcopyingtextfromonefiletoanother.
Algorithm:
Step 1:Start
Step2:Createfilenamedfile.txtandwritesomedatainto it.
Step3:Createafilenamesample.txt tocopythe contentsofthefile
Step4:Thefilefile.txtisopenedusingthe open()functionusingthe fstream.
Step5:Anotherfilesample.txtisopenedusingtheopen()functioninthewritemodeusingthe f1 stream.
Step6:Eachlineinthefileisiteratedoverusingaforloop(intheinputstream). Step 7 : Each
of the iterated lines is written into the output file.
Step8:Stop
Program:
withopen("file.txt")asf:
withopen("sample.txt","w")asf1: for
line in f:
f1.write(line)
Thecontentsoffilenamedfile.txtiscopiedinto sample.txt
Result:
Thusthepythonprogramforcopyingtextfrom onefile toanotheris executedandtheresults
are verified.
Aim:
TowriteaPythonprogramforcommandlinearguments.
Algorithm:
Step1:Start
Step2:Importthepackagesys
Step3:Gettheargumentsincommandlineprompt
Step4:Printthenumberofargumentsinthecommandlinebyusinglen(sys.argv)function Step5:
Print the arguments using str(sys.argv ) function
Step6:Stop
Program:
importsys
print('Numberofarguments:',len(sys.argv),'arguments.')
print('Argument List:',str(sys.argv))
Stepsforexecution:
OpenWindowscommandpromptbytypingcmdinstartupmenu C:\
Users\admin>cd..
C:\Users>cd..
C:\>cd Portable Python 3.2.5.1 C:\
PortablePython3.2.5.1>cdApp
C:\PortablePython3.2.5.1\App>python.execmd.pyarg1arg2arg3
Or
C:\PortablePython3.2.5.1\App>pythoncmd.pyarg1arg2arg3
Output:
Number of arguments: 4 arguments.
ArgumentList:['cmd.py','arg1','arg2','arg3']
Result:
ThusthePythonprogramforcommandlineargumentsisexecutedsuccessfullyandthe output is
verified.
Aim:
TowriteaPythonprogramforfindingthelongestwordsusingfilehandling concepts.
Algorithm:
Step1:Startthe program
Step2:Createatextfilenameitfile.txtandsaveit. Step3:
Open the text file in read mode
Step4:Readthefileandsplitthewordsinthefileseparately. Step4: Find
the word with maximum length
Step5: Print the result.
Step6:Stoptheprogram.
Program:
#Openingfileinreadingmode
file=open("file.txt", 'r')
#Converting in a list
print("Listofwordsinthefile")
words=file.read().split()
print(words)
#Selectingmaximumlengthword
max_len = max(words, key=len)
print("WordwithmaximumLengthis",max_len) for i
in max_len:
iflen(i)==max_len:
print(i)
Output:
Listofwordsin thefile
['hai','this','is','parvathy','how','are','you','all','read','well','all','best','for','university', 'exams.']
WordwithmaximumLengthisuniversity
Result:
ThusthePythonprogramfindingthelongestwordsusingfilehandlingconceptsisexecuted
successfully and the output is verified.
Aim:
TowriteaPythonprogramforfindingdividebyzeroerror.
Algorithm:
Step1:Startthe program
Step2:Takeinputsfromtheuser,twonumbers.
Step 3:Ifthe entered datais not integer,throw anexception.
Step4:Iftheremainderis0,throwdividebyzeroexception. Step
5: If no exception is there, return the result.
Step6:Stopthe program.
Program:
try:
num1 = int(input("Enter First Number: "))
num2=int(input("EnterSecondNumber:"))
result = num1 / num2
print(result)
exceptValueErrorase:
print("InvalidInputPleaseInputInteger...") except
ZeroDivisionError as e:
print(e)
Output:
EnterFirstNumber: 12.5
InvalidInputPleaseInput Integer...
Result:
ThusthePythonprogramforfindingdividebyzeroerrorisexecutedsuccessfullyandthe output is
verified.
Aim:
TowriteaPythonprogramforvalidatingvoter’s age.
Algorithm:
Step1:Startthe program
Step2:Accepttheageofthe person.
Step3:Ifageisgreaterthanorequalto18,thendisplay'Youareeligibletovote'. Step 4: If
age is less than 18, then display 'You are not eligible to vote'.
Step5:Iftheentereddataisnotinteger,throwanexceptionvalueerror. Step 6: :
If the entered data is not proper, throw an IOError exception Step 7: If no
exception is there, return the result.
Step8:Stopthe program.
Program:
def main():
#singletrystatementcanhavemultipleexceptstatements. try:
age=int(input("Enteryourage")) if
age>18:
print("'Youareeligibletovote'")
else:
print("'Youarenoteligibletovote'") except
ValueError:
print("agemustbeavalidnumber")
except IOError:
print("Entercorrectvalue")
#genericexceptclause,whichhandlesanyexception.
except:
print("AnErroroccured")
main()
Enteryourage35
Eligible to vote
Result:
ThusthePythonprogramforvalidatingvoter’sageisexecutedsuccessfullyandtheoutputis verified.
Aim:
Towriteapythonprogramforstudentmarkrangevalidation
Algorithm:
Program:
def main():
try:
mark=int(input("Enteryourmark:"))
if(mark>=50 and mark<101):
print("Youhavepassed")
else:
print("Youhavefailed")
except ValueError:
print("Itmustbeavalidnumber") except
IOError:
print("Entercorrectvalidnumber")
except:
print("anerroroccured")
main()
Result:
Thusthepythonprogramforstudentmarkrangevalidationisexecutedandverified.
Pygame:
Stepsforinstallingpygamepackage:
1. OpenWindowscommandpromptbytypingcmdinstartupmenu
2. C:\Users\admin>cd..
3. C:\Users>cd..
4. C:\>cdPortablePython3.2.5.1
5. C:\PortablePython3.2.5.1>py-mpipinstall-Upygame–user
OnlineExecutionProcedure:
1. Copythisurl:https://trinket.io/features/pygametoyourbrowserandopen pygame
interpreter
2. Removethesourcecodeinmain.pyandcopythebelowsourcecode to main.py
3. ClicktheRun buttonto execute.
Aim:
TowriteaPythonprogramtosimulatebouncingballinpygame.
Algorithm:
Step1:Start
Step2:Importthenecessarypackages
Step3:Initializetheheight,widthandspeedinwhichtheballbounce Step4:Set
Step4:Movetheballfromlefttoright Step5:
Stop
Program:
importsys,pygame
pygame.init()
size=width,height=700,300
speed = [1, 1]
background=255,255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball=pygame.image.load("'C:\\Users\\parvathys\\Downloads\\ball1.png") ballrect
= ball.get_rect()
while1:
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:sys.exit()
ifballrect.left<0orballrect.right>width: speed[0] =
-speed[0]
ifballrect.top<0orballrect.bottom>height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball,ballrect)
pygame.display.flip()
Output:
Result:
Aim:
TowriteaPythonprogramtosimulatecarraceinpygame.
Algorithm:
Step1:Start
Step2:Importthenecessarypackages
Step3:Initializetheheight,widthofthescreenandspeedinwhichthecarcanrace. Step4:Set the
screen mode
Step5:Loadtherequiedimageslikeracingbeast,logo,fourdifferentcarimages Step4:
Move the car on the race track
Step5:Stop
Program:
importpygame
pygame.init()#initializesthePygame
frompygame.localsimport*#importallmodulesfromPygame screen
= pygame.display.set_mode((798,1000))
#changing title of the game window
pygame.display.set_caption('Racing Beast')
#changing the logo
logo=pygame.image.load('C:\\Users\\parvathys\\Downloads\\cargame/logo.png')
pygame.display.set_icon(logo)
#definingourgameloopfunction def
gameloop():
#settingbackgroundimage
bg=pygame.image.load(''C:\\Users\\parvathys\\Downloads\\cargame/bg.png') #
setting our player
maincar=pygame.image.load(''C:\\Users\\parvathys\\Downloads\\cargame\car.png')
maincarX = 100
maincarY=495
maincarX_change=0
maincarY_change=0
Result:
ThusthePythonprogramtosimulatecarraceusingpygameisexecutedsuccessfullyandthe output is
verified.
Ex:7.1
REVERSE OF A STRING
Date:
Aim:
To write a python program for reversing a string.
Algorithm:
Step 1: Start the program.
Step 2: Read the value of a string value by using function call reversed_string.
Step 3: if len(text)==1 return text.
Step 4: else return reversed_string(text[1:])+text[:1].
Step 5: Print a
Step 6: Stop the program
Program:
def reversed_string(text):
if len(text) == 1:
return text
return reversed_string(text[1:])+text[:1]
a=reversed_string("Hello, World!")
print(a)
Output:
dlroW,olleH
Result:Thus the python program for reversing a.string is executed and the results are verified.
Ex:7.2
PALINDROME OF A STRING
Date:
Aim:
To write a python program for palindrome of a string.
Algorithm:
Step 1: Start the program.
Step 2: Read the value of a string value by using input method.
Step 3: if string==string[::-1],print “the string is palindrome”.
Step 4: else print “ Not a palindrome ”.
Step 5: Stop the program
Program:
string=input(("Enter a string:"))
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")
Output:
Enter a string: madam
The string is a palindrome
Enter a string: nice
Not a palindrome
Result: Thus the python program for palindrome of a string is executed and the results are verified.
Ex:8.1
Date: CONVERT LIST IN TO A SERIES USING PANDAS
Aim:
To write a python program for converting list into a Series.
Algorithm:
Program:
Output:
1 a
2 b
3 c
4 d
5 e
dtype: object
Result: Thus the python program for converting list into a series is executed and the results are
verified.
Ex:8.2
FINDING THE ELEMENTS OF A GIVEN ARRAY IS ZERO USING
Date: NUMPY
Aim:
To write a python program for testing whether none of the elements of a given array is zero.
Algorithm:
Program:
import numpy as np
#Array without zero value
x = np.array([1, 2, 3, 4,])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
#Array with zero value
x=np.array([0,1,2,3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
Output:
Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero:
True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero:
False
Result:
Thus the python program for testing whether none of the elements of a given array is zero is
executed and the results are verified.
Ex:9.1
Date: COPY TEXT FROM ONE FILE TO ANOTHER
Aim:
To write a Python program for copying text from one file to another.
Algorithm:
Step 1: Start
Step 2: Create file named file.txt and write some data into it.
Step 3: Create a file name sample.txt to copy the contents of the file
Step 4: The file file.txt is opened using the open() function using the f stream.
Step 5: Another file sample.txt is opened using the open() function in the write mode using the
f1 stream.
Step 6: Each line in the file is iterated over using a for loop (in the input stream).
Step 7: Each of the iterated lines is written into the output file.
Step 8: Stop
Program:
with open("file.txt")as f:
with open("sample.txt","w")as f1:
for line in f:
f1.write(line)
Output:
Result: Thus the python program for copying text from one file to another is executed and the results
are verified.
Ex:9.2
Date: COMMAND LINE ARGUMENTS (WORDCOUNT)
Aim:
To write a Python program for command line arguments.
Algorithm:
Step 1: Start
Step 2: import the package sys
Step 3: Get the arguments in command line prompt
Step 4: Print the number of arguments in the command line by using len(sys.argv)function
Step 5: Print the arguments using str(sys.argv ) function
Step 6: Stop
Program:
import sys
print('Number of arguments:',len(sys.argv),'arguments.')
print('Argument List:',str(sys.argv))
Output:
Number of arguments: 4 arguments.
Argument List: ['cmd.py','arg1','arg2','arg3']
Result: Thus the Python program for command line arguments is executed successfully and the
output is verified.
Ex:10.1
DIVIDE BY ZERO ERROR–EXCEPTION HANDING
Date:
Aim:
To write a Python program for finding divide by zero error.
Algorithm:
Program:
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number:"))
result = num1 / num2
print(result)
except Value Error as e:
print("Invalid Input Please Input Integer...")
except Zero Division Error as e:
print(e)
Output:
Enter First Number: 12.5
Invalid Input Please Input Integer...
Result: Thus the Python program for finding divide by zero error is executed successfully and the
output is verified.
Ex:10.2
VOTER’S AGE VALIDITY
Date:
Aim:
To write a Python program for validating voter’s age.
Algorithm:
Program:
def main():
#single try statement can have multiple except statements.
try:
age=int(input("Enter your age"))
if age>18:
print("'You are eligible to vote'")
else:
print("'You are not eligible to vote'")
except Value Error:
print("age must be a valid number")
except IOError:
print("Enter correct value")
#generic except clause, which handles any exception.
except:
print("An Error occured")
main()
Output:
Enter your age 20.3
age must be a valid number
Result: Thus the Python program for validating voter’s age is executed successfully and the output
is verified.
Ex:10.2
STUDENT MARK RANGE VALIDATION
Date:
Aim:
To write a python program for student mark range validation
Algorithm:
Program:
def main():
try:
mark=int(input("Enter your mark:"))
if(mark>=50 and mark<101):
print("You have passed")
else:
print("You have failed")
except ValueError:
print("It must be a valid number")
except IOError:
print("Enter correct valid number")
except:
print("an error occured")
main()
Output:
Enter your mark:50
You have passed
Enter your mark:r
It must be a valid number
Enter your mark:0
You have failed
Result: Thus the python program for student mark range validation is executed and verified.