PROGRAMMING IN
PYTHON (42)
HAND ON PRACTICE & BOOK INSIDE
EXAMPLE PROGRAMS
TAMIL NADU HIGHER SECONDARY SECOND YEAR SYLLABUS\V.Devanathan M.Se (CS)., M.Phil, Ph.D., B Sharmila BSe(CS),,B.Ed.,
ACKNOWLEDGEME!
T owe my thanks to a great many people who helped and
supported me to write this book.
1 express my deep and sincere gratitude to Dr.RM.Alagappa
Chettiar Founder of Alagappa Group of Educational Institutions.
1 extend my heartfelt and sincere thanks to our beloved Achi-
Dr.Umayal Ramanathan and Dr.Ramanathan V
Chairman, for providing all necessary facility.
Textended my reverential gratitude to Mr.G. Naresh Kumar,
Trustee for his valuable suggestions and ideas towards completion of
book successfully and Mrs. K.S. Revati, Principal for her valuable
‘guidance and support throughout the completion of my task.
It’s my privilege to express my sincere thanks to all the staff
members of Alagappa schools, who guided and
pired me to
complete the book. | also thank all my well wishers and friends who
extended this valuable cooperation by providing all the information
that I needed for this book.
1 express my sincere thanks 10 my family who have helped
and supported me to the journey of my book
tp:/swww.youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M.Sc (CS)., MPhil, PLD, BSharmila B.Se(CS),,B.Ed.,
ALAGAPPA SCHOOLS, CH-84.
Study Materials -XII STD
COMPUTER SCIENCE
PROGRAMMING IN PYTHON
HAND ON PRACTICE & BOOK INSIDE EXAMPLE.
PROGRAMS
Prepared by
DEPARTMENT OF COMPUTER SCIENCE
ALAGAPPA SCHOOLS, CH-84
1.V.Devanathan M.Sc (CS).,.M.Phil..Ph,D., 2. B.Sharmila B.Se(CS)..B.Ed.,
PGT Computer Science TGT Computer Science
Alagappa Schools ‘Alagappa Schools
Purasaiwalkam Purasaiwalkam
‘Chennai-84. ‘Chennai-84.
E-mailvigneshvlandefa@gmailcom —_E-mail'shamilababul1@mailcom
‘ntp://www.youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M.Se (CS)., M.Phil, Ph.D., B Sharmila BSe(CS),,B.Ed.,
TABLE OF CONTEN
UNITNO | CHAPTER TITLE my
i Function 1
UNIT-1
Problem 2 Data Abstraction nil
Solving 3 Scoping 2
Techniques as
4 “Algorithmic Strategies nil
; Python -Variables and =
Operators
we ual 6 Control Structures 3
Python 7 Python funetions 2
; Strings and String es
‘manipulations
aa é Lists, Tuples Sets and >
Modularity Dictionary
and OOPS 10 | Python Classes and objects 62
ul Database Concepts wil
UNIT-IV Siractured Query Language
Database tls 2
concepts
and Masal 13 __ | Python and CSV files 87
Tmporting CF programs in
UNIT-V a Python, ee
Integrating Ts | Data manipulation through
Python with SQL.
MySql and Data visualization using pyplot
CH 16 line chart, pie chart and bar | 106
chart
hutp://www.youtube.com/e/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B.Sharmila B.Se(CS).,B.Ed.,
CHAPTER 1
FUNCTION
HANDS ON EXPERIENCE:
L.Write algorithmic function definition to find the mit
numbers.
let min x y z=
if x
b) and (ae):
print(a," is largest")
elif (ba) and (be):
incl, "is Ingest")
else:
print(e, "is largest”)
Ourpue
Ent
Enter third
34 is largest
13. Write a program to check whether the given character is a vowel
or not
Coding:
ch = input ("Enter a character")
Af ch in(tar, Atte, EB 'a','T', 10", 10%, a), 0):
print (eh,'is @ vovel')
e1se:
print (ch,'is not a vowel!)
Output :
10
hnttp:// www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
14, Using if. else..elif statement check smallest of three numbers
Codin;
= ant (input ("Enter nunber 1"))
b= int (input ("Enter nurber 2”))
= ine (input ("Enter nuxber 3"))
An acb and ace:
print(a,'is swallest')
else bea and beer
print (b,'is the smallest’)
else:
print (c,!is the smallest!)
Output
Enter munber 123
Enter nurber 345
29 is smallest
1
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
EXAMPLE-PROGRAMS
1.Program to print your name and address - example for sequential
statement,
Coding:
print (*Hello! This is Shyan")
print (*43, Second Lane, North Car Street, ‘N")
Output:
Hello! This is Shyam
43, Second Lane, North Car Street, TN
2,Program to check the age and print whether eligible for voting,
Coding:
nt (input ("Enter your age :"))
if w
PE:
ft ("You are eligible for voting")
Output:
Enter your age :34
you are eligibie ror voting
>>>
RESTART: C:/Users/Kumaran/F
Enter your age :16
2
hnttp://wwww.youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
3.Program to check if the accepted number odd or even.
Coding:
‘@_= int Gnput MEnter any number =")?
Se asz==0:
print (a, " is an even number")
Print (a, " is an oad number)
Output:
Enter any number :56
Se is an even number
RESTART: C:/Usere/Kur
67 is an odd number
4.Program to check if the accepted number is-odd or even(using
alternate method of if...else)
Coding:
a = int (input ("Enter any number =
xe"even" if at2==0 else "odd"
print (a, "is ")x)
Output:
Enter any number :3
3 is oda
>>>
RESTART: C:/Users/Ku
Enter any number :22
22 is even
B
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M.Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
S.Program to illustrate the use of nested if statement
Average Grade
>=80 and above
>=70and <80
>=60 and <70
>=50 and <60
Otherwise
moO eS
Codin;
misint (input (Enter mark in first subject > “))
RE (input ("Enter mark in second subject: "))
Svo= (mlim2)/2
avg>=s0:
Print ("Grade : A")
elif avg>=70 and avgeso:
print ("crade zB)
elif! avg>~60 and avg<70:
print ("crage :c")
e1if avg>=50 and avge60:
print ("Grade : D")
else?
print ("Grade : EB")
Output:
Enter mark in first subject : 34
Grade ? D -
Enter mark in first subject
Enter mark in second subject
Grade : B
Users/Kumaran/APpD
67
ae
14
‘http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
lchinput ("Enter @ character :")
# to check if the letter is vovel
if ch in ("a","RM,"e,"E", "iM, "1", "08, 908, "a", "0M)
print (ch,"is 2 vowel")
# to check if the Lecter typed 1s not ‘a’ or
if ch not in ("2","D","c%):
print (ch," the letter is not a/b/c*)
eon ig
Output:
Enter a character :e
e is a vowel
© the letter is not a/b/c
se= RESTART: C:/users/Kumarar
Enter a character :x
x the letter is not a/b/e
7 Program to illustrate the use of while loop - to print all numbers
from 10 to 15.
Codi
i=10 Hintializing part of the control variable
ide (heet5): # test condition
print (ivend-"\tt) —# statements - block 1
isitl 4 Updation of the control variable
zw oo 1s
15
|hup:/www.youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
8,Program to illustrate the use of while loop - with else part
fintiaLiing art of the control variable
ftest condition
fstateents ~B
fopdation of the
rint ("nfalae of i when the Loop exit *,i)
Output:
to aaa Fe
9,Program to illustrate the use of for loop = to print single digit even
number.
16
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
10.Program to illustrate the use of for loop - to print single digit even
number with else part
Codi
for 1 in range@
Beine (lend
Output:
2468
End of the loop
11.Program to calculate the sum of numbers 1 10.100:
in range (1)n41
print (tou of 1 neil $d: $a" ¥ (nyoum)
Output:
sum of 1 until_100: $050
12,Program to’illustrate the use of string in range() of for loop.
Codin;
for word in ‘Computer™
BEint (word, end=
PEint ("\nBnd of the Loop")
>
Outp
computer
End of the loop
v7
hitp://www.youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
13.Program to illustrate the use nested loop -for within while loop.
Codin;
ist
while (ice
for j in range (1,i):
print (jend="\t")
print (end-'\n")
a)
14 Program to illustrate the use of break statement inside for loop.
Coding:
for word in"Jump statement":
if word=="e":
broak
Outp
Jump stat
18
‘http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
15.Program to illustrate the use of break statement inside for loop.
print ("End of the loop")
Output:
End of the program
16.Program to illustrate the use of continue statement inside for loop.
Coding:
for word in “Jump Statement":
if word=s"e":
continue
print (word, end="")
print ("\n End of the program")
Ontpat:
End of the program
19
hhetp://www.youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
17.Program to illustrate the use of pass statement.
‘Coding:
else:
print ("non zero value is accepted")
Output:
Enter any number :3
non zero value is accepted
18.Program to illustrate the use of pass statement in for
loop
Coding:
for val intcomputer*:
pass
print ("End of the loop, loop structure vill be built in future")
Output:
nd of the loop, oop structure will te built in future
20
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, BSharmila B.Se(CS),,B.Ed.,
LESSON-7
PYTHON FUNCTIONS
HANDS ON EXPERIENCE:
1. Write a python code to check whether a given year is leap yearor
not
Coding:
‘ye int (input ("Enter year"))
it yeareor
peint("The given year is a leap year")
else:
peint("The given year is not a leap year")
Output 1:
Enter year2004
‘The given year is a leap year
Output 2:
Enter year2005
The given year is not @ leap year
2
hhttp://www.youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
2. Write a python code to find the L.C.M of two numbers.
Codin;
def lem(x, y=
se wey:
greater = x
else:
greater = y
while (True!
Af ((greatertx==0) and (greaterty==0)) :
lem = greater
break
greater t=1
return lem
a= int (input ("Enter @ number 1"))
be int (input ("Enter a number 2"))
print ("The LCM of",a,"and",b,"is", 1cm(a,b}}
Output:
Enter a number 125
Enter a number Z5U
The LCM of 25 and 50 is 50
>>>
2
http://www youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD,
Hands on Experience:
ef printinfo(name, salary=3500):
rint(’Name:" name)
print("Salary:" salary)
return
1. Try the following code in the above program
B Sharmila B.Sc(CS).B.Ed.,
Sino [ode ‘output
1. | printinfoC"3500°7) ‘Name: 3500
Salary: 3500.
Z| primtinfoC3500""Sar) | Name: 3500
Salary: Sri
3. | printinfo(name="bals") | Name: bal
Salary: 3500
Z| primiinfoC Tose"-1234) Name: Jose
Salary: 1234
S| printinfoC salan=1234) | Name:
Salary: 1234
z
2, Evaluate the following functions and write the output
http://www. youtube.cam/c/CSKNOW! FNGFOPENER
Sloo_| functions output
1 [eval(2s#2se9) [30
2. | math sqrtfabs(-81)) [9.0
3, | mathoell3SH46) |)
4 [mato sH9 [3
23\V.Devanathan M Se (CS)., M.Phil, Ph.D.,
B.Shamnila B.Se(CS).,B.Ed.,
3. Evaluate the following functions and write the output.
‘Sino | functions ‘output
a 1 abs(-25+12.5) 125
2. abs(-3.2) 32
2. 1. ord(2) 30
2. ord('S') 36.
3 ‘type('s})
4. ban( 6) “0b10000"
5. 1. chr(13) v
2. print(chr(13))
€ 1. round(18.2.1) 182
2. round(18.2,0) 18.0
3. round(0.5100,3) 051
4. sound(0.5120,3) 0512
zi 1. format(66.c’)
2. format(10,'x) ‘
a”
6
10°
8 0.125
80
a:
4.pow((1+2).2) 9
5. pow(-3,2) 9
6. pow(2*2.2) 16
24
nttp://www.youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
EXAMPLE-PROGRAMS,
1, Program to illustrate the use of simple function to display the given
string.
Coding:
def hello():
print ("hello-python")
return
hel10()
Output:
Hello python
2. Program to illustrate the use of'simple function to display the given
string by using alternative method of calling function within the
print() function
Coding:
det net10()+
print ("hello-python",
return
print (hello())
Output:
hello-python
None
25
Inttp://www.youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
3. Program to illustrate that defines a function that helps to pass
parameters into the function,
Coding:
#assume vw =3 and h= 5
def area(u,h):
return uth
print (area(3,5))
Output:
15
4, Program to illustrate that Required Arguments passed to a
function.
Codin;
def printstring(str) :
print ("Example - Required argument")
print (str)
return
#mov you can call printstring() function
printstring("welcome")
Output,
Example - Required argument
welcome
Doe
26
Inttp://www.youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
5. Program to illustrate that Required Arguments in Improper order.
Codin;
def printdata (name):
print ("Example-1 Keyword argument")
print ("Name:", name)
return
#Now you can call printdata() function
printdata(name = "Gshan")
Outp
Example-1 Keyword argunent
Name: Gshen
6. Program to illustrate that Required Arguments in unexpected
keyword.
Codi
def printdata (name) :
print ("Example-1 Keyword argument")
Prine ("Newe:", name)
return
#Now you can call printdata() function
printdata(namet = "Gshan")
Output:
Traceback (nost recent call last):
File "C:/Users/mrsva/Desktop/in.py", line 6, in
printdata(name1 = "Gshan")
‘TypeError: printdata() got an unexpected keyword arguvent 'nanel!
>
7
|nttp://www.youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
7. Program to illustrate that the parameters orders are changed
Codin;
def printdata (name, age):
print ("Example-3 Keyword argument”)
print ("Name:", name)
print ("Age:", age}
return
#Now you can call printdata() function
printdata(age=25, name="qshan")
Output:
Example-3 Keyword argument
Name: gshan
Age: 25
>>>
8, Program to illustrate that the default Arguments are passed.
Codin;
def printinfo (name,salery = 3500;
print (""Name:", name)
print ("Salary:", salary)
print info ("tlani")
Output:
Name: Mani
Salary: 3500
>>>
28
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
9. Program to illustrate that we pass more than 3 arguments in the
sum() funetion,
Codi
def Sum(x,¥,2)!
print ("Sum of three nos: ",cty+e)
summ(5, 10, 15,20,25)
Output:
Traceback (most recent call Lasc):
Pile "C:/Usere/mesva/Deaktop/ine.py", Line 3, in
‘un(5, 10, 15,20,25)
Typeteror! sim() takes 3 positional arguvents but § vere given
10. Program to illustrate that the variable-length arguments function.
Coding:
Ges peintnos (*nos) =
for n in nos:
print (n)
cuen
fmow invoking the printnos() funceion
print ("Pinting two values")
print (1,2)
print("Printing three values")
printnos (10, 20,30)
Output
Painting two values
12
Printing three values
10
20
30
29
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
11, Program to illustrate that to use the Anonymous function
[LAMBDA]
Coding:
sun lanbde argl,arg2:argltarg2
print ("Sum 15:",sum(3U,4U))
print ("Sum is:", suma(-30, 40) )
Output:
Sum ist 70
Sum is: 10
12. Program to illustrate that to use th Return statement,
Coding:
#recurn statement
Sez usr_abs(n)?
ae B>=0:
ese:
#Now invoking the function
xeint (input ("Enter a number: "))
peint (usr_abe (x) )
Outpu
Enter a number:25
25
>>
Enter a number:-25
25
30
http://www. youtube.com/e/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
13, Program to illustrate that to create a local variable.
Coding:
def oct):
yr0 #local scope
print (¥)
toc ()
Output:
0
14, Program to illustrate that to accessing Global Variable from
inside a function,
#1 #global variable
def aaa:
print (c)
aaa ()
Output:
1
31
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
15, Program to illustrate that to modifying Global Variable from
inside the function,
Coding:
emt Aglobal variable
det add():
o=c#2 #increnent c by 2
print (¢)
add ()
Output:
‘Traceback (moat recent cali Last)
File "c:/Users/mesva/Desktop/ ind -py", line 5, in
File "C1/Usere/meeva/Desktop/in2-py", Line 3, in add
SSei2 increment c by 2
16, Program to illustrate that t changing Global Variable from inside
a function using Global keywords.
Coding:
x=0 figlobal variable
det ada()s
global x
xoxtS #increment by 2
print ("Inside edd() function x value is:"/x)
aaa)
print ("In main function x value is :"/x)
Output:
Inside add() function x value is: 5
In main function x value is : 5
32
Inttp://www.youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
17. Program to illustrate that to use Global Variables and Local
Variables in same code.
Ce
x8 fx ts globai variapie
ace locwr
Hosts =
¥omtocat”
peace
print
root)
Output
16
tecat
18. Program to illustrate that to se Global Variables and Local
Variables in same name.
See 10c(ys
Prine ("Local x"):
recy
Prine ("gioba x:")*)
Output:
33
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
19, Program to illustrate that to use Function input() and apply eval()
function,
Coding:
>>> nieval (input ("Enter @ nunber:"))
Enter @ number:234
>>> ngeeval (input ("enter an arthematic experission:"))
enter an arthematic experission: 12.0413.0%2
>>> mz
38.0
>>>
20, Program to illustrate that Recursive fuiiction used to calculate
factorial of the given number.
Coding:
det tact (n):
else:
return nffact (n-1)
print (fact (0) )
print (fact (5))
Output,
20
34
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M.Sc (CS)., MPhil, Ph.D., BSharmila B.Se(CS),,B.Ed.,
Lesson 8
STRINGS AND STRINGS MANIPULATION
HANDS ON EXPERIENCE:
1. What will be the output of the following python code?
Coding:
prant (stri*3)
Output:
| Schoo1schooischoo1
2. Write a python program to find the length of a string,
Codi
‘strtinput ("Enter a string”)
print (len(str))
Output:
Enter @ stringcomputer
35
nutp://ovww.youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
3.Write a program to print integers with ° on the right of specified
width
Coding:
Output:
widen 2(r<3a)
wan ecre7a)
4.Write a python program to display the given pattern.
COMPUTER
COMPUTE
COMPUT
COMPU
coMP
com
co
ci
Coding:
index -1en (sera)
per2~ seri(O: index)
Outputs
Enter stringCOMPUTER
36
http://www youtube.com/c/CSKNOW! FNGFOPFNER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
5.Write a program to add a prefix text to all the lines in a string
Coding:
import textwrap
strisinput("enter string")
exturap.dedent (str)
wetexturap. fill (t, width=50)
fetexturap. indent (u,'>')
print ()
print (f)
print ()
Output:
eater stringy Python is videly used high-level, general purpose, interpceted,
dmnanic proyenming Lsnguage, Its design philosophy emphasizes code resdbility
ad its syntax allows progcemers to express concepts in fener Lines of code t
Yan possible in Languages such os C# or Java,
>. Tython is @ widely noed high-level, general
purpose, interpreted, dynanie programing
language, Its design philosophy enphasizes code
readability, and ite syntar allows programers to
Dexpress concepts i fever Lines of cade than
pyossible in Languages such as C++ or Java,
37
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
6.Write a program to create a mirror of the given string. For
example,"wel”="lew”
Coding:
Gee reverse (a)?
et inpue ("Enter @ string")
peine (3)
print ("The reversed string(using Loops) is ",ende"m)
Deine (reverse (o})
Output:
Enter @ stringhello
The original string is + hello
‘The reversed string(using loops) is : olleh
7. Write a program to remove all the occurrences of a given character
ina string
Coding:
strisinput ("Enver string")
chsinput ("Enter a character to be removed")
print (str1.replace(ch.""))
‘Output:
Enter otringeomputer
Enter a character to he renovedu
compter
38
hupi//www.youtube.com/e/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
8, Write a program to append a string to another string without using
+= operator
Codi
stri=input ("Enter first string”)
str2einput ("Enter second string")
print (stri¢str2)
Output
Enter first stringcomputer
Enter second stringectence
computerscience
9. Write a program to swap two strings:
Coding:
strisinput ("Enter string 1")
str2=input ("Enter string 2")
vemp=stri
strisstr2
str2=temp
print ("After swapping")
print (str1)
print (str2)
Output:
Enter string icomputes
Enter string 2actence
After svapping
computer
39
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
10. Write a program to replace a string with another string without
using replace()
Coding:
weed = dapat ("Eneer « series")
print (seri)
Beri= input ("enter a string to repiacea"
print (seri)
Outpu
Enter a stringcomputer
computer
enter a string to replacedscience
11, Write a program to count the number of characters words and lies
ina given string.
xestri.count (!\n!)42
print ("Mimbers of a characters",c-x+1)
print ("Numbers of a words", w4x-1)
Outp
Enter stringwelcowe to python programing
Munbere of a characters 26
Wunbers of @ vords 4
Numbers of a lines 1
40
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
EXAMPLE-PROGRAMS
Program to access each character with its positive subscript of a
giving string
for d in stel:
print ("Subscript (*, index,
Output:
Subseripel 0)
Subseripe (
Subseripet
Subserins |
Subsceipet
Subserips (
Subseripet
oaonnes
:
:
1
if
a
2. Program to access each‘charaéter with its negative subscript of a
giving string
Coding:
strisinput("Bater a string:
inder=-1
valle dndew=-(Len(strl}):
son abseil" Ani") 5 "sre
Outp
Subscript ~1
Subseripe!
Subscript [
gussesaeer
Subscript
Subsceapet
Subssripel
cannon
a
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M.Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
3. Code lines to delete a particular character in a string.
‘Codin;
Output:
rraceback (nost recent call last)
File "c:\Users\Kuraran\appData\Local \Prograns\zython\zython37\8.3.py", Line 2,
in exodule>
del stei(2)
rypesrror: ‘str object doesn't support ivem deletion
4,Code lines to delete a stringvariable.
eEI~"How about you"
print (str)
Outp
ow about you
freaceback (nost recent call last):
File "c:/Users/Runatan/AppData/Local/Prograns/Python/Python37/8.5.py", line 4,
in aodule>
print (str)
tes eae nel wer
42
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
§5.Program to slice substrings using for loop.
Coding:
for i in strl:
print (stri{:indext1])
index+=1
Output
<
come
comeu,
CcomPuTE
6 Stride when slicing string,
Coding:
strl="Welcone to learn eythor™
print (str1(10:16})
[print (str1 (10:16:
ie (strl[10:16:
t_(strl[::3])
Output
learn
Weeoenyo
43
hhttp://www.youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
7.Example forthe format ) function.
Number 2: 54
vhe sum of 34 and s4is 88
8.Example for the Membership Operatots
Coding:
stei=inpat Menter a strin:
serze"chennai™
if'ste2 in seri
print ("Found")
elset
print ("Not Found”)
Output
Enter a string:chennai G HSS>
<= RESTART. ¢./Uscis/unasau/AypDate/te
Enter a string:Govt G HSS,Ashok Nagar
Not Found
rol
44
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
9.Program to check whether the given string is palindrome or not.
Coding:
sergtestel [index]
Sndex=
int ("The given string
if (stele=str2
Print ("Hence, the given string is Palindrone")
)\athe Reversed string={)".format (str, str2))
els
pein (thence, Ube given is uot palindrome")
Output
‘saver a string:malayalan
‘the given string =nalayalan
‘The Reversed string-malayalan
Hence, the given string is Palindrone
RESTART: C:/Users/Ruraran/appDeta/Le
Eater a string:welcone
‘The given string =velcone
"The Reversed string=encci ew
Hence, the given is not a palindrane
45
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
10-Program to display the following patter.
S prine (eee*)
Output:
11.Program to display the‘number of vowels and consonants in the
given string
Print ("The given string contains () vovels and {} consonants*.format (vc)
Output:
Enter a string:Tamilnadu school Education
‘The given string contains 11 vowels and 15 consonants
46
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
12, Program to create an Abecedarian series. (Abecedarian refers list
of elements appear in alphabetical order)
for i in stel:
print (Gaste9) -ande'\r")
Output:
13.Program that accept a string from the user ‘and display the same
after removing vowels from it!
Coding:
def rem_vowels(s)?
print ("The string without vowels:
strisinput ("Enter a String: ")
rom yowcls (2tri)
temp_str)
Output:
iter a String: Mathematical fundations of Computer Science
The string without vowels: Mthmtcl fndtns £ captr Scene
a7
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
14, Program that count the occurrences of a character in a string,
‘Codin;
ae come tered
cl
seturn el
put ("Enter a String: *)
heinput ("Enver a character t2 be searched: *)
fentecount (SEr1,c8)
PEIAE(*TSe given character {) is occurs {) tines in the given string". fomat(ehyent)}
Output:
Enter a String: Software Engineering
Enter a character to be searched:
The given character e is occurs 3 times in the given string
>
48
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, BSharmila B.Se(CS),,B.Ed.,
Lesson 9
LISTS, TUPLES,SETS AND DICTIONARY
HANDS ON EXPERIENCE:
1. What will be the value of x in following python code?
Coding:
x = len(Listi)
print (x)
Output:
4
2. What will be the output of the following code?
Coding:
List=[2*x for x in range(S}]
print (List)
Output:
49
hnttp://www.youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
3. Write a program to remove duplicate from a lst.
Codins
mylist=(1,2/3,4,8,1/2,3,4,8)
=o
rrappend(t)
prince)
Output:
(1, 2, 3) 4 51
4.Write a program that prints the maximum value\in a Tuple,
Coding:
tuplet = (8,17,15,20,7,3) r
print ("ax imum’ value", tax (euplet))
Output:
Maximum value 20
5. Write a program that finds the sum of all the numbers in a tuples
using while loop.
Coding:
t=
telus tena)
said]
print (2)
50
bitp:/wwww. youtube com/e/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
6.Write a program that finds sum of all even numbers in a list.
Codin;
aise = (4,2,9/4,5,6/7,8,9/201
print ("Sum of even nunberse)
Output:
Sun of even number 30
7. Write a program that reverse ¢ list using’a loop.
Codi
fiise = (,2/3,4,5)
tet
wnile 2
print (ist {})
init
Output:
eres
8, Write'a program to insert a value in a list at the specified location.
Codi
list = [1,2,4,5]
List insert (2,3)
print (list)
Output:
[1 2, 3, 4 51
51
|ntp:/swww.youtube.com/e:CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
10. Write a program that creates a list of numbers from 1 to 50 that
are either divisible by 3 or divisible by 6
Coding:
a=0
for i in range(1,51)
if 443 == 0 or a86
‘append (i)
print (a)
Output:
[3 6) 9, 12, 15, 18, 24, 24, 27%, 30, 33, 36, 39, 42, 45, 40}
11, Write a program to create a list of numbers in the range 1 to 20.
Then delete all the numbers from the list that are divisible by3
Codin;
asa
for x in range(1,21)
a.append (x)
for nei in enumerate(a) :
a(iaseeo)
del atnl
peant (a)
Output:
[te er ae 5, 7, 8, 10, 41, 33, 14, 16, 17, 49, 20)
52
‘http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
12, Write a program that counts the number of times a value appears
in the list. Use a loop to do the same
Codi
Li = [8,6,8,10,8,20, 10,8,8)
x8
x = Liscount (x)
eine (x)
Outp
5
13, Write a program that prints the maximum and minimum value in
a dictionary.
Codin,
dict = (1a! 210, 'b!:20,'0! 35)
v= dict.values ()
print ("Maxima =", mx (¥) }
print ("Minima =",min(v)}
Output:
Naxtmm = 20
Minimum ~ §
53
http://www. youtube.com/:/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
EXAMPLE-PROGRAMS
1 Python program to update/change single value.
Codin;
MyList=[2, 4,5,8,10]
print ("MyList elements before update...")
for x in MyList:
print (x)
MyList [2]
print ("MyList elements after updation... ")
for y in MyList:
print (y)
Output:
MyList elements before update...
54
http://www youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
2.Python program to update/change range of values.
Coding
MyList—(1,3,5-7,9)
print ("List odd numbers. ..")
for x in MyList:
print (x)
MyList [0:51=2,4,6,8,10
print ("List Even numbers...)
for yin Mynise:
print cy
Output
3.Program that creates alist of numbers from 1 to 20 that are
divisible by 4.
Coding
divey4=[)
for i in range(21):
2 £(284==0):
divBy4. append (i)
print (divBy4)
Output:
(0, 4, 8, 12, 16, 20]
55
Iitp:/Avww.youtube.com/e/CSKNOWLEDGEOPENER,\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
4,Program to define a list of countries that are a member of BRICS.
Check whether a county is member of BRICS or not.
Coding:
country=["India", "Russia", "Srilanka", "China", "Brazil"]
is member-input ("Enter the name cf the country:")
if is member in country:
print (is menber,"Is the menber of BRICS")
else:
print (is menber,"Is not a menber of BRICS")
Output:
Enter the name of the country:India
India Is the member of BRICS
>>
== RESTART: C:/Users/Kumaran/Applata
Enter the name of the country:Japan
Japan Is not a member of BRICS
56
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
5.Python program to read prices of 5 items in a list and then display
sum of all the prices, product of all the prices and find the average.
Coding:
itens=11
prodel
for & in range(5)¢
print ("enter price for Stam ()-* format (141))
peint (input ())
items. append(p)
for j in range(len(items)
Print ("Price for item {}=Rs. ()". format (j+1, items(31))
ptod-prod*items(j)
print ("sum of all prices = Rs.", sum(items))
print ("Product of all prices = Rs.", prod)
print ("Average of all prices = Rs." sum(items) /len(items))
Output:
Enter price for item 1:
Enter price for item 2:]
Enter price for item 3:
Enter price for item 5:
Price for item 1=Rs.5
Price for item 2-R=.10
Price for item 3=Re.15
Price for item 5=Rs.25
Sum of all prices = Rs. 75
Product of all prices = Rs. 375000
Average of all prices = Rs. 15.0
7
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
6.Program to create a list of numbers in the range I to 10. Then delete
all the even numbers from the list and print the final list.
ge (231):
Nun. append(x)
print ("the List of numbers from 1 to 10=*,mum)
Sor index, in enumerate um):
LE(GAZ=0)
Sot mime inaes)
Jprint("the List after deleting even mnber:
Output:
he List of numbers from 1 to 10= [1, 2, 3y 4y Sy 6 Ty 8, 8 10)
The List after deleting even numbers = {1, 3, 5, 7, 3]
7.Program to generate in the Fibonacei'series and store it in a list.
Then find the sum of all values:
Fibo. appends)
Eine (7
Output:
Enter no. of terms: 10
Fibonacci series uptol0terms is:[0, 1, 1, 2 3, 5, 8 13 21, 34]
‘The sum of Fibonacci series: 96
58
hhttp://www.youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
8.Program to return the maximum as well as minimum values in a
list.
a=max (n)
bemin(n)
veturn(a. b)
Num = (12, 65, 84, 1, 18, 85, 99)
(Max_Num, Min_Num)"Min_Max (Num)
print ("Maximum value=", Max Num)
print ("Minimum value=",min Num)
Output:
Maximum valui
Minimum valu!
9,Program to swap two values using tuple assignment.
Codin;
a=int (input ("Enter value of
Deint (input ("Enter value of
print ("Value of A =",a,"\n Value of B=",b)
(arb)=(b,a)
print ("Value of A=",a,"\n Value of B
Output:
Enter value of A:54
Enter value of B:38
Value of A= 5¢
value of B= 38
value of A= 38
Value of B= 54
>>>
59.
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
10-Program using a function that retums the area and circumference
of a circle whose radius is passed as an argument.two values
using tuple assignment.
def Circle(r):
return(pitr*r, 2*pitr)
radius=float (input ("Enter the Radius:"))
(area, circum) =Circle (radius)
print ("Area of the circle=",area)
print ("Circumference of the circle:
circum)
Output:
Enter the Radius:5
area of the circle= 76.5
Circumference of the circle= 31.400000000000002
11 Program that has a list of positive and negative numbers. Create a
new tuple that has only positive numbers from the list.
Coding:
51-8, 6,8,-4,3/1)
Positives ()
for i in Numbers:
if 10:
Positive += (i, )
jprint ("Positive Nunbers:", Positive)
Output:
Positive Numbers: (5, 6, 8, 3, 1)
>|
60
|ntp://www.youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
12, Program to access all the values stored in a dictionary.
1221",
‘Tanilselvi',
school" :*CGHSS",
‘Address':'Rotler St.,Chennai 112")
print (yDict)
print ("Register Munber:",MyDict{"Reg_No"])
print(*Nane of the Student:",MyDict{"wame'])
print ("school:*,
print ("address:
MyDict ["Schoo!"})
{ MyDict["Address"])
Output:
("Heg Jo's "221", "Wane: anilsele", ‘School's ‘Cass, "des
Register Mer: 121
Bane of the Stade: tailselni
Schoo: CS
ares: tle St, hema 112
»
St Chemal 112")
61
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M.Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
Lesson 10
PIHIYTHON CLASSES AND OBJECTS
HANDS ON EXPERIENC]
1. What is the output of the following program?
Coding:
Output:
2. Write a program using class to accept three sides of a triangle and
print its area,
Coding:
clase area?
def area(sel£,b,h) :
Print ("Area of triangle", (oth) /2)
reat)
ne (2npue ("Enter base") )
int (input ("Enter height”) )
ea (b,h)
Output:
Encer bases
Enter heights
Acca of triangle 15.0
62
|hup:swww.youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
3. Find the error in the following program to get the given output,
odin
class Fruits:
ef _init_{eelf,t1,£2):
selt.ti=t1
selt.t2-02
et displey|selt)
print ("Fruit 1 = ts,Fruit 2 = 49" $(self.t1,self.22))
F = Fruits('ppkle! ,'Hango')
del Fdisplay
Fadispay()
Outpu
Traceback (aust recent call Last}:
File "C:/lsers/ursve/Deskeop/12.19", Line 6, in
del Fdisplay
Avtesbutedreor: dieplay
4, What is the output of the following program?
Coding:
class Greeting:
det _snit_(self,nene) :
Belt. “iavesnawe
ef diplay (wel):
print ("Good Horning”, self.__nane)
wa yrorecting|"Biseta Bauwas|
ob}.display()
Output:
Good Morning Bindu Nadavan
>>>
63
hhtps/www.youtube.com/e/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
5. Write a menu driven program to add or delete stationary items.
You should use dictionary to store items and the brand.
Coding:
stationary()
print ("\atsAddSten\a2 Delete Sten\nd Beit")
chrint input "\nErter your choice:™))
vhilefobeet) or (obee2):
nt (input |"\nEnter the mmber of item to be added in the Dictionary:")
for 4 im ranget(a):
itemrinput("\nEnter an item nane:*)
Drandinput "\ndnter the Brand same:")
stationary[iten] brand
print (stationary)
elit(etee2|:
ritewsinput "\aEnter the iten to be removed from the Dictionary:")
stationary. pop(citen)
print (stationary)
ccbrint (input ("\nfnter your choice:*))
64
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
Output:
LeAda_ stem
2 delete item
Enter your choice:
(pent: 'rorite!, 'penesi': camilin')
('pencii': "eamslin'»
65
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
6, Write a program using class to store name and marks of students in
list and print total marks.
Coding:
clase eotalr
nawe=()
marke [)
Get get (sete)
self.mmmint (input ("How many student s:"))
‘for 1 in range (se1£.nus)
self.nane.append (input ("Ener students neme:"))
self.mmck.eppend{int (input("Enter mark of the students:")))
det display(self):
0
for 4 in range |se1f-nun) :
print (self.name(),":",se1.mark(4))
ceteseLf mark(s]
prine ("Total mark :*,¢)
orstoral()
tot.get()
toe-atepiey()
Output:
Enter students name: AAA
Enter mark of the students
Enter students name:BBB
Enter mark of the studente:100
Enter students name:cce
0
wa: 90
BBB : 100
ccc + 100
Total mark : 20
>>>
66
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
7. Write a menu driven program to read, display, add and subtract
two distances.
Coding:
class distance:
‘def _init_(setf):
self distT=0
self dist2=0
def readsetf:
self dist mint(nput‘Enter distancel:")
self. dist2intnput( "Enter distance?: "))
def disp(celf)
rin("Difference in Distance: , self dist-self.dst2)
sedistanced)
dey’
while(ch—~y):
Brin" accept n2 Display Totala4 Subtract)
‘c=int(input("Enter your choice”))
1).
read)
lisfe—2):
67
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
Output:
laccept
2.Display
3 Total
4 Subtract
Enter your choice
Enter distance1: 120
Enter distance2: 230
Do you want to continue y/ny
accept
2.Display
3-Total
4.Subtract
Enter your choice?
Distancel: 120
Distance2: 230
Do you want to continue y/ny
accept
2.Dispiay
3-Total
4.Subtract
Enter your choices
Total Distance: 350
Do you want to continue y/ny
accept
2.Dispiay
3.Total
4-Subtract
Enter your choice4
Difference in Distance: -110
Do you want to continue y/nn
68
‘nttp:// www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
EXAMPLE-PROGRAMS,
1.Program to define a class and access its member variables.
Coding:
class Sample: class variables
x,¥=10,20
‘S=sanple () #class instantiation
print ("value of x =",S.x)
print ("Value of y =",S.y)
print ("Value of x and y =",S.x+3.y)
Output:
Value of y = 20
Value of x and y ~ 30
>>|
2.Program to find total and average Marks using class.
Coding:
class student:
i KA ae KZ, mae K3=43, 9272 fetes variable
def process (self) #class method
sun=Student .markl+Student .mark2+Student .mark3
avg=sun/3
print ("total Marks='
print ("average Marks=
sum)
ava)
S.process()
Output:
Total Mark:
average Mark
>>|
207
69.0
69.
Inup:/vww.youtube.com/e:CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
3.Program to check and print if the given number is odd or even
using class,
Coding:
class odd_pve
Gee check (se2£,nun):
Tt numeceo™
Print (num,* is Even nunber*)
else:
pHinc(nun," is og munner")
neodd_Even ()
netanpue ("Enter @ value:"))
Bucheck (x)
Output:
Enter a value:4
4 is Even number
4.Program to illustrate Constructor.
Coding:
class Sample:
def _init_(self, nun):
print ("Constructor of class sample.
eelf.num=num
print ("the value is
S=Sampie (10)
a)
Output:
Constructor of class Sample...
The value is : 10
70
http://www youtube com/e/CSKNOW! ENGFOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
5.Program to illustrate class variable to keep count of number of
objects created.
Codi
class Sample
sumed
def _init_{self, var):
‘Sample numt=L
self.var=var
print ("The object value i:
print ("The count of object created =",Sample.num)
st=sample(35)
‘2=Sanple (35)
sO=sample(45)
Output:
The object value is = 15
The count of object created
The object value is = 35
The count of object created = 2
The object value is = 45
The count of object created
>>
nm
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M.Se (CS)., M.Phil, Ph.D., B.Shamila BSe(CS).,B.E«
6.Program to illustrate about the _del_() method.
Coding:
oe _gBeREIRS POISE GF Cb Genie Lae, sampte- nom)
Srinetcofect with walue 4d de'enie teow the ecipartsel£.vext
Output:
foe yates of cites vartanie to 1
be valce of class varlanie ie 2
fs soject yeioe fs'= 8
7.Program to illustrate private and publié variables.
Coding:
less SeRp Te?
det indt_
nly m2):
self.
det display (elt):
prine(*Class variable 2 =", self._n2)
Sesample(i2, 14)
S.display0
print ("Value 2
Prine ("value 2
3.1)
Sn)
‘outpur
clase variable 1 = 12
Class variable 2= 14
value T= 12,
‘Traceback (most recent call last):
File ":/Users/Kunaran/Appbata/tocal/Prograns/Python/ Python37/10.7.py", Line 1
ay in enodule>
rine ("Value 2 = *,8._92)
AttributeBsror: ‘Sample" abject has no attribute * 12"
2
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
8.Program to calculate area and circumference of a circle.
Coding:
Sines. Cincier
pisa.i6
Get _init_(seit, radius):
elf. radius-radius
def area(self):
Seturn Cirele.pi* (self. radius**2)
def circunference (self) =
Feturn 2*Cirele.pitseif radius
reint (input ("Enter Radius: "))
cacirele (rd
print ("the Area =",C.area())
Print ("the Circumference —", C.circumference())
Output:
|epeer maaius: 5
The Area = 78.5
The Circumference = 31.400000000000002
boo
B
nttp:// www.youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M.Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
9.Program that keeps record of books available in you school library.
Coding:
class Library:
def _ init__(self):
Self. booknane=""
self.author=""
def getdata (self):
self. booknane=input ("Enter Nane of the Book:")
self.author=input ("Enter Author of the Book:")
def display (self):
print("Nane of the Book: ",self.bookname)
print ("Author of the Book: ",self.author)
print ("\n*)
book=[] fempty list
print ("1. Add New Book \n 2.Display Books")
resp=int (input ("Enter your choice:"))
if(resp==1):
IsLibrary()
L.getdata()
book. append (L)
elit (resp=2):
for x in book:
x.display()
else:
print ("Invalid input....")
ch=input ("Do you want continue....")
74
hnttp:// www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
Outpu
dx Bo
aay ses
ecer yu cic
bce in of Sx: Pagrmiag in CHF
ene ator of the Boks aman
oo you wnt cote.
‘apy Boks
cer yur cance
be ace of te Star yan
bce ator of te Sok. akisan
bo you wnt crtine..y
dad ex eco
spay soe
cer your cues
bee ie of te Boadmsced een
esr ator of the Gott hs
so you wnt cxtie..g
2.spay Boks
bce yous ccs
ee ine of he Sxk:vrking ith patie
ec nator of te Bok. Grislar
oo you want comie...7
ae ok
2.nspay aks
bce your nice
nce ie of emote strarure
nace toe ot te Bese
bo yu wnt cotie...y
I, de Bok
2.pay Boks
bce yur coe
eae ae at ce Sorte Itromtion to Dak Syten
tr ator of te Sok. srevaan
no you wane comame..7
ad Bex Be
2.pay mks
bce yur ace
ne of the ark: orang inc
toe of te Be Raman
nae of the sok: eae ation
aoe ofthe Bc TG facister
5
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M.Se (CS)., M.Phil, Ph.D., B.Shamila BSe(CS).,B.E«
lane of the Book: Advanced eython
lator of the Book: Or vsiya
lane of the ook: Working with Openttice
lator of the Book: 8.7. Goaisanlar
ane uf Ue Buk: ate Struture
lator of the Book: x.tenin
wane of te Bok: An ToLzvucLlon Wo Daebave Systen
lauthor of the Book: x. Stenirasan
loo you want cookin...
>
76
http://www. youtube.com/:/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
10.Program to accept a string and print the number of uppercase,
lowercase, vowels, consonants and spaces in the given string,
Coding:
lass Seeing:
nit_(sel6):
det
Tovercase0
cele consonant +0
self -spaces=0
der gerste(sein:
Self. string-str (input ("enter a string!
Count apper wel)
for ohn self.etring?
Se(cheisupper 0)
et count, tover (ett)
‘eteh-islover 0)
‘self lovercaret=l
ot count_vowels(sel#l =
for eh in self. string:
fe(en an (eats tar et
seit. woveler=t
et count, consonants (self)
for oh in self.oteang
“it(ch not in(*aty at
‘self. consonanter-l
ot count, space elf)
Tee
‘self spaceste
‘execute (self)
coun UPBeE
reoune lover)
eount_eonsenaats ()
peinc(rthe given string contains...*)
Eine ("ed Uppercase lecterstiself uppercase)
Print ("ed Lowercase letters"tself_ lowercase)
DEint ("ed VYorels"sseir. vowels)
Eine (rea Consonanes"ese1t-consonants)
rine ("ed spacestsself- spaces)
is = seeing)
s.qetstr()
execute)
aisplay)
7
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
Output:
Enter a String:Welcome To Leai
‘The given string contains...
5 Uppercase letters
24 Lowercase letters
13 Vowels
16 Consonants
4 spaces
>>>
78
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
11 Program to store product and its cost price. Display all the
available products and prompt to enter quantity of all the products.
Finally generate a bill which displays the total amount to be paid.
Codi
cas ton
cde
Tyee
Least price)
peat gat)
aaa:
sel gpin ip tte oof pets you eed sees")
for in elt:
sje
def dolls
tt"
print )
print rofict
print
forx it maptalt.p):
int elf._peed oxen, "ee self,_prod naa] "o\'self,_cost pricela))
His ramelselfp):
(Fiat ingue( "tater the quaity forthe product code 84
pod ua gpg
twtal peicestocalpriotselt. cost prioe[]!self, prod qua]
ped exits)
79,
http://www. youtube.com/c/CSKNOWLEDGEOPENER‘VDevanathan M.Se (CS)., M.Phil. Ph.D., B Sharmila B.Sc(CS),B.Ed.,
pipempee anata pene
J Soe
ia i a ls py a)
sna, seme pe, ce
80
hnttp://www.youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Se (CS)., MPhil. PhD., B Sharmila B.Sc(CS).B.Ed.,
Outpu
enter no. of products you need to store: 5
exter Product Sane: Profuct-A
enter cost price: 25
enter eroduct code: 201
fencer eroduct wane: Product-B
ter cost price: 35
enter Product Cade: 301
fencer rroduct wane: Product-<
enter cost price: 35
enter Froguct Code: 402
enter eroduct sane: Protuct-D
enter cost price: 50
enter Eeoduct Code: 502
enter eroduct mane: Product-E
ter cost price: 120
stack in store
Product code
Product wane cost Brice
io Produce-k 8
an Prodact- 8
soa Poel 35
fon Prodce-D 3
san Poet rt)
inter the quantity for the product code 103 : 10
enter the quantity for
Product code
‘otal Amount
>>>
3325
http://www. youtube.com/c/CSKNOWLEDGEOPENER
Product Han |
the product code 201 : 15,
Invoice Receipt
cost Pelee
ie Prodce-k 8
81
fencer the quantity for the product code 301 : 10
enter the quantity for the product code 401 : 20
inter the quantity for the product code $01 : 10
uantity
‘otal Ancunt
0 350
an Predact-B 5 8 525
san oodct-¢ 5 » 30
faa Produt-> 50 2 000
sat Predact- 120 » 200\V.Devanathan M.Sc (CS),, MPhil, Ph.D. B Sharmila B.Se(CS).,B.E4
CHAPTER 12
STRUCTURED QUERY LANGUAGE
HANDS ON EXPERIENCE:
1. Create a query of the student table in the following order of fields
mame, aye,place aud adie.
CREATE TABLE student(name char(20), age integer, place
char(15),
admno integer not null primary key);
2. Create a quety to display the students table with students of age
more than 18.withunique city.
Select * from sttident where
>=18 group by place;(or)
and place="Coimbatore”;
Select * from student where age
hnetp:// www. youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD. B.Sharmila B.Se(CS).,B.Ed.
3. Create a employee table with the following fields employee
number,employee name, designation, date of joining and basic pay
Create Table employee(empno integer, ename char(30), desig
char(20), doj datetime, basic integer):
4. In the above table, set the employee number as primary key and
check for NULL values in any field.
Alter table employee modi
83
http://www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M.Sc (CS),, MPhil, Ph.D. B Sharmila B.Se(CS).,B.E4
5. Prepare list of employees who are Managers.
Select * from employee where desig="Manager”;
© Seve bnesinysas 720brimecne
6. Consider the following employee table. Write SQL Commands for
the qtns(i) to (v).
EMPCODE| NAME | DESIG | PAY | ALLOWANCE
‘S1001 Hariharan | Supervisor_| 29000 |12000
P1002 Shaji [Operator | 10000_|5500
P1003 Prasad [Operator | 12000 | 6500
‘C1004 Manjima | Clerk ‘8000 [4500
M1005 Ralieesh | Mechanic | 20000 [7000
i) To display the details of all employees in descending order of pay
Select * employees order by pay dese
24
htp:/swwwyoutube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD. B.Sharmila B.Se(CS).,B.Ed.
1 euamptrnyalengS7 2b mylene I)
ii) To display all employees whose allowance is between 5000 and,
7000.Select * from employees where allowance>=5000 and
iii) To remove the employees who are mechanic.
Delete fiom employees where desig=’Mechanic’;
iv) To add a new row
Insert into employees(empcode, ename, desig, pay, allowance)
85
bap:/www. youtube.com/c/CSKNOWLEDGEOPENER\V.Devanathan M.Sc (CS),, MPhil, Ph.D. B Sharmila B.Se(CS).,B.E4
values(A1005".’Balaguru’ ,"Engineer’ 30000,
v) To display the details of all employees who are opetators.
Select * from employees where desig=’Operator’-
7.Write a SQL Statement t0 create a table for employee having any
five fields and creaté'a table constraint for the employee table
Create table Employee(‘empcode char(10) not null, ename char(30),
design char(20), pay integer, allowance integer, PRIMARY
KEY (empeode)):
86
http://www youtube.com/c/CSKNOWLEDGEOPENER‘V.Devanathan M.Sc (CS)., M.Phil, PLD, B Sharmila B.Sc(CS).B.Ed.,
CHAPTER 13
PYTHON AND CSV FILES:
HANDS ON EXPERIENCE:
1. Write a python program to read the following Namelist.csv file and
sort the data in alphabetical order of names in a list and-display the
output.
A 8
1 SNO NAME OCCUPATION
2 1 NIVETHITHA ENGINEER
3 2 ADHITH DOCTOR
4 3 LAVANYA SINGER
5 4 VIDHYA ‘TEACHER
6 5 BINDHU LECTURER
Program:
import esv, operator
ifile~"c:\\pyprg)\namelistiesv"
Fopentifile,"’)
reader=esv.reader(f)
next(reader)
sortedlst~sorted(reader,key-operator.itemgetter(1))
fort in sortedlst
print(r)y
feelose
87
Inup:/www.youtube.com/e/CSKNOWLEDGEOPENER\V.Devanathan M.Se (CS)., M.Phil, Ph.D., B.Shamnila B.Se(CS).,B.Ed.,
Output:
(2). ‘ADHITH’. 'DOCTOR']
(3, 'BINDHU’, LECTURER’)
(3, 'LAVANYA', 'SINGER)]
(1, 'NIVETHITHA’, 'ENGINEER’]
(4, 'VIDHYA’, 'TEACHER']
2. Write a python program to accept the name and five subjects
‘marks of 5 students. Find the total and store all the details of the
students in a CSV file
import esv
Istheader=['Sl.no',Name',’TamilEnglish' /Maths'Séience’'Social’’T
otal’)
with open(‘c:\\pypre)\students.csv','w') as f
w=csv.writer(f)
w.writerow(Istheader)
for i in range(5):
total-0
input("Enter Name")
print("Enter marks in 5 subjects")
for jin range(5)
m=input()
marks append(in),
total-total+int(m)
‘w.weriterow( {i+ name,marks{0],marks{ 1}, marks[2],marks{3],marks[4
J,total])
Eclose
fopent'cs\\pyprelistudents.csv'’)
reader=esv.reader(f)
for row in reader:
print(row)
fclose
88
‘hup://www.youtube.com/c(CSKNOWLEDGEOPENER,