Python Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 86

Listof experiments:

1. Identificationand solving of simple reallife or scientific or technical problems, and


developingflow chartsforthesame.(ElectricityBilling,Retailshopbilling,Sin series,weight
ofamotorbike, Weight ofa steelbar,computeElectrical Currentin ThreePhaseACCircuit, etc.)
2. Pythonprogrammingusingsimplestatementsandexpressions(exchangethevalues of
twovariables,circulatethevaluesofnvariables,distancebetweentwopoints).
3. Scientific problems using Conditionals and Iterative loops. (Number series,
NumberPatterns,pyramidpattern)4.Implementingreal-time/technicalapplicationsusing
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,
componentsofanautomobile,Elementsofacivilstructure,etc.-
operationsofSets&Dictionaries)
6. ImplementingprogramsusingFunctions.(Factorial,largestnumberin alist,areaofshape)
7. ImplementingprogramsusingStrings.(reverse,palindrome,charactercount,replacing
characters)
8. ImplementingprogramsusingwrittenmodulesandPythonStandardLibraries(pandas,
numpy. Matplotlib, scipy)
9. Implementingreal-time/technicalapplicationsusingFilehandling.(copyfromonefileto
another, word count, longest word)
10. Implementingreal-time/technicalapplicationsusingExceptionhandling.(dividebyzero
error, voter’s age validity, student mark range validation)
11. ExploringPygame tool.
12. DevelopingagameactivityusingPygame likebouncingball, car raceetc.
ExpNo:1)a.FlowchartforElectricityBill Calculation
Aim:
TodrawtheflowchartforElectricity billcalculation withthefollowingratesfor its
customers:-

No. of unit consumed Charges/unit(RM)


1-200 2.50
201 -500 3.50
over501 5.00

Draw aflowcharttocalculatedthe netamountof thebill foreachconsumerandprint it.

Algorithm :

Step 1 : Start
Step 2 : Read the unit values
Step3 :Check 1<=unit<=200
Thencalculatetotal_charges=unit*2.50
Step 4 : Check 201<=unit<=500
Thencalculatetotal_charges=unit*3.50
Step 5 : Check unit>500
Thencalculatetotal_charges=unit*5.0
Step 6 : print total_charges
Step 7 : Stop
Flowchart:
ExpNo :1) b.Flowchart forcalculation ofgross salaryofan employee
Aim:
Todraw aflowchart forcalculating thegross salaryofan employee

Algorithm :
Step 1: Start
Step2:Readbasicsalaryofan employee
Step3: Usethe formulahra=basic_salary* 0.2and da=basic_salary *0.7.
Step4:Calculategrosssalarybyusingformulagross_salary=basic_salary+hra+da. Step 6:
Print gross salary.
Step 7: End
Flowchart:
ExpNo:1)c. FlowchartforMovieticket booking

Aim:
Todraw aflowchart for booking amovie ticket.

Algorithm :
Step 1: Start
Step2:Readandselecttheshowtimings Step
3: Check if tickets==available
Thenselect thetypeofa movie
else:
goto Step3
Step4:Selectamovietype Step
5: Select the seats
Step 6: Chooseapayment option
Step7:Makepaymentandgetthetickets Step
8: Stop
Flowchart:

START

STOP
ExpNo:1)d.FlowchartforStudentgradeprinting

Aim:
Todrawa flowchartfor studentgradeprinting.

Algorithm :
Step 1: Start
Step 2: Read score
Step3:ifscore>90:
printgradeis“O” Step
4: if score>80:
Printgradeis“A+”
Step 5: if score>70:
Printgradeis“A” Step
6: if score>60:
Printgradeis“B+”
Step 7: if score>50:
Printgradeis“B” Step
8: if score <50:
Print “Fail”
Step 9: Stop
Flowchart:

90

>80

>70

>60

>50
ExpNo :1) e.Flowchart forcollegeadmission

Aim:
Todrawa flowchartforcollegeadmission

Algorithm :
Step 1: Start
Step2:Getenquiryform Step
3: Check eligibility
Step4:Uploadrequireddocuments
Step5:Checkifeligible:thengotoStep6elsegotoStep4 Step
6:Submit registration fees
Fill admission form
Gettheadmissionslip
Step 7: Stop
Flowchart:
ExpNo :1) f. Flowchartforretailshop bill calculation

Aim:
Todrawa flowchartforretailbill preparation

Algorithm :
Step 1: Start
Step 2: Read item name
Step 3: Read price per unit
Step4:ReadNoofQuantity
Step5:ComputeTotalcost=Quantity*priceperunit Step
6: Display total
Step7:Read payment
Step 8: Compute paychange=payment-Totalcost
Step9:Displaytheitems,paymentandpaychange
Step 10: Stop
Flowchart:
ExpNo :1)g.Flowchart forcomputing sin series

Aim:
Todrawaflowchart for computingsin series

Algorithm :
Step1:Takeinthevalueofxindegreesandthenumberoftermsandstoreitinseparate variables.
Step2:Pass thesevalues tothesine functionas arguments.
Step 3: Defineasine function and using aforloop, first convert degrees to radians.
Step4:Thenusethesineformulaexpansionandaddeachtermtothesumvariable. Step 5:
Then print the final sum of the expansion.
Step 6: Stop
Flowchart:
ExpNo:1)h. Flowchartforcalculating theweight ofa motorbike

Aim:
Todrawa flowchartforweightofa motorbike.

Algorithm :
Step 1:
StartStep2:Read
D,L
Step3:Computew=D**2L/162 Step
4: Print w
Step 5: Stop

Flowchart:

START

READ D,L

COMPUTEW=D**2*L/162

DISPLAYW

STOP
ExpNo:1)i. Flowchartforcalculating theweight ofa Steelbar

Aim:
Todrawaflowchartfor weightofasteel bar

Algorithm :
Step 1: Start
Step2:Read LBS
Step3:Computew=LBS/2.2046 Step
4: Print w
Step 5: Stop

Flowchart:

START

READ LBS

COMPUTEW=LBS/2.2046

DISPLAYW

STOP
ExpNo:1)j.FlowchartforcalculatingthecomputeElectricalCurrentinThreePhase AC
Circuit

Aim:
Todrawaflowchartfor computeElectricalCurrentinThreePhaseAC Circuit
Algorithm :
Step 1: Start
Step2:Read kva,voltage
Step3:Computecurrent=kva/voltage
Step 4: Print current
Step 5: Stop

Flowchart:

START

READKVA,
Voltage

COMPUTECurrent=KVA/Voltage

DISPLAY
Current

STOP

Result:Thustheflowchartsweresuccessfully drawn.
Ex.2.Python programsusing simplestatements and expressions

Aim:
Towritepythonprograms using simplestatements and expressions.
2(a).Exchangethe value oftwo variables

Algorithm:

STEP1:ReadthevaluesofPandQ
STEP 2: temp = P
STEP 3:P =Q
STEP 4: temp = P
STEP5:PRINTP,Q

Program:
P=int(input("PleaseentervalueforP: "))
Q=int(input("PleaseentervalueforQ:"))
temp= P
P =Q
Q =temp
print ("The Value of P after swapping: ", P)
print("TheValue of Qafterswapping: ", Q)

Output:

Please entervalue for P: 5


PleaseentervalueforQ:7
TheValue of P afterswapping:7
TheValue of Qafter swapping:5
2(b)Circulate‘n’valuesAlgorit
hm:
STEP 1: Read the values to be circulated in a list
STEP2:Readthenumberoftimesofshiftinginn
STEP 3:Using list slicing, perform rotationSTEP
4: Print (list[n:]+list[:n])
STEP 5: Stop

Program:
list=[10,20,30,40,50]
n=2
print(list[n:]+list[:n])

Output:
[30,40, 50, 10, 20]

2(c)Distancebetweentwo points

Algorithm:

STEP1:Read thevaluesofx1,x2and y1,y2


STEP2:Importmathmoduletocalculatethesquareroot STEP
3:Compute the distance using the formula
STEP4:Usingtheformula,findsquarerootof(((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2)) STEP
5: Print the result
STEP 6: Stop
Program:

importmath
p1 = [4, 0]
p2 =[6, 6]
distance=math.sqrt(((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2))
print(distance)

Output:
6.324555320336759

2(d)CalculatetheArea of a Triangle

Algorithm:
STEP1:Readthevaluesofthreesidesofatriangle STEP 2:
Calculate ‘s’ value
STEP3:Calculatetheareausingtheformula(s*(s-a)*(s-b)*(s-c)) STEP 4:
Find the square root of the result
STEP5:Printtheresult STEP
6: Stop

Program:
a=float(input('Enter firstside: '))
b=float(input('Entersecondside: '))
c=float(input('Enterthirdside:')) s
= (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('Theareaofthetriangleis:',area)
Output:
Enter first side: 5
Entersecondside:4
Enter third side: 2
Theareaof thetriangle is:3.799671038392666

2(e) Convert Kilometers to Miles

Algorithm:

STEP1:Readthevaluesofdistanceinkilometers STEP 2:
Read the conversion factor
STEP3:Calculatethemilesusingkilometers*conv_fac STEP
4: Print the result
STEP 5: Stop

Program:
kilometers=float(input("Entervalueinkilometers:"))
conv_fac = 0.621371
miles = kilometers * conv_fac
print('kilometersisequalto:',miles,'miles')

Output:
Enter value in kilometers: 20
kilometersisequalto:12.42742miles
2(f)ConvertCelsiusToFahrenheit Algorithm:
STEP1:Readthevalues oftemperaturein celcius
STEP2:Calculatethetemperatureusing(celsius*1.8)+32 STEP 4:
Print the result
STEP 5: Stop

Program:
celsius=float(input("Enterthetemperatureincelcius:"))
fahrenheit = (celsius * 1.8) + 32
print('Celsius isequal to', fahrenheit)

Output:
Enterthetemperatureincelcius:3.5
Celsius is equal to38.3

2(g)CalculationofSimpleInterest andCompound Interest

Algorithm:
STEP1:Readthevaluesofprincipalamount,noofyearsandrateofinterest STEP 2:
Calculate the simple interest using (principal*time*rate)/100
STEP3:Calculatethecompoundinterestusingprincipal*((1+rate/100)**time -1) STEP 4:
Display the two values
STEP5:Stop Program:
principal=float(input('Enteramount:'))
time = float(input('Enter time: '))
rate = float(input('Enter rate: '))
simple_interest=(principal*time*rate)/100
compound_interest=principal*((1+rate/100)**time-1)
print('Simple interest is:',simple_interest)
print('Compound interest is:' , compound_interest)

Output:
Enteramount:20000
Entertime:5
Enterrate:6.7
Simpleinterestis:6700.0
Compoundinterestis:7659.994714602134

2(h)CalculationofSimpleInterest andCompound Interest

Algorithm:
STEP1:Read thevaluestwo numbers
STEP2:Performallarithmeticoperationsusingappropriateoperators
STEP 3: Use print statements to print the calculated values
STEP4:Displaytheresults
STEP 5: Stop

Program:
num1 = float(input('Enter first number: '))
num2=float(input('Entersecondnumber:'))
sum1=num1+num2
diff1=num1-num2
prod1=num1*num2
div1=num1/num2
rem1=num1%num2
floordiv1=num1//num2
exp1=num1**num2
print("Sum is:", sum1)
print("Differenceis:",diff1)
print("Product is:", prod1)
print("Quotient is:", div1)
print("Reminder is:", rem1)
print("Floordivisionresultis:",floordiv1)
print("Exponent is:", exp1)
Output:
Enter first number: 2
Entersecondnumber:3
Sum is: 5.0
Differenceis:-1.0
Productis:6.0
Quotient is: 0.6666666666666666
Reminderis:2.0
Floordivisionresultis:0.0
Exponent is: 8.0

2(i)Display Random value in python

Algorithm:
STEP1:Read thevaluesin n
STEP 2: Using import, import random in python
STEP3:Useprintstatements,printtherandomvalue
STEP 4: Display the results
STEP 5: Stop
Program:
importrandom
n=random.random()
print(n)
Output:
0.8496781335157302
Result:
Thus,theprogramforsimplepythonstatementsandexpressionswereexecutedandthe output
is verified.
Ex.3.ScientificproblemsusingConditionalsandIterative loops

Aim:
Towritepythonprogramsusingconditionalstatementsand loops.

3(a).Biggestofthreenumbers
Algorithm:
Step1: Askthe userto enterthreeinteger values.
Step2:Readthethreeintegervaluesinnum1,num2,andnum3. Step 3:
Check if num1 is greater than num2.
Iftrue, then check if num1 is greaterthan num3.
Iftrue, thenprint ‘num1’asthe greatest number.
Step4:Iffalse,thenprint‘num3’asthegreatestnumber.
Iffalse, thencheck ifnum2 isgreaterthan num3.
I f true, then print ‘num2’ as the greatest number.
Iffalse, then print ‘num3’asthe greatest number
Step5:Stop
Program:
num1 = float(input("Enter first number: "))
num2=float(input("Entersecondnumber:"))
num3 = float(input("Enter third number: "))
if(num1>num2)and(num1>num3): largest =
num1
elif(num2>num1)and(num2>num3): largest
= num2
else:
largest=num3
print("Thelargestnumber is",largest)
Output:
Enter first number: 55
Enter second number: 64
Enter third number: 34
Thelargestnumberis64.0

3(b)Sumofdigitsofanumber
Algorithm:
Step1: Usermust firstenterthevalueandstoreitin a variable.
Step2:Thewhileloopisusedandthelastdigitofthenumberisobtainedbyusingthe modulus
operator.
Step3:Thedigitisaddedtoanothervariableeachtimetheloopisexecuted. Step 4:
This loop terminates when the value of the number is 0.
Step5:Thetotalsumofthenumberisthenprinted. Step 6:
Stop

Program:
n=int(input("Enteranumber:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("Thetotal sum of digits is:",tot)

Output:
Entera number:456
Thetotal sumof digitsis: 15
3(c)PerfectNumberor Not

Algorithm:
Step 1: Start
Step2:Readn
Step 3: Initialize s=0
Step4: fori=1 ton do
if(n%i)==0,then
s=s+i
Step 5: if s==n
thenPrint"GivenNumberisPerfectNumber".GotoStep7 Step 6:
Print "Given Number is Not a Perfect Number"
Step 7: Stop

Program:
Number=int(input("PleaseEnter anyNumber: "))
Sum = 0
foriinrange(1,Number):
if(Number % i == 0):
Sum = Sum + i
if(Sum ==Number):
print("%disaPerfectNumber"%Number) else:
print("%d isnot aPerfect Number"%Number)

Output:
PleaseEnteranyNumber:6 6
is a Perfect Number
3(d)PrintingFibonacciSeries
Algorithm:
Step 1: Start
Step2:Declarevariables i,t1,t2, sum
Step3:Initializethevariables,t1=0,t2=1,and sum=0
Step4:EnterthenumberoftermsofFibonacciseriestobeprinted Step 5:
Print First two terms of series
Step 6: Useloop forthe following steps
-> sum=t1+t3
-> t1=t2
-> t2=sum
->increasevalue ofi each time by 1
->printthevalueofshow Step
7: Stop

Program:
n=int(input("Enterthevalueof'n':")) t1 =
0
t2 = 1
sum = 0
count =
1print("FibonacciSeries:")
while(count <= n):
print(sum, end = "") count
+= 1
t1 =
t2t2=su
m
sum = t1 + t2
Output:

Enterthevalueof'n':7 Fibonacci
Series:
0112358
3(e) PrintDifferent Patterns in python

Algorithm:
STEP1:Readthe rowandcolumn values
STEP2:Usingnestedloops,printtherequiredpattern
STEP 3: Stop
Pattern1:
num_rows=int(input("Enterthenumberofrows")); for i
in range(0, num_rows):
forjinrange(0,num_rows-i-1):
print(end="")
forjinrange(0,i+1):
print("*", end="")
print()
Output:
Enterthenumberofrows5
*
**
***
****
*****
Pattern2:
num_rows=int(input("Enterthenumberofrows")); k =
1
fori in range(0, num_rows):
forj in range(0, k):
print("*",end="")
k=k+1
print()

Output:
Enterthenumberofrows5
*
**
***
****
*****

Pattern3:

num_rows=int(input("Enterthenumberofrows")); k =
8
foriinrange(0,num_rows): for
j in range(0, k):
print(end="")
k =k-2
forjinrange(0,i+1):
print("* ", end="")
print()
Output:

Enterthenumberofrows5
*
**
***
****
*****

Pattern4:
num_rows=int(input("Pleaseenterthenumberofrows")); for
i in range(num_rows,0,-1):
forjinrange(0,num_rows-i):
print(end="")
for j in range(0,i):
print("* ", end="")
print()

Output:
Pleaseenterthenumber of rows5
*****
****
***
**
*
Pattern5:
rows=6
foriinrange(rows): for
j in range(i):
print(i,end='')
print('')
Output:

1
22
333
4444
55555

3(f)PascalsTriangle
Algorithm:
STEP 1: Read the number of rows to be printed
STEP 2: Using nested loop, print the spaces needed
STEP3:Usingbinomialcoefficient,printthevalues
STEP 4: Stop
Program:
n=int(input("Entertherows:")) for
i in range(1, n+1):
forjinrange(0,n-i+1):
print('', end='')
C =1
for j in range(1,
i+1):print('',C,sep='',end
='')
C=C*(i-j)//j
print()
Output:

Entertherows:5
1
11
121
1331
14641
3(g)AlphabetPatternsinPython
Algorithm:

STEP1:Readthe rowandcolumn values


STEP2:Usingnestedloops,printtherequiredpattern
STEP 3: Stop
Pattern1:
foriinrange(65,70): #
inner loop
forjinrange(65,i+1):
print(chr(j),end="")
print()

Output:
A
ABABC
ABCD
ABCDE
Pattern2:
foriinrange(65,70):
k=i
#Innerloop
for j in range(65,i+1):
print(chr(k),end="")
k=k+1
print()

Output:
ABC
CDE
DEFG
EFGHI

Pattern3:
str=input("Enteryourname:")
for i in range(0,len(str)):
for j in range(0,i+1):
print(str[j],end="")
print()
Enteryourname:Ajin
A
Aj
Aji
Ajin
Pattern4:
n=int(input("Entertherow"))
for i in range(n):
#printingspaces
for j in range(i):
print('', end='')
#printingalphabet
forjinrange(2*(n-i)-1):
print(chr(65+j),end='')
print()

Output:
Entertherow5
ABCDEFGHI
ABCDEFG
ABCDE
ABC
A

Pattern5:
n =5

#upwardpyramid
for i in range(n):
forjinrange(n-i-1): print('',
end='')
for j in range(2 * i + 1):
print(chr(65+j),end='')
print()
fori in range(n-1):
forjinrange(i+1):
print('', end='')
forj in range(2*(n-i- 1)-1):
print(chr(65+j),end='')
print()

Output:

A
ABC
ABCDE
ABCDEFG
ABCDEFGHI
ABCDEFG
ABCDE
ABC
A

3(h)PrimeNumbers inarange

Algorithm:

Step 1: Start
Step2:Read lowerandupper range
Step3:Usingaforloop,iterateonallthenumbersintherange Step 4 :
For each number, check if its prime or not
Step5:Ifthenumberisprime,print Else
skip
Step 6 : Stop
Program:
lower=900
upper=1000
print("Primenumbersbetween",lower,"and",upper,"are:") for
num in range(lower, upper + 1):
if num >1:
foriinrange(2,num): if
(num % i) == 0:
break
else:
print(num)

Output:
Primenumbersbetween900and1000are:
907
911
919
929
937
941
947
953
967
971
977
983
991
997
Result:
Thus,theprogramusing conditionalsand loopshasbeenexecuted andverified.
Ex.4.Implementingreal-time/technicalapplicationsusingLists,Tuples

Aim:
Towritepython programsusing Lists and Tuples.
DisplaytheBookdetailsusingalist
Algorithm:
Step 1: Start
Step2:Createanemptylist
Step3:Print themenuand readthechoice
Step4:Ifthechoiceis1,readthebooknamefromtheuserandappendtolist Step 5: If
the choice is 2, print the books in the list
Step 6: Stop

Program:
my_book=[]
ch='y'
while(ch=='y'):
print('''
1. AddNewBook
2. DisplayBooks
''')
choice=int(input("Enterchoice:"))
if(choice==1):
book=input("Enterthenameofthebook:")
my_book.append(book)
elif(choice==2):
foriinmy_book: print(i)
else:
print("Invalidchoice!")
ch=input("Doyouwanttocontinue...?") print("Bye!")
Output:
1. AddNewBook
2. DisplayBooks
Enterchoice:1
Enterthenameofthebook:Pythonprogramming Do
you want to continue...?y

AutomobileComponentsusingLists
Algorithm:
Step 1: Start
Step2:Createalistofcomponentsofautomobile Step
3: Print the menu and read the choice
Step4:Ifthechoiceis1,displaythemaincomponentsinthelist Step 5:
If the choice is 2, print the components of list
Step6:If thechoiceis3,Print thetotal components
Step7:Ifthechoiceis4,arrangethecomponentsinorder Step :
Stop
Program:
components=['RADIATOR','AC
COMPRESSOR','BATTERY','ALTERNATOR','AXLE','BRAKES','SHOCK
ABSORBERS','TRANSMISSION','FUEL TANK']
components1=['CATALYTICCONVERTER','MUFFLER','TAILPIPE']
ch='y'
while(ch=='y'):
print('''
1. DisplayMainComponents
2. DisplayAll Components
3. Total Components
4. ComponentsinAlphabeticalOrder
''')
choice=int(input("Enterchoice:")) if(choice==1):
print("TheMaincomponentsare:")
print(components)

elif(choice==2):
print("The components are:")
print(components+components1)
elif(choice==3):
print("Thecomponents are:")
print("Main Components:",len(components))
print("OtherComponents:",len(components1))
elif(choice==4):
print("Thecomponentsinalphabeticalorderare:") components.sort()
print("MainComponents:",components)
print("Sorted order")

else:
print("Invalid
choice!")ch=input("Doyouwanttocontin
ue...?")
print("Bye!")

Output:
1. DisplayMainComponents
2. DisplayAll Components
3. Total Components
4. ComponentsinAlphabeticalOrder
Enterchoice:4
Thecomponentsinalphabeticalorder are:
Main Components: ['AC COMPRESSOR', 'ALTERNATOR', 'AXLE', 'BATTERY',
'BRAKES','FUELTANK','RADIATOR','SHOCKABSORBERS','TRANSMISSION']
Sortedorder
Doyou wantto continue...?

MaterialsofConstructionusingTuple
Algorithm:
Step 1: Start
Step2:Createatupleofconstructionmaterials Step
3: Print the menu and read the choice
Step4:If thechoiceis 1,displaythe materialsinthe tuple
Step5:Ifthechoiceis2,displaythetypesofmaterialsinthetuple Step 6: If
the choice is 3, Print the reverse order of materials
Step7:If thechoiceis4,print thetotal number
Step8:Ifthechoiceis5,printanymaterialatrandom Step 9:
Stop

Program:

types=('Artificial Materials','Natural Materials')


material=('Cement','Aggregates','StonesandRocks','MudandClay',
'Concrete','Bricks','Glass','Plastic','Structural Steel',
'Foam','Fabric','Thatch','Timber and Wood','Tiles (Ceramics)',
'Electrical Items')
ch='y'
while(ch=='y'):
print('''
1. DisplayMaterials
2. Displaytypes ofMaterials
3. DisplayReverseorder of materials
4. CountofNeededmaterials
5. Chooseamaterialatrandom
''')
choice=int(input("Enterchoice:"))
if(choice==1):
print(material)

elif(choice==2):
print(types)
elif(choice==3):
print(material[::-1])
elif(choice==4):
print(len(material))
elif(choice==5):
print(material[5])

else:
print("Invalid
choice!")ch=input("Doyouwanttocontin
ue...?")
print("Bye!")

Output:

1. DisplayMaterials
2. Displaytypes ofMaterials
3. DisplayReverseorder of materials
4. CountofNeededmaterials
5. Chooseamaterialatrandom
Enterchoice:4
15
Doyou wantto continue...?y
1. DisplayMaterials
2. Displaytypes ofMaterials
3. DisplayReverseorder of materials
4. CountofNeededmaterials
5. Chooseamaterialatrandom

Enterchoice:5
Bricks
Doyou wantto continue...?

List Operations

Algorithm:

Step 1: Start
Step2: Createalistof items
Step3:Printtheoutputforeach ofthe operations
Indexing,extend,pop,slicing,clear,removeanddel Step
4: Stop

Program:
numbers=[11,22, 33, 100, 200, 300]
print(numbers[0])
print(numbers[5])
print(numbers[1])
print(numbers[-1])
print(numbers[-3])
print(numbers[-4])
n_list=["hello","world","hi","bye"]
print(n_list[1:3])
print(n_list[:3])
print(n_list[3:])
print(n_list[:])
n_list.insert(3, 100)
print(n_list)
n_list.append(99)
print(n_list)
n_list.extend([11,22])
print(n_list)
n_list[2]=100
print(n_list)
n_list[1:4] =[11,22, 33]
print(n_list)
deln_list[2:4]
print(n_list)
ch_list=['A', 'F','B', 'Z', 'O', 'L']
ch_list.remove('B')
print(ch_list)
ch_list.pop(1)
print(ch_list)
ch_list.clear()
print(ch_list)
Output:
11
300
22
300
100
33
['world', 'hi']
['hello','world','hi']
['bye']
['hello','world','hi','bye']
['hello','world','hi',100,'bye']
['hello','world','hi', 100,'bye', 99]
['hello','world', 'hi',100, 'bye',99, 11, 22]
['hello','world',100,100,'bye',99,11, 22]
['hello',11, 22,33, 'bye',99, 11, 22]
['hello',11,'bye',99,11,22] ['A',
'F', 'Z', 'O', 'L']
['A','Z','O','L'] []

ListOperations
Algorithm:
Step 1: Start
Step2: Createatupleof items
Step3:Printtheoutputforeach ofthe operations
Type,del,sum,max,min,sorted,packing,slicing,indexing,membership Step 4:
Stop

Program:
type1=(1,3,4,5,'test') print
(type1)
tuple1=('a', 'b', 1,3, [5,'x', 'y', 'z'])
print(tuple1[0])
print(tuple1[4][1])
print(tuple1[-1])
print(tuple1[2:5])
Tuple1=(1,3, 4)
Tuple2=('red’,’green’,‘blue')
Tuple3 = (Tuple1, Tuple2)
print (Tuple3)
del(Tuple2)
print (1 in Tuple1)
print (5 in Tuple1)
print(max(Tuple1))
print(sum(Tuple1))
print(sorted(Tuple1))
person = ("Sai", '5 ft', "Actor")
(name,height,profession)=person
print(name)
print(height)
print(profession)

Output:
(1, 3,4, 5, 'test')
a
x
[5,'x', 'y', 'z']
(1,3,[5, 'x', 'y', 'z'])
((1,3,4),'red",’green’,"blue') True
False
4
8
[1, 3,4]
Sai
5 ft
Actor
Result:Thus,theapplicationsandoperationsoflist,tuplehasbeen executed.
5. Implementingreal-time/technicalapplicationsusingSets, Dictionaries.

Ex.No. 5(a) ComponentsofanautomobileusingSetOperations

AIM:
Towriteapythonprogramfortoadd,removeandpoptheautomobilecomponentsusing python
set operations.

ALGORITHM:

1. Startthe Program
2. Initializetheemptydictionarywithcomponents{}
3. Printthetype ofcomponents {}so that dictionarytypewill beprinted.
4. Initializethecomponentsas set()
5. Addthevaluesofautomobilecomponentsto the set.
6. Gettheextracomponenttobeaddedto thesetas input.
7. Addtheextra componentthroughadd() method.
8. Printtheset as components
9. Removeany onecomponentfrom thesetusing pop() method.
10. Printtheupdated components.
11. Stop theProgram.

PROGRAM:
components={}
print(type(components))
components=set()
print(type(components))
components={"Clutch","GearBox","Frontdeadaxle","Engine","Reardrive
axle","Differential"}
print(components)
b=input("Enterthecomponentstobeadded")
components.add(b)
print("Componentsofautomobileafteraddinganelementinset")
print(components)
print("RemovingtheoneComponent")
components.pop()
print("UpdatedComponentsafterremovinganelementisset")
print(components)

OUTPUT:
<class'dict'>
<class'set'>
{'GearBox','Frontdeadaxle','Engine','Clutch','Differential','Reardriveaxle'} Enter the
components to be addedAxle
Componentsofautomobileafter addingan elementin set
{'GearBox','Frontdeadaxle','Engine','Clutch','Differential','Reardriveaxle','Axle'}
Removing the one Component
UpdatedComponentsafterremovinganelementis set
{'Frontdeadaxle','Engine','Clutch','Differential', 'Reardriveaxle','Axle'}

Ex.No 5.(b) Elementsofacivilstructureusingdictionaries


Date:

AIM:
Toimplement Elementsofacivil structureusing dictionariesin python

ALGORITHM:
1. Startthe Program.
2. Createthe emptydictionarywithElements_dictionary
3. Addtheelements todictionarywith thekeyvalues.
4. Print thetype ofElements_dictionary
5. Displaythe elements in the dictionary.
6. Removetheparticulariteminthe Elements_dictionarybyusing keywithpop()method.
7. Displaythepopped elementin thecivil structure
8. Add thesingleelement into theElements_dictionary
9. Displaythemodifieddictionaryelements.
10. Stop theProgram

PROGRAM:
#Elementsofacivilstructure
Elements_dictionary = {}

# dictionary with integer keys


Elements_dictionary={1:'Roof',2:
'Parapet',3:'Lintels',4:'Beams',5:'Columns',6:'Walls',7:'Floor',8:'Stairs'}
print(type(Elements_dictionary))
print("ThedictionaryelementsofCivilStructure")
print(Elements_dictionary)
print("RemovetheparticularitemintheCivilstructure")
print(Elements_dictionary.pop(4))
Elements_dictionary[9]='Plinth Beam'
print("TheDictionaryElementsafteraddingoneelementsinCivilStructure")
print(Elements_dictionary)

OUTPUT:
<class'dict'>
Thedictionary elementsof Civil Structure
{1:'Roof',2:'Parapet',3:'Lintels',4:'Beams',5:'Columns',6:'Walls',7:'Floor',8:'Stairs'} Remove the
particular item in the Civil structure
Beams
TheDictionaryElements afteradding oneelements inCivil Structure
{1:'Roof',2:'Parapet',3:'Lintels',5:'Columns',6:'Walls',7:'Floor',8:'Stairs',9:'Plinth Beam'
Ex.No.5(c)Add andSearchstudentrecordusingdictionary
Date:

AIM:
ToimplementapythonProgramtosearchstudentrecordusing dictionary

ALGORITHM:
1. Createalistto storethestudent details
2. Readthedatasuch asrno,name, marks
3. Calculatethetotal,average
4. Convertthelist to the dictionary
5. Print thestudent information’s
6. Stop theProgram.

PROGRAM:
n=int(input("Pleaseenternumberofstudents:")) all_students

= []

fori in range(0, n):


stud_name=input('Enterthenameofstudent:') print
(stud_name)

stud_rollno=int(input('Entertherollnumberofstudent:')) print
(stud_rollno)

mark1=int(input('Enterthemarksinsubject1:')) print
(mark1)

mark2=int(input('Enterthemarksinsubject2:')) print
(mark2)

mark3=int(input('Enterthemarksinsubject3:')) print
(mark3)

total=(mark1+mark2+mark3) print("Total
is: ", total)

average=total/ 3
print("Averageis:", average)

all_students.append({
'Name': stud_name,
'Rollno':stud_rollno,
'Mark1': mark1,
'Mark2': mark2,
'Mark3': mark3,
'Total': total,
'Average':average
})

forstudentinall_students: print
('\n')
forkey,valueinstudent.items():
print (key, value)

OUTPUT:
ENTERZERONUMBERFOREXIT!!!!!!!!!!!!
ENTERSTUDENTINFORMATION------------------------
enter roll no.. :: -- 1
entermarks1:: --77
entermarks2:: --88
entermarks3:: --77
Pleaseenternumberofstudents:2
Enter the name of student: Alex
Alex
Entertherollnumberofstudent:1 1
Enterthemarksinsubject1:99 99
Enterthemarksinsubject2:88 88
Enterthemarksinsubject3:88 88
Totalis:275
Averageis: 91.66666666666667
Enterthenameofstudent:Avin Avin
Entertherollnumberofstudent:2 2
Enterthemarksinsubject1:77 77
Enterthemarksinsubject2:77 77
Enterthemarksinsubject3:77 77
Total is:231
Averageis:77.0

NameAlex
Rollno 1
Mark199
Mark288
Mark388
Total275
Average91.66666666666667
NameAvin
Rollno 2
Mark177
Mark277
Mark377
Total231
Average77.0

Ex.No.5(d)OperationsinasetusingComponentsofaLanguage Aim:
ToImplementoperationsinasetusingComponentsofaLanguageas example.
ALGORITHM:

1. Startthe Program
2. Initializethedictionaries L1,L2
3. Performthesetoperations
4. Stop

Program:
L1={'Pitch','Syllabus','Script','Grammar','Sentences'};
L2={'Grammar','Syllabus','Context','Words','Phonetics'}; print("Union
of L1 and L2 is ",L1 | L2)
print("Intersection of L1 and L2 is ",L1 & L2)
print("Difference of L1 and L2 is ",L1 - L2)
print("SymmetricdifferenceofL1andL2is",L1^L2) Output:
UnionofL1andL2is{'Words','Pitch','Sentences','Phonetics','Script','Grammar', 'Syllabus',
'Context'}
Intersection of L1 and L2 is {'Grammar', 'Syllabus'}
DifferenceofL1andL2is{'Script','Pitch','Sentences'}
SymmetricdifferenceofL1andL2is{'Words','Context','Script','Pitch',
'Sentences', 'Phonetics'}

Result:Thusthebasicset anddictionaryoperationswere executedandthe output verified.


ExpNum : 6.a ImplementingprogramsusingFunctions

/*Program forFactorialof a number*/

Aim:
Towriteapython programforimplementing afactorialof agiven numberusing
recursion.

Algorithm:
Step 1 : Start
Step2 :Readanumber
Step3: Passthenumberasan argumenttoarecursivefactorialfunction.
Step4:Definethebaseconditionasthenumbertobelesserthanorequalto 1andreturn1if it is.
Step5:Otherwisecallthefunctionrecursivelywiththenumberminus1multipliedbythe number
itself.
Step6:Printtheresult. Step
7: Stop.

Program:
deffact(n):
if n==1:
returnn
else:
returnn*fact(n-1)
num = int(input("Enter a number: "))
print("Thefactorialof",num,"is",fact(num))

Output:
Enteranumber:5
Thefactorial of5 is 120

Result:
Thustheprogramwasimplementedandexecutedsuccessfully.
Exp Num : 6.b /*Programtofindthelargestnumberinalist*/
Aim :
Towriteaprogram to findthe largestnumber in alist using python.

Algorithm :
Step 1 : Start
Step2:Readnumberofelementstobestoreinalist Step 3 :
Initialize an empty list lst = [].
Step4:Readeachnumberinyourpythonprogramusingaforloop. Step 5 :
In the for loop append each number to the list.
Step6:Defineacustom function,whichisanacceptednumberlistandusedtofind the
largest number from list.
Step7:Callthiscustomfunctionandstorethefunctionresult. Step 8
: Print the result.
Step 9 : Stop

Program:
deffind_max(list):
max = list[ 0 ]for
a in list:
ifa>max:
max =a
returnmax
num=int(input('Howmanynumbers:')) lst
= []
forn in range(num):
numbers=int(input('Enternumber'))
lst.append(numbers)
print("Maximumelement in thelist is :",find_max(lst))

Output:
Howmanynumbers:5
Enter number 10
Enternumber20
Enternumber30
Enternumber40
Enternumber50
Maximumelement in thelist is : 50

Result:
Thustheprogramwasimplementedandexecuted successfully.
Exp Num : 6.c /*Programtofindtheareaofdifferentshapes*/
Aim :
Towriteaprogram tofind theareaofdifferent shapesusing python.
Algorithm :
Step 1: Start.
Step2:Calltheappropriateshapesandgettheinputs. Step 3:
Compute the formula as the shapes.
Step4:Returnthearea
Step 5: Print the area.
Step 6: Stop
Program:
defcir():
r=int(input("Entertheradious"))
area=3.14*r*r
returnarea
def tria():
b=int(input("Enter the base"))
h=int(input("Entertheheight"))
area=1/2*b*h
return area
defsquare():
a=int(input("Entertheside"))
area=a*a
returnarea
def rect():
l=int(input("Enter the length"))
w=int(input("Enterthewidth"))
area=l*w
return area

print(cir())
print(tria())
print(square())
print(rect())
Output:
Entertheradious2
12.56
Enter the base12
Entertheheight2
12.0
Entertheside3
9
Enterthelength12
Enter the width8
96
Result:
Thustheprogramwasimplementedandexecuted successfully.
Exp Num : 6.d /*Programtofindthesumoflistofelementsusing
function*/

Aim:
Towriteaprogramto sum ofanumbers ina list using function
Algorithm :
Step 1: Start.
Step2: Createa emptylist l=[]
Step 3: Read number of elements to store in a list.
Step4:Gettheinputandstoreinalistusingforloop Step 5:
Make a call to sum_list() function.
Step6:Initializesum=0
Step7:Iteratetheelementsusingforloopandaddtheelements. Step 8:
Return the sum
Step9:Printthesum
Step 10: Stop

Program:
defsum_list(l):
sum=0
fori in range(len(l)):
sum=sum+l[i]
return sum
l=[]
n=int(input("Enterthenumberofelements")) for
i in range(n):
x=int(input("Entertheelement"))
l.append(x)
result=sum_list(l)
print(result)
Output:
Enterthenumberofelements5
Enter the element10
Entertheelement20
Entertheelement30
Entertheelement40
Entertheelement50
150
Result:
Thustheprogramwasimplementedandexecuted successfully.
Exp Num : 6.e /*ProgramtocreateaSimplearithmeticcalculatorusing
function*/

Aim:
Towriteaprogram tocreate asimple arithmeticcalculatorusing function
Algorithm :
Step1:Takethevaluesoftwonumbersfromtheuserusingtheint(input())function and store
it in two variable say num1 and num2
Step2:Callfunctionaddandpassthevaluesofnum1andnum2asanargumentto the add
function.
Step3:Callfunctionsubandpassthevaluesofnum1andnum2asanargumentto the sub
function.
Step4:Callfunctionmulandpassthevaluesofnum1andnum2asanargumentto the mul
function.
Step5:Callfunctiondivandpassthevaluesofnum1andnum2asanargumentto the div
function.
Step6 :Copy the valuesofnum1 andnum2 at variable n1,n2.
Step7:Createauserdefinedfunctionstosayadd,whichtakesthevaluesofn1and n2 as an
argument using def keyword and return calculated result.
Step8:Createauserdefinedfunctionstosaysub,whichtakesvaluesofn1andn2as an
argument using def keyword and return calculated result.
Step9:Createauserdefinedfunctionstosaymul,whichtakesvaluesofn1andn2 as an
argument using def keyword and return calculated result.
Step10:Createauserdefinedfunctionstosaydiv,whichtakesvaluestheofn1and n2 as an
argument using def keyword and return calculated result.
Step11 : Printtheresultasoutput and exit.

Program:

#Programmakeasimplecalculator

#Thisfunctionaddstwonumbers def
add(x, y):
returnx+y

#Thisfunctionsubtractstwonumbers def
subtract(x, y):
returnx-y

#Thisfunctionmultipliestwonumbers
def multiply(x, y):
returnx* y

#Thisfunctiondividestwonumbers
def divide(x, y):
return x / y

print("Selectoperation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
#takeinputfrom theuser
choice=input("Enter choice(1/2/3/4): ")

#checkifchoiceisoneofthefouroptions if
choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2=float(input("Entersecondnumber:"))

ifchoice=='1':
print(num1,"+",num2, "=",add(num1, num2))

elifchoice=='2':
print(num1,"-",num2, "=",subtract(num1,num2))

elifchoice=='3':
print(num1,"*",num2,"=",multiply(num1, num2))

elifchoice=='4':
print(num1,"/",num2,"=",divide(num1,num2))

#checkifuserwantsanothercalculation #
break the while loop if answer is no
next_calculation=input("Let'sdonextcalculation?(yes/no):") if
next_calculation == "no":
break

else:
print("InvalidInput")
Output

Selectoperation.
1.Add2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Entersecondnumber:14
15.0 * 14.0 =210.0
Let'sdonextcalculation?(yes/no):no

Result:
Thustheprogramwasimplementedandexecuted successfully.
Exp Num : 6.f /*ProgramtofindtheGCDofanumberusingEuclidean
Algorithm*/

Aim:
TowriteaProgram to findtheGCD ofanumberusing Euclidean Algorithm
Algorithm :

Step1 :Taketwo numbersfrom the user.

Step 2. Pass the two numbers as arguments to a recursive function.

Step3.Whenthesecondnumberbecomes0,returnthefirstnumber.

Step4.Elserecursivelycallthefunctionwiththeargumentsasthesecondnumberand the
remainder when the first number is divided by the second number.

Step5.ReturnthefirstnumberwhichistheGCDofthetwonumbers. Step 6.

Print the GCD.

Step 7. Stop

Program:
deffind_gcd(a,b):
while(b):
a,a=b,a%b return
a
a=int(input (" Enterthefirst number: ") )
b=int(input("Enterthesecondnumber:")) num =
find_gcd(a, b)
print("TheGCDoftwonumberaandbis") print(num) #
call num
Output
Entre the first number :144
Enterthesecondnumber:96
TheGCD oftwo number and b is 48
7. ImplementingprogramsusingStrings
AIM:
Toimplementpythonprogram using strings.

REVERSE ASTRING

ALGORITHM:
STEP1:Gettheinputfromtheuser
STEP2:Thefunctioncallisinvoked,wherethestringispassedasinputtoreversefunction STEP3: For
loop is executed until the last character in the string is reached
STEP4:Thestrvariableisincrementedfor eachiterationandreturnedasthereversed string.

PROGRAM:
defreverse(s):
str = ""
fori in s:
str=i+str
return str
s =input("Enter the string to reverse:")
print("Theoriginalstringis:",end="") print
(s)
print("Thereversedstringis:",end="") print
(reverse(s))

OUTPUT:
Enterthestringtoreverse:python
The original stringis : python The
reversed string is : nohtyp

PALINDROMEOFASTRING
ALGORITHM:
STEP1:Gettheinputstringfromtheuser.
STEP2:Checkwhetherstringisequaltothereverseofthesamestringusingslicing operation in
an if condition.
STEP3:If thecondition is satisfied,then thestringis apalindrome.

PROGRAM:

string=input(("Enteraletter:"))
if(string==string[::-1]):
print("Theletterisapalindrome") else:
print("Theletteris notapalindrome")

OUTPUT:
Enteraletter:mom
Theletteris a palindrome

CHARACTERCOUNT

ALGORITHM:
STEP1:Get thestring fromthe user
STEP2:Getthecharacterto becountedin thestring fromtheuser.
STEP3:Forloopisexecuted untilthelastcharacter ischeckedinthestring
STEP4:Usingtheifcondition,thecharacterenteredandthecharactersinthestringis compared
inside the for loop for each iteration.
STEP5:Thenumberoftimestheenteredcharacterhasbeenpresentinthestringwillbe returned
as the total count.
PROGRAM:
test_str = input("Enter the String:")
character=input("EntertheCharacter:") count
=0
fori in test_str:
if i == character:
count=count+1
print ("Count is : "+str(count))

OUTPUT:
EntertheString:expression
Enter the Character: s
Count is : 2

REPLACINGCHARACTERS

ALGORITHM:
STEP1:Readthe String
STEP2:Replacethecharacterinthestringusingreplace()method. STEP3:
Display the replaced string.

PROGRAM:
string= " HI!HI!HI!WELCOMETOPYTHONPROGRAMMING"
print ("Original String:",string)
replace1=string.replace("HI","HELLO")
print ("Replaced String 1:",replace1)
replace2=replace1.replace("HELLO","Hello",3)
print ("Replaced String 2:",replace2)

OUTPUT:
OriginalString:HI!HI! HI!WELCOMETOPYTHON PROGRAMMING
ReplacedString1:HELLO!HELLO!HELLO!WELCOMETOPYTHON PROGRAMMING
ReplacedString2:Hello!Hello!Hello! WELCOMETOPYTHONPROGRAMMING
BASICSTRING OPERATIONS

ALGORITHM
STEP1:Declarea string
STEP2:Accessa word fromthestringusingindex value
STEP3:Carryouttheslicingoperationseitherbyusingtheforwardslicingorbackward slicing.
STEP4:Concatenationoftwostringsaredonebyusing“+”operator.
STEP5: Repetition of a string is done by using “*” operator.
STEP6:Checkwhetherthewordsarepresentinthestringbyusingmembershipoperator. STEP7:
Print the string in uppercase by using upper() method.
STEP8:Lengthofthestringiscalculated byusinglen() method.

PROGRAM:
a="hello"print("Strin
gis:",a) #accessing a
string
print("AccessedStringis:",a[3])
#Slicing Operation
print("Slicing Operation:",a[0:3])
print("Forward Slicing:", a[0:4])
print("BackwardSlicing:",a[-3:-1])
print("Slicingusingsize:",a[1:4:2])
#concatenation
print("concatenation:", a+"Hi")
#repetition
print("Repetition:",a*3)
#membership
print("Membershipeina:",'e'ina)
print("Membershipvina:",'v'ina)
#methods
print("stringinUppercase:",a.upper())
print("Length of string:", len(a))

OUTPUT:
String is:hello
Accessed String is:l
Slicing Operation: hel
Forward Slicing: hell
Backward Slicing: ll
Slicing using size: el
concatenation:helloHi
Repetition: hellohellohello
Membership e in a: True
Membership v in a: False
stringinUppercase:HELLO
Length of string: 5

RESULT:
Thusthepythonprogramtoimplementthestringwasdonesuccessfullyandthe output
was verified.
8. ImplementingprogramsusingwrittenmodulesandPythonStandardLibraries

Ex.No. 8(a) Simple Program using numpy

AIM:
Towriteapython programto plot asimple pythongraph for astraight line.

ALGORITHM:

1. Startthe Program
2. Importthemodulesnumpy, pyplot
3. Storetheset ofvaluesinx,equationin y
4. Assigntitle,axis labelforthe graph
5. Show thegraph
6. Stop

PROGRAM:
import numpy as np
frommatplotlibimportpyplotasplt

x=np.arange(1,11)
y=2*x+7
plt.title("Matplotlibdemo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x,y)
plt.show()

OUTPUT:
Ex.No 8.(b) Programusingpandas
Date:

AIM:
Tocreatedataframes usingpandasinpython.

ALGORITHM:
1. Startthe Program.
2. Importnumpyandpandas
3. Createadictionarywithstudentname,marksof threesubjects
4. Convertthedictionarytoadata frame
5. Printthedata frame
6. Stop

PROGRAM:
importnumpyasnp
importpandasaspd

mydictionary={'names':['Somu','Kiku','Amol','Lini'],
'physics': [68, 74, 77, 78],
'chemistry':[84, 56,73,69],
'algebra':[78,88,82,87]}

#create dataframe using dictionary


df_marks=pd.DataFrame(mydictionary)

print(df_marks)

OUTPUT:
namesphysicschemistryalgebra
0Somu 68 84 78
1Kiku 74 56 88
2Amol 77 73 82
3Lini 78 69 87
Ex.No.8(c)UsingScipy-Univariate Interpolation
Date:

AIM:
ToimplementapythonProgram toplotanunivariateinterpolation.

ALGORITHM:
1. Start
2. Importinterpolate,pyplot
3. Usingx,yvalues arrangethegrapharea
4. Usingpyplot ,print thegraph
5. Stop

PROGRAM:
importmatplotlib.pyplotasplt
from scipy import interpolate
x = np.arange(5, 20)
y =np.exp(x/3.0)
f=interpolate.interp1d(x,y)
x1 = np.arange(6, 12)
y1=f(x1)#useinterpolationfunctionreturnedby`interp1d` plt.plot(x, y,
'o', x1, y1, '--')
plt.show()

OUTPUT:

Result:
Thusthe programsusing moduleswereimplementedin python.
ExpNumber9. Implementingreal-time/technicalapplicationsusingFilehandling.
A. Pythonprogramtocopythecontentofonefileintoanotherfile Aim :
Towriteaprogram to copy the content ofonefileinto anoqther file.
Algorithm:
Step 1: Start
Step 2: Openonefilecalledtest.txtinreadmode.
Step 3: Open another file out.txt in write mode.
Step 4: Readeachlinefromtheinputfileandwriteitintotheoutputfile. Step 5:
Stop.
Program:
print("EntertheNameofSourceFile:")
sourcefile = input()
print("EntertheNameofTargetFile:")
targetfile = input()
fileHandle=open(sourcefile,"r")
texts = fileHandle.readlines()
fileHandle.close()
fileHandle=open(targetfile,"w")
for s in texts:
fileHandle.write(s)
fileHandle.close()
print("FileCopiedSuccessfully!")
Output:
Enter the Name of Source File: in.txt
EntertheNameofTargetFile:out.txt

FileCopiedSuccessfully
B. PythonProgramtoCounttheNumberofWordsinaTextFile Aim :
TowriteaPython Programto Count theNumber ofWords in aText File
Algorithm:
Step 1: Start
Step 2:Openfile“book.txt”inreadmodeandstorecontentsoffileinfileobjectsayfin Step
3: Read each line from the file using read() function
Step 4:Splitthelinetoformalistofwordsusingsplit()functionandstoreitinvariable say l.
Step 5:IntitiallySetthevalueofcount_wordsvariabletozeroinwhichwewillstorethe
calculated result.
Step 6:Useforlooptoreadlistofwordstoredinvariablesayl. Step
7: Find the length of words in the list and print it.
Step 8:Closethefileusingclose()function.Program:
Step 9: Stop
Program:
fin=open("book.txt","r")
str = fin.read()
l = str.split()
count_words=0
for i in l:
count_words=count_words+1
print(count_words)
fin.close()

Output:
25
C. PythonProgramtofindlongestWordinaTextFile Aim :
TowriteaPython Program tofind longest Wordina Text File
Algorithm:
Step 1: Start
Step 2:Opentextfilesay‘name.txt’inreadmodeusingopenfunction Step
3: Pass file name and access mode to open function
Step 4:Readthewholecontentoftextfileusingreadfunctionandstoreitinanother variable
say ‘str’
Step 5:Usesplitfunctiononstrobjectandstorewordsinvariablesay‘words’ Step
6: Find maximum word from words using len method
Step 7:Iteratethroughword bywordusingfor loop
Step 8:Useifloopwithinforlooptocheckthemaximumlengthofword Step 9:
Store maximum length of word in variable say ‘longest_word’ Step
10: Display longst_word using print function
Step 11:Stop
Program:
fin=open("name.txt","r")
str = fin.read()
words=str.split()
max_len=len(max(words,key=len)) for
word in words:
iflen(word)==max_len:
longest_word =word

print(longest_word)
Output:
Encyclopedia
Result:
Thustheprogramforreal-time/technicalapplicationsusingFilehandlingwas implemented and
executed successfully.
10. Implementingreal-time/technicalapplicationsusingExceptionhandling
AIM:
Toimplementpythonprogramforreal-time/technicalapplicationsusing Exception
handling.

DIVIDEBY ZERO ERROR

ALGORITHM:
STEP1:Get theinput forn,d and c.
STEP2:Inthetryblock, calculate q=n/(d-c).
STEP3:Ifthedenominatorisnon-zero,thenthequotientgetsprinted.
STEP4: Otherwise, the exception Zero Division Error is executed.

PROGRAM:
n=int(input("Enterthevalueofn:"))
d=int(input("Enterthevalueofd:"))
c=int(input("Enterthevalueofc:"))
try:
q=n/(d-c)
print("Quotient:",q)
except ZeroDivisionError:
print("DivisionbyZero!")

OUTPUT:
Enterthevalueofn:10
Enter the value of d: 5
Enter the value of c: 5
Division by Zero!
VOTER’SAGEVALIDITY
ALGORITHM:
STEP1:Gettheagefromthe user.
STEP2:Intheifblock,checkiftheageisgreaterthan18,thenprint“Eligibletovote”. STEP3:
Otherwise, print “Not eligible to vote”
STEP4:If theageentered is anon-number, then theexception block is executed.
PROGRAM:
defmain():
try:
age=int(input("Enteryourage")) if
age>18:
print("Eligibletovote")
else:
print("Noteligibletovote")
except:
print("agemustbeavalidnumber")
main()

OUTPUT1:
Enteryourage24
Eligible to vote
OUTPUT 2:
Enter your age 14
Noteligibletovote

STUDENTMARKRANGEVALIDATION
ALGORITHM:
STEP1:Getthenumberbetweenthe range(1 -100)
STEP2:Intheifblock,checkwhetherthenumberisbetween1to100. STEP3:
Otherwise, print “Above 100, wrong”
STEP4:If theageentered is anon-number, then theexception block is executed.
PROGRAM:
definput_number(min,max):
try:
while True:
n=int(input("Pleaseenteranumberbetween{}and{}:".format(min,max))) n=int(n)
if(min<=n<=max):
print(n)
break
else:
print("Above100,wrong")
break
except:
print("markmustbeavalidnumber")
input_number(1,100)

OUTPUT1:
Pleaseenter anumberbetween 1and 100 :4
4
OUTPUT2:
Pleaseenter anumberbetween 1and 100 :156
Above100, wrong
OUTPUT3:
Pleaseenteranumberbetween1and100:ab mark
must be a valid number

RESULT:
Thustheprogramforreal-time/technicalapplicationsusingExceptionhandlingwas
implemented and executed successfully.
Ex.No. 11
ExploringPygame tool

 Pygameisacross-platformsetofPythonmoduleswhichisusedtocreate video
games.
 Itconsistsofcomputergraphicsandsoundlibrariesdesignedtobeusedwith the
Python programming language.
 PygamewasofficiallywrittenbyPeteShinnerstoreplacePySDL.
 Pygameissuitabletocreateclient-sideapplicationsthatcanbepotentially
wrapped in a standalone executable.

Pygame Installation

InstallpygameinWindows

BeforeinstallingPygame, Pythonshould beinstalled inthesystem,and itis goodto have


3.6.1oraboveversionbecauseit ismuchfriendlier tobeginners,andadditionallyruns faster.

Therearemainly twowaysto installPygame,which aregiven below:


1. Installingthroughpip:ThegoodwaytoinstallPygameiswiththepiptool.Thecommand is the
following:

py-mpipinstall -Upygame--user

2. Installing through an IDE: The second way is to install it through an IDE and here we are
usingPycharmIDE.Installationofpygameinthepycharmisstraightforward.Wecaninstall it by
running the above command in the terminal or use the following steps:

Openthe Filetaband click onthe Settings option.

SelecttheProject Interpreterand clickonthe+icon.

Itwilldisplaythesearch box. Searchthepygameandclickontheinstallpackagebutton.


Tocheckwhetherthepygameisproperlyinstalledornot,intheIDLEinterpreter,typethe following
command and press Enter:

import pygame

Ifthecommandrunssuccessfullywithoutthrowinganyerrors,itmeanswehavesuccessfully installed
Pygame and found the correct version of IDLE to use for pygame programming.

SimplepygameExample

import pygame

pygame.init()
screen=pygame.display.set_mode((400,500))
done = False

while not done:


for event in
pygame.event.get():ifevent.typ
e==pygame.QUIT:
done = True
pygame.display.flip()

importpygame-Thisprovidesaccesstothepygameframeworkandimportsallfunctionsof pygame.

pygame.init()-This isused toinitializeallthe requiredmoduleofthe pygame.

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


size.ThereturnvalueisaSurfaceobjectwhichistheobjectwherewewillperformgraphical
operations.

pygame.event.get()-Thisis usedtoempty theevent queue.

pygame.QUIT -Thisisusedtoterminatetheeventwhenweclickontheclosebuttonatthe corner of


the window.

pygame.display.flip()-Pygameisdouble-buffered,sothisshiftsthebuffers.Itisessentialto call this


function in order to make any updates that you make on the game screen to make visible.
Pygame Surface
The pygame Surface is used to display any image. The Surface has a pre-defined resolution
andpixelformat.TheSurfacecolorisbydefaultblack.Itssizeisdefinedbypassingthesize argument.

Pygame Clock
Timesarerepresentedinmillisecond(1/1000seconds)inpygame.Pygameclockisusedto track the
time. The time is essential to create motion, play a sound, or, react to any event.
Developingagameactivity using Pygame
12.A. Bouncingball game

Aim:
Writeapythonprogram tosimulate bouncingball using pygame

Algorithm:

1. Importpygamemodule
2. Callpygame.init()toinitiateallimportedpygamemodule
3. Setthescreensizeintermsofpixelsusing
pygame.display.set_mode((400,300)
4. Ifthereisanyeventin pygamequeue
a. Gettheevent fromthe pygamequeue
b. Ifeventtypesispygame.QUITthen setdone=true
5. Else,Drawthecircleupdatethescreendisplaywithnewcircletobring
bouncingeffect
6. Callsys.exit()touninitializedallthepygamemodules

Program:

import pygame
frompygame.localsimport*

pygame.init()
screen =
pygame.display.set_mode((40
0, 300)) done = False

while not done:


foreventinpygame.event.get(): if
event.type ==
pygame.QUI
T: done =
True
pygame.draw.circle(screen,(255,255,255),[100, 80],10,
0)pygame.display.update()
pygame.draw.circle(screen,(0,0,0),[100,80],
10,0)pygame.display.update()
pygame.draw.circle(screen,(255,255,255),[150, 95],10,
0)pygame.display.update()
pygame.draw.circle(screen,(0,0,0),[150,95],10,0)
pygame.display.update()
pygame.draw.circle(screen,(255,255,255),[200, 130],10,0)
pygame.display.update()pygame.draw.circle(screen,(0,0,0),
[200,130],10,0)pygame.display.update()
pygame.draw.circle(screen,(255,255,255),[250,150],10,0) pygame.display.update()
pygame.display.update()
for event in
pygame.event.get():
if event.type ==
QUIT:
pygame.quit() sys.exit()

Output:
Result:
Thus,theprogramtosimulateellipticalorbitsinpygamehasbeenexecuted
successfully.
12. B. CarGame
Aim:
Writeapython programto simulatecar gameusing pygame.

Algorithm:

1. Importpygamemodule
2. Callpygame.init()toinitiateallimportedpygamemodule
3. Setthescreensizeintermsofpixelsusing
pygame.display.set_mode((798,600
4. Setthelogo and thebackground forthe game.
5. Assignthecarimagesforthe raceandsetits parameters
6. Setthekeymovement values
7. Updatethescreendisplayafter every changeincarposition
8. Callthegame loopuntil run
9. Stop

Program:
importpygame
pygame.init()
frompygame.localsimport*
import random
screen = pygame.display.set_mode((798,600))
pygame.display.set_caption('Racing
Beast')logo=pygame.image.load('cargame/logo.
jpeg') pygame.display.set_icon(logo)
defgameloop():
bg=pygame.image.load('cargame/bg.png')
maincar=pygame.image.load('cargame\car.png')
maincarX = 350
maincarY=495
maincarX_change=0
maincarY_change=0

car1=pygame.image.load('cargame\car1.jpeg')
car1X = random.randint(178,490)
car1Y=100

car2=pygame.image.load('cargame\car2.png')
car2X = random.randint(178,490)
car2Y=100
car3=pygame.image.load('cargame\car3.png')
car3X = random.randint(178,490)
car3Y=100
run = True
while run:
for event in
pygame.event.get():ifevent.typ
e==pygame.QUIT:
run = False
ifevent.type==pygame.KEYDOWN:
ifevent.key== pygame.K_RIGHT:
maincarX_change+=5
ifevent.key==pygame.K_LEFT:
maincarX_change -= 5
ifevent.key==pygame.K_UP:
maincarY_change -= 5
ifevent.key==pygame.K_DOWN:
maincarY_change += 5

ifevent.type==pygame.KEYUP:
ifevent.key==pygame.K_RIGHT:
maincarX_change = 0

ifevent.key==pygame.K_LEFT:
maincarX_change = 0

ifevent.key==pygame.K_UP:
maincarY_change = 0

ifevent.key==pygame.K_DOWN:
maincarY_change = 0

ifmaincarX<178:
maincarX=178
ifmaincarX>490:
maincarX=490

ifmaincarY<0:
maincarY=0
ifmaincarY>495:
maincarY=495

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

#displayingthebackground image
screen.blit(bg,(0,0))

#displaying our main car


screen.blit(maincar,(maincarX,maincarY))

#displaing other cars


screen.blit(car1,(car1X,car1Y))
screen.blit(car2,(car2X,car2Y))
screen.blit(car3,(car3X,car3Y))

#updatingthe values
maincarX+=maincarX_change
maincarY +=maincarY_change

car1Y+=10
car2Y+=10
car3Y+=10

if car1Y > 670:


car1Y=-100
if car2Y > 670:
car2Y=-150
if car3Y > 670:
car3Y=-200

pygame.display.update()
gameloop()
Output:

Result:
Thusthe gamewas developedusing pygame module.

You might also like