50% found this document useful (2 votes)
6K views66 pages

Hands On Practice

The document contains chapter summaries and hands-on practice problems for a +2 Computer Science course. It covers topics like functions, data abstraction, scoping, algorithms, Python variables and operators, control structures, functions, strings and string manipulation. For each chapter, it provides 2-8 practice problems with sample code and outputs to solve common programming tasks related to that chapter's topic.

Uploaded by

Priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
50% found this document useful (2 votes)
6K views66 pages

Hands On Practice

The document contains chapter summaries and hands-on practice problems for a +2 Computer Science course. It covers topics like functions, data abstraction, scoping, algorithms, Python variables and operators, control structures, functions, strings and string manipulation. For each chapter, it provides 2-8 practice problems with sample code and outputs to solve common programming tasks related to that chapter's topic.

Uploaded by

Priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

+2 Computer Science

Hands on Practice

Video Lessons for


+2 Computer Science
+2 Computer Applications
+1 Computer Science
@
https://www.youtube.com/c/alphakarumpalagai
Alpha Karumpalagai +2 Computer Science – Hands on Practice 1
Chapter 1 Function
1. Write algorithmic function definition to find the minimum among 3 numbers.

let min3 x y z :=
if x < y then
if x < z then
return (x)
else
return (z)
else
if y < z then
return (y)
else
return (z)

2. Write algorithmic recursive function definition to find the sum of n natural numbers

let rec sum n :=


if n <= 1
return (n)
else
return(n) + sum(n - 1)

Alpha Karumpalagai +2 Computer Science – Hands on Practice 2


Chapter 2 Data Abstraction

NO Hands on Practice

Alpha Karumpalagai +2 Computer Science – Hands on Practice 3


Chapter 3 Scoping

1. Observe the following diagram and Write the pseudo code for the following

1. sum()
2. num1 :=20
3. sum1()
4. num1:=num1 +10
5. sum2()
6. num1 := num1 + 10
7. sum2()
8. sum1()
9. num1 := 10
10. sum()
11. print num1

Alpha Karumpalagai +2 Computer Science – Hands on Practice 4


Chapter 4 Algorithmic Strategies

NO Hands on Practice

Alpha Karumpalagai +2 Computer Science – Hands on Practice 5


Chapter 5 Python Variables and Operators

NO Hands on Practice

Alpha Karumpalagai +2 Computer Science – Hands on Practice 6


Chapter 6 Control Structures
1. Write a program to check whether the given character is a vowel or not.

ch=input ("Enter a character :")


if ch in ('A','a','E','e','I','i','O','o','U','u') :
print (ch,' is a vowel')
else :
print (ch,' is not a vowel')

Enter a character :a
a is a vowel

Enter a character :x
x is not a vowel

Alpha Karumpalagai +2 Computer Science – Hands on Practice 7


2. Using if..else..elif statement check smallest of three numbers.

a=int(input ("Enter a number 1 :"))


b=int(input ("Enter a number 2 :"))
c=int(input ("Enter a number 3 :"))
if a < b and a < c :
print (a," is smallest")
elif b < c :
print (b," is smallest")
else :
print (c," is smallest")

Enter a number 1 :5
Enter a number 2 :3
Enter a number 3 :2
2 is smallest

Enter a number 1 :7
Enter a number 2 :9
Enter a number 3 :12
7 is smallest

Enter a number 1 :14


Enter a number 2 :4
Enter a number 3 :17
4 is smallest

Alpha Karumpalagai +2 Computer Science – Hands on Practice 8


3. Write a program to check if a number is Positive, Negative or zero.

a=int(input ("Enter a number "))


if a < 0 :
print (a," is Negative")
elif a == 0 :
print (a," is Zero")
else :
print (a," is Positive")

Enter a number 0
0 is Zero

Enter a number -7
-7 is Negative

Enter a number 125


125 is Positive

Alpha Karumpalagai +2 Computer Science – Hands on Practice 9


4. Write a program to display Fibonacci series 0 1 1 2 3 4 5…… (upto n terms)

n=int(input ("Enter Number of Terms "))


t1 = -1
t2 = 1
print ("Fibonacci Series")
for i in range(1,n+1):
t3 = t1 + t2
print(t3)
t1 = t2
t2 = t3

Enter Number of Terms 7


Fibonacci Series
0
1
1
2
3
5
8

5. Write a program to display sum of natural numbers, upto n.

n=int(input ("Enter N "))


sum = 0
for i in range(1,n+1):
sum = sum + i
print("Sum of numbers upto %d is %d", %(n,sum))

Enter N 10
Sum of numbers upto 10 is 55

Alpha Karumpalagai +2 Computer Science – Hands on Practice 10


6. Write a program to check if the given number is a palindrome or not.

n=int(input ("Enter a Number "))


num = n
rev = 0
while num > 0 :
r = num % 10
rev = rev*10 + r
num = num // 10
if n == rev :
print(n, " is Palindrome")
else :
print(n, " is not Palindrome")

Enter a Number 7632


7632 is not Palindrome

Enter a Number 575


575 is Palindrome

Alpha Karumpalagai +2 Computer Science – Hands on Practice 11


7. Write a program to print the following pattern
*****
****
***
**
*

for i in range(5,0,-1) :
for j in range(1,i+1):
print('*',end=' ')
print("\n")

*****
****
***
**
*

Alpha Karumpalagai +2 Computer Science – Hands on Practice 12


8. Write a program to check if the year is leap year or not.

year = int(input("Enter a year: "))


if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print(year, " is a leap year")
else:
print(year, " is not a leap year")
else:
print(year, " is a leap year")
else:
print(year, " is not a leap year")

Enter a year: 1996


1996 is a leap year

Enter a year: 2000


2000 is a leap year

Enter a year: 1900


1900 is not a leap year

Alpha Karumpalagai +2 Computer Science – Hands on Practice 13


Chapter 7 Python Functions

def printinfo( name, salary = 3500):


print (“Name: “, name)
print (“Salary: “, salary)
return

1. Try the following code in the above program

Slno Code Result


1 printinfo(“3500”) Name: 3500
Salary: 3500
2 printinfo(“3500”,”Sri”) Name: 3500
Salary: Sri
3 printinfo(name=”balu”) Name: balu
Salary: 3500
4 printinfo(“Jose”,1234) Name: Jose
Salary: 1234
5 printinfo(“ ”,salary=1234) Name:
Salary: 1234

2. Evaluate the following functions and write the output

Slno Function Output


1 eval(‘25*2-5*4’) 30
2 math.sqrt(abs(-81)) 9.0
3 math.ceil(3.5+4.6) 9.0
4 math.floor(3.5+4.6) 8.0

Alpha Karumpalagai +2 Computer Science – Hands on Practice 14


3. Evaluate the following functions and write the output

Slno function Output


1 1)abs(-25+12.0) 13.0
2) abs(-3.2) 3.2
2 1) ord('2') 50
2) ord('$') 36
3 type('s') <type 'str'>
4 bin(16) 0b10000
5 1) chr(13) \r
2) print(chr(13))
(A new line)
6 1) round(18.2,1) 18.2
2) round(18.2,0) 18.0
3) round(0.5100,3) 0.51
4) round(0.5120,3) 0.512
7 1) format(66, 'c') B
2) format(10, 'x') a
3) format(10, 'X') A
4) format(0b110, 'd') 6
5) format(0xa, 'd') 10
8 1) pow(2,-3) 0.125
2) pow(2,3.0) 8.0
3) pow(2,0) 1
4) pow((1+2),2) 9
5) pow(-3,2) 9
6) pow(2*2,2) 16

Alpha Karumpalagai +2 Computer Science – Hands on Practice 15


Chapter 8 Strings and String Manipulation

1. Write a python program to find the length of a string.

str=input("Enter a string")
length = len(str)
print ("Length of ",str," is ",length)

Enter a string alpha


Length of alpha is 5

2. Write a program to count the occurrences of each word in a given string.

str=input("Enter a string ")


searchstr=input("Enter a search string ")
c = str.count(searchstr)
print (searchstr, " is found ",c," times in ",str)

Enter a string You can not complete a sentence with because because because is a
conjunction
Enter a search string because
because is found 3 times in You can not complete a sentence with because because
because is a conjunction

Alpha Karumpalagai +2 Computer Science – Hands on Practice 16


3. Write a program to add a prefix text to all the lines in a string.

str = """Python programming language has four collections of data types


such as List, Tuples, Set and Dictionary.
A list in Python is known as a sequence data type like strings.
"""
prefix = input("Enter the Prefix String")
i=0
prefixstr = ""
while i != -1:
pos = str.find("\n",i)
if pos == -1 :
break
prefixstr += prefix + str[i:pos]+"\n"
i = pos+1
print("After prefixing")
print(prefixstr)

Enter the Prefix String%%%%


After prefixing
%%%%Python programming language has four collections of data types
%%%%such as List, Tuples, Set and Dictionary.
%%%%A list in Python is known as a sequence data type like strings.

Alpha Karumpalagai +2 Computer Science – Hands on Practice 17


4. Write a program to print integers with ‘*’ on the right of specified width.

str=input("Enter a string ")


n=int(input("Enter number of * "))
print (str+'*'*n)

Enter a string Alpha


Enter number of * 5
Alpha*****

5. Write a program to create a mirror of the given string. For example, “wel” = “lew“.

str1 = input ("Enter a string: ")


str2 = ''
index=-1
for i in str1:
str2 += str1[index]
index -= 1
print ("The given string = {} \nThe mirror image = {}".format(str1, str2))

Enter a string: Alpha


The given string = Alpha
The mirror image = ahplA

Alpha Karumpalagai +2 Computer Science – Hands on Practice 18


6. Write a program to removes all the occurrences of a give character in a string.

str = input ("Enter a string: ")


c = input ("Enter a character to be removed: ")
removedstr= str.replace(c, "")
print ("After removing\n{}".format(removedstr))

Enter a string: alpha karumpalagai


Enter a character to be removed: a
After removing
lph krumplgi

7. Write a program to append a string to another string without using += operator.

str1 = input ("Enter string 1: ")


str2 = input ("Enter string 2: ")
strtemp = str1+str2
str1 = strtemp
print ("After appending\n{}".format(str1))

Enter string 1: Alpha


Enter string 2: Karumpalagai
After appending
AlphaKarumpalagai

Alpha Karumpalagai +2 Computer Science – Hands on Practice 19


8. Write a program to swap two strings.

str1 = input ("Enter string 1: ")


str2 = input ("Enter string 2: ")
strtemp = str1
str1 = str2
str2 = strtemp
print ("Strings after swapping\n{}\n{}".format(str1, str2))

Enter string 1: Alpha


Enter string 2: Karumpalagai
Strings after swapping
Karumpalagai
Alpha

9. Write a program to replace a string with another string without using replace().

str = input ("Enter a string : ")


replacestr = input ("String to be replaced : ")
newstr = input ("String to be replaced with : ")
strlength = len(replacestr)
startpos = str.find(replacestr)
while startpos >0 :
prefixstr = str[:startpos]
suffixstr = str[(startpos+strlength):]
str = prefixstr + newstr + suffixstr
startpos = str.find(replacestr)
print ("After removing\n{}".format(str))

Enter a string : This is a good sis


String to be replaced : is
String to be replaced with : was
After removing
Thwas was a good swas

Alpha Karumpalagai +2 Computer Science – Hands on Practice 20


10. Write a program to count the number of characters, words and lines in a given
string.

str = """Python programming language has four collections of data types


such as List, Tuples, Set and Dictionary.
A list in Python is known as a sequence data type like strings.
"""
lines = str.count("\n")
words = str.count(" ") +lines
chars = len(str) -lines
print(str)
print("Number of lines = ",lines)
print("Number of words = ",words)
print("Number of characters = ",chars)

Python programming language has four collections of data types


such as List, Tuples, Set and Dictionary.
A list in Python is known as a sequence data type like strings.

Number of lines = 3
Number of words = 29
Number of characters = 166

Alpha Karumpalagai +2 Computer Science – Hands on Practice 21


Chapter 9 Lists, Tuples, Sets and Dictionary

1. Write a program to remove duplicates from a list.

n = int(input("Number of Elements in the List"))


numlist = []
print("List Elements")
for x in range(0,n):
num = int(input(""))
numlist.append(num)
print(numlist)
i=0
while i < len(numlist):
c = numlist.count(numlist[i])
if c > 1 :
del numlist[i]
else:
i=i+1
print("List Elements After Removing Duplicates")
print(numlist)

Number of Elements in the List 8


List Elements
2
4
2
5
5
8
4
2
[2, 4, 2, 5, 5, 8, 4, 2]
List Elements After Removing Duplicates
[5, 8, 4, 2]

Alpha Karumpalagai +2 Computer Science – Hands on Practice 22


2. Write a program that prints the maximum value in a Tuple.

n = int(input("Number of Elements in the Tuple"))


numtuple = ()
print("Tuple Elements")
for x in range(0,n):
num = int(input(""))
numtuple +=(num,)
print(numtuple)
m = max(numtuple)
print("Maximum Element is ",m)

Number of Elements in the Tuple 8


Tuple Elements
23
56
31
78
56
32
12
67
(23, 56, 31, 78, 56, 32, 12, 67)
Maximum Element is 78

Alpha Karumpalagai +2 Computer Science – Hands on Practice 23


3. Write a program that finds the sum of all the numbers in a Tuples using while loop.

n = int(input("Number of Elements in the Tuple "))


numtuple = ()
print("Tuple Elements")
for x in range(0,n):
num = int(input(""))
numtuple +=(num,)
print(numtuple)
c = len(numtuple)
i=0
sum = 0
while i < c:
sum += numtuple[i]
i += 1
print("Sum = ",sum)

Number of Elements in the Tuple 5


Tuple Elements
67
23
56
12
87
(67, 23, 56, 12, 87)
Sum = 245

Alpha Karumpalagai +2 Computer Science – Hands on Practice 24


4. Write a program that finds sum of all even numbers in a list.

n = int(input("Number of Elements in the List "))


numlist = []
print("List Elements")
for x in range(0,n):
num = int(input(""))
numlist.append(num)
print(numlist)
sum = 0
for num in numlist :
if num%2 == 0 :
sum += num
print("Sum of Even Numbers in list is ", sum)

Number of Elements in the List 6


List Elements
12
65
78
11
24
56
[12, 65, 78, 11, 24, 56]
Sum of Even Numbers in list is 170

Alpha Karumpalagai +2 Computer Science – Hands on Practice 25


5. Write a program that reverse a list using a loop.

n = int(input("Number of Elements in the List "))


numlist = []
print("List Elements")
for x in range(0,n):
num = int(input(""))
numlist.append(num)
print(numlist)
reverselist = []
c = len(numlist)
i = c-1
while i >= 0 :
reverselist.append(numlist[i])
i -= 1
print("Reverse List")
print(reverselist)

Number of Elements in the List 7


List Elements
12
65
78
32
59
97
46
[12, 65, 78, 32, 59, 97, 46]
Reverse List
[46, 97, 59, 32, 78, 65, 12]

Alpha Karumpalagai +2 Computer Science – Hands on Practice 26


6. Write a program to insert a value in a list at the specified location.

n = int(input("Number of Elements in the List "))


numlist = []
print("List Elements")
for x in range(0,n):
num = int(input(""))
numlist.append(num)
value = int(input("Value to inserted "))
pos = int(input("Position to be inserted "))
print("List Elements")
print(numlist)
numlist.insert(pos,value)
print("List Elements After Inserted")
print(numlist)

Number of Elements in the List 6


List Elements
23
67
87
32
90
45
Value to inserted 55
Position to be inserted 3
List Elements
[23, 67, 87, 32, 90, 45]
List Elements After Inserted
[23, 67, 87, 55, 32, 90, 45]

Alpha Karumpalagai +2 Computer Science – Hands on Practice 27


7. Write a program that creates a list of numbers from 1 to 50 that are either divisible by
3 or divisible by 6.

divBy3or6=[ ]
for i in range(1,51):
if i%3==0 or i%6 == 0:
divBy3or6.append(i)
print("List of elements from 1 to 51 divisible by 3 or 6")
print(divBy3or6)

List of elements from 1 to 51 divisible by 3 or 6


[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]

8. 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 by 3.

numlist = [ x for x in range(1,21)]


print("List Elements")
print(numlist)
i=0
while i < len(numlist):
if numlist[i]%3 == 0:
del numlist[i]
else:
i=i+1
print("List Elements After Removing numbers divisible by 3")
print(numlist)

List Elements
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
List Elements After Removing numbers divisible by 3
[1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20]

Alpha Karumpalagai +2 Computer Science – Hands on Practice 28


9. Write a program that counts the number of times a value appears in the list. Use a
loop to do the same.

n = int(input("Number of Elements in the List? "))


numlist = []
print("Enter List Elements")
for x in range(0,n):
num = int(input(""))
numlist.append(num)
elt = int(input("Element to be counted "))
print("List Elements")
print(numlist)
c=0
for num in numlist :
if num == elt :
c += 1
print("Number of ", elt, " in list is ", c)

Number of Elements in the List? 8


Enter List Elements
63
82
96
45
82
38
82
22
Element to be counted 82
List Elements
[63, 82, 96, 45, 82, 38, 82, 22]
Number of 82 in list is 3

Alpha Karumpalagai +2 Computer Science – Hands on Practice 29


10. Write a program that prints the maximum and minimum value in a dictionary.

n = int(input("Number of Elements in the Dictionary? "))


numdict = {}
print("Enter Dictionary Elements")
for x in range(0,n):
num = int(input(""))
numdict[x] = num
print("Dictionary")
print(numdict)
maximum = numdict[0]
minimum = numdict[0]
for x in range(0,n):
if maximum < numdict[x]:
maximum = numdict[x]
if minimum > numdict[x]:
minimum = numdict[x]
print("The maximum value is ", maximum)
print("The minimum value is ", minimum)

Number of Elements in the Dictionary? 5


Enter Dictionary Elements
12
56
78
45
32
Dictionary
{0: 12, 1: 56, 2: 78, 3: 45, 4: 32}
The maximum value is 78
The minimum value is 12

Alpha Karumpalagai +2 Computer Science – Hands on Practice 30


Chapter 10 Python Classes and Objects

1. Write a program using class to store name and marks of students in list and print total
marks.

class Student:
__name=[]
__tamilmark=[]
__englishmark=[]
__mathsmark=[]
__totalmarks=[]
def getdata(self):
self.n = int(input("Enter number of students: "))
for x in range(self.n):
self.__name.append(input("Enter Student Name: "))
self.__tamilmark.append(int(input("Enter Tamil Mark: ")))
self.__englishmark.append(int(input("Enter English Mark: ")))
self.__mathsmark.append(int(input("Enter Maths Mark: ")))
def calculate_total(self):
for x in range(self.n):
self.__totalmarks.append(self.__tamilmark[x]+self.__englishmark[x]+
self.__mathsmark[x])
def display(self):
print("-------------------------------------------------")
print("Name\tTamil\tEnglish\tMaths\tTotal\t")
print("-------------------------------------------------")
for x in range(self.n):
print(self.__name[x], "\t", self.__tamilmark[x], "\t",self.__englishmark[x],
"\t",self.__mathsmark[x], "\t",self.__totalmarks[x])
print("-------------------------------------------------")

S = Student()
S.getdata()
S.calculate_total()
S.display()

Alpha Karumpalagai +2 Computer Science – Hands on Practice 31


Enter number of students: 3
Enter Student Name: Anu
Enter Tamil Mark: 67
Enter English Mark: 45
Enter Maths Mark: 89
Enter Student Name: Baskar
Enter Tamil Mark: 65
Enter English Mark: 78
Enter Maths Mark: 69
Enter Student Name: David
Enter Tamil Mark: 78
Enter English Mark: 56
Enter Maths Mark: 76
-------------------------------------------------
Name Tamil English Maths Total
-------------------------------------------------
Anu 67 45 89 201
Baskar 65 78 69 212
David 78 56 76 210
-------------------------------------------------

Alpha Karumpalagai +2 Computer Science – Hands on Practice 32


2. Write a program using class to accept three sides of a triangle and print its area.

import math
class Triangle:
def __init__(self,a,b,c):
self.__a=a
self.__b=b
self.__c=c
def area(self):
s = (self.__a+self.__b+self.__c)/2
tarea = math.sqrt(s*(s-self.__a)*(s-self.__b)*(s-self.__c))
return tarea
a=int(input("Enter length of triangle side 1: "))
b=int(input("Enter length of triangle side 2: "))
c=int(input("Enter length of triangle side 3: "))
T=Triangle(a,b,c)
print("The Area =",T.area())

Enter length of triangle side 1: 12


Enter length of triangle side 2: 8
Enter length of triangle side 3: 10
The Area = 39.68626966596886

Alpha Karumpalagai +2 Computer Science – Hands on Practice 33


3. Write a menu driven program to read, display, add and subtract two distances.

class Distance:
def __init__(self):
self.__km = 0
self.__m = 0
def read(self):
self.__km = int(input("Enter Kilometer: "))
self.__m = int(input("Enter Meter: "))
def display(self):
print(self.__km,"Km",self.__m,"m")
def add(self,a,b):
totalmtr = a.__km * 1000 + a.__m + b.__km * 1000 + b.__m
self.__km = totalmtr // 1000
self.__m = totalmtr % 1000
def subtract(self,a,b):
totalmtr = (a.__km * 1000 + a.__m) – (b.__km * 1000 + b.__m)
self.__km = totalmtr // 1000
self.__m = totalmtr % 1000
choice = 1
while(choice!=5):
print("1. Read Two Distances\n2. Display Distances\n3. Add Two Distances\n4.
Subtract Two Distances\n5. Exit")
choice = int(input("Enter your choice : "))
if choice == 1:
print("Distance 1")
d1=Distance()
d1.read()
print("Distance 2")
d2=Distance()
d2.read()
elif choice == 2:
print("Distance 1")
d1.display()

Alpha Karumpalagai +2 Computer Science – Hands on Practice 34


print("Distance 2")
d2.display()
print("Distance 3(Result)")
d3.display()
elif choice == 3:
d3=Distance()
d3.add(d1,d2)
elif choice == 4:
d3=Distance()
d3.subtract(d1,d2)

1. Read Two Distances


2. Display Distances
3. Add Two Distances
4. Subtract Two Distances
5. Exit
Enter your choice : 1
Distance 1
Enter Kilometer: 3
Enter Meter: 568
Distance 2
Enter Kilometer: 7
Enter Meter: 490
1. Read Two Distances
2. Display Distances
3. Add Two Distances
4. Subtract Two Distances
5. Exit
Enter your choice : 3

Alpha Karumpalagai +2 Computer Science – Hands on Practice 35


1. Read Two Distances
2. Display Distances
3. Add Two Distances
4. Subtract Two Distances
5. Exit
Enter your choice : 2
Distance 1
3Km 568m
Distance 2
7Km 490m
Distance 3(Result)
11Km 58m
1. Read Two Distances
2. Display Distances
3. Add Two Distances
4. Subtract Two Distances
5. Exit
Enter your choice : 1
Distance 1
Enter Kilometer: 8
Enter Meter: 345
Distance 2
Enter Kilometer: 2
Enter Meter: 854
1. Read Two Distances
2. Display Distances
3. Add Two Distances
4. Subtract Two Distances
5. Exit
Enter your choice : 4

Alpha Karumpalagai +2 Computer Science – Hands on Practice 36


1. Read Two Distances
2. Display Distances
3. Add Two Distances
4. Subtract Two Distances
5. Exit
Enter your choice : 2
Distance 1
8Km 345m
Distance 2
2Km 854m
Distance 3(Result)
5Km 491m
1. Read Two Distances
2. Display Distances
3. Add Two Distances
4. Subtract Two Distances
5. Exit
Enter your choice : 5

Alpha Karumpalagai +2 Computer Science – Hands on Practice 37


Chapter 11 Database Concepts

NO Hands on Practice

Alpha Karumpalagai +2 Computer Science – Hands on Practice 38


Chapter 12 Structured Query Language
+-------+----------+--------+------+-----------+
| Admno | Name | Gender | Age | Place |
+-------+----------+--------+------+-----------+
| 100 | Ashish | M | 17 | Chennai |
| 101 | Adarsh | M | 18 | Delhi |
| 102 | Akshith | M | 17 | Bangalore |
| 103 | Ayush | M | 21 | Delhi |
| 104 | Abinandh | M | 14 | Chennai |
+-------+----------+--------+------+-----------+

1. Create a query of the student table in the following order of fields name, age, place
and admno.

SELECT name, age, place, admno from STUDENT;

+----------+------+-----------+-------+
| name | age | place | admno |
+----------+------+-----------+-------+
| Ashish | 17 | Chennai | 100 |
| Adarsh | 18 | Delhi | 101 |
| Akshith | 17 | Bangalore | 102 |
| Ayush | 21 | Delhi | 103 |
| Abinandh | 14 | Chennai | 104 |
+----------+------+-----------+-------+

2. Create a query to display the student table with students of age more than 18 with
unique city.

SELECT * from STUDENT where age > 18 and place IN (SELECT DISTINCT place
from STUDENT);

+-------+-------+--------+------+-------+
| Admno | Name | Gender | Age | Place |
+-------+-------+--------+------+-------+
| 103 | Ayush | M | 21 | Delhi |
+-------+-------+--------+------+-------+

Alpha Karumpalagai +2 Computer Science – Hands on Practice 39


3. Create an employee table with the following fields employee number, employee
name, designation, date of joining and basic pay.

CREATE TABLE Employee(EmployeeNo integer, EmployeeName char(20),Designation


char(20),DOJ Date,BasicPay Integer);

4. In the above table set the employee number as primary key and check for NULL
values in any field.

CREATE TABLE Employee(EmployeeNo integer NOT NULL PRIMARY KEY,


EmployeeName char(20) NOT NULL,Designation char(20),DOJ Date,BasicPay Integer);

5. Prepare a list of all employees who are Managers

SELECT * from EMPLOYEE where designation = ‘Manager’

Alpha Karumpalagai +2 Computer Science – Hands on Practice 40


Chapter 13 Python and CSV Files

1. Write a Python program to read the following Namelist.csv file and sort the data in
alphabetically order of names in a list and display the output

SNO NAME OCCUPATION


1 NIVETHITHA ENGINEER
2 ADHITH DOCTOR
3 LAVANYA SINGER
4 VIDHYA TEACHER
5 BINDHU LECTURER

#Program to sort the entire row by using a specified column.


# declaring multiple header files
import csv ,operator
#One more way to read the file
data = csv.reader(open('c:\\PYPRG\\namelist.csv'))
next(data) #(to omit the header)
#using operator module for sorting multiple columns
sortedlist = sorted (data, key=operator.itemgetter(1)) # 1 specifies we want to sort
# according to second column
for row in sortedlist:
print(row)

['2', 'ADHITH ', 'DOCTOR ']


['5', 'BINDHU ', 'LECTURER ']
['3', 'LAVANYA ', 'SINGER ']
['1', 'NIVETHITHA ', 'ENGINEER ']
['4', 'VIDHYA ', 'TEACHER ']

Alpha Karumpalagai +2 Computer Science – Hands on Practice 41


2. Write a Python program to accept the name and five subjects mark of 5 students.
Find the total and store all the details of the students in a CSV file.
import csv
with open('c:\\pyprg\\mark.csv', 'w') as f:
w = csv.writer(f)
for i in range(1,6):
name = input("Name? ")
tamil = input("Tamil Mark? ")
english = input("English Mark? ")
maths = input("Maths Mark? ")
science = input("Science Mark? ")
social = input("Social Mark? ")
totalmark = tamil + english + maths + science + social
w.writerow([name, tamil, english, maths, science, social, totalmark])
F=open('c:\\pyprg\\mark.csv','r')
reader = csv.reader(F)
for row in reader:
print(row)
F.close()

Name? Anu
Tamil Mark? 56
English Mark? 45
Maths Mark? 78
Science Mark? 56
Social Mark? 87
Name? Banu
Tamil Mark? 78
English Mark? 87
Maths Mark? 98
Science Mark? 91
Social Mark? 67
Name? Cheran
Tamil Mark? 89

Alpha Karumpalagai +2 Computer Science – Hands on Practice 42


English Mark? 80
Maths Mark? 82
Science Mark? 81
Social Mark? 85
Name? Diana
Tamil Mark? 98
English Mark? 56
Maths Mark? 97
Science Mark? 56
Social Mark? 91
Name? Elango
Tamil Mark? 61
English Mark? 45
Maths Mark? 98
Science Mark? 85
Social Mark? 72

['Anu', '56', '45', '78', '56', '87', '322']


['Banu', '78', '87', '98', '91', '67', '421']
['Cheran', '89', '80', '82', '81', '85', '417']
['Diana', '98', '56', '97', '56', '91', '398']
['Elango', '61', '45', '98', '85', '72', '361']

Alpha Karumpalagai +2 Computer Science – Hands on Practice 43


Content of mark.csv

Alpha Karumpalagai +2 Computer Science – Hands on Practice 44


Chapter 14 Importing C++ Programs in Python

1. Write a C++ program to create a class called Student with the following details
Protected member
Rno integer
Public members
void Readno(int); to accept roll number and assign to Rno
void Writeno(); To display Rno.
The class Test is derived Publically from the Student class contains the following details
Protected member
Mark1 float
Mark2 float
Public members
void Readmark(float, float); To accept mark1 and mark2
void Writemark(); To display the marks
Create a class called Sports with the following detail
Protected members
score integer
Public members
void Readscore(int); To accept the score
void Writescore(); To display the score
The class Result is derived Publically from Test and Sports class contains the following
details
Private member
Total float
Public member
void display() assign the sum of mark1, mark2, score in total. invokeWriteno(),
Writemark() and Writescore(). Display the total also.
Save the C++ program in a file called hybrid. Write a python program to execute the
hybrid.cpp

Alpha Karumpalagai +2 Computer Science – Hands on Practice 45


hybrid.cpp
#include <iostream>
using namespace std;
// base class
class Student
{
protected:
int rno;
public:
Student()
{
rno = 0;
}
void readNo(int num)
{
rno = num;
}
void writeNo()
{
cout<<"Register Number :"<<rno<<"\n";
}

};

Alpha Karumpalagai +2 Computer Science – Hands on Practice 46


class Test: public Student
{
protected:
float mark1,mark2;
public:
Test()
{
mark1 = 0;
mark2 = 0;
}
void readMark(float m1, float m2 )
{
mark1 = m1;
mark2 = m2;
}
void writeMark()
{
cout<<"Mark 1 :"<<mark1<<"\n";
cout<<"Mark 2 :"<<mark2<<"\n";
}
};

Alpha Karumpalagai +2 Computer Science – Hands on Practice 47


class Sports
{
protected:
int score;
public:
Sports()
{
score = 0;
}
void readScore(int num)
{
score = num;
}
void writeScore()
{
cout<<"Score :"<<score<<"\n";
}

};

Alpha Karumpalagai +2 Computer Science – Hands on Practice 48


// sub class derived from two base classes
class Result: public Test,public Sports
{
private :
float total;
public:
Result()
{
total = 0;
}
void display()
{
int num,s;
float m1,m2;
cout <<"Register Number : ";
cin>>num;
readNo(num);
cout <<"Mark1? ";
cin>>m1;
cout <<"Mark2? ";
cin>>m2;
readMark(m1,m2);
cout <<"Score? ";
cin>>s;
readScore(s);
writeNo();
writeMark();
writeScore();
cout <<"Total : "<< m1+m2+s;
}
};

Alpha Karumpalagai +2 Computer Science – Hands on Practice 49


// main function
int main()
{
//creating object of sub class will invoke the constructor of base classes
Result r;
r.display();
return 0;
}

Alpha Karumpalagai +2 Computer Science – Hands on Practice 50


classpy.py

import sys, os, getopt


def main (argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt (argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):
cpp_file = a + '.cpp'
exe_file = a + '.exe'
run (cpp_file, exe_file)
def run(cpp_file, exe_file):
print ("Compiling " + cpp_file)
os.system ('g++ ' + cpp_file + ' -o ' + exe_file)
print ("Running " + exe_file)
print ("-------------------")
print
os.system (exe_file)
print
if __name__ =='__main__':
main (sys.argv[1:])

Alpha Karumpalagai +2 Computer Science – Hands on Practice 51


C:\Python27>Python classpy.py -i hybrid
Compiling hybrid.cpp
Running hybrid.exe
-------------------

Register Number : 1245


Mark1? 78
Mark2? 82
Score? 67
Register Number :1245
Mark 1 :78
Mark 2 :82
Score :67
Total : 227

Alpha Karumpalagai +2 Computer Science – Hands on Practice 52


2. Write a C++ program to print boundary elements of a matrix and name the file as
Border. cpp. Write a python program to execute the Border.cpp

border.cpp
#include <iostream>
using namespace std;
int main()
{
int a[10][10], i, j,m,n;
cout<<"Number of Rows? ";
cin>>m;
cout<<"Number of Columns? ";
cin>>n;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
cout<<"enter the value for array["<<i+1<<"]"<<"["<<j+1<<"] :";
cin>>a[i][j];
}
}
cout<<"The Matrix\n";
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
cout<<a[i][j]<<' ';
cout<<endl;
}

Alpha Karumpalagai +2 Computer Science – Hands on Practice 53


cout<<"The Boundary Elements are\n";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
if (i==0 || j==0 || i == m-1 || j == n-1)
cout<<a[i][j]<<' ';
}
return 0;
}

Alpha Karumpalagai +2 Computer Science – Hands on Practice 54


classpy.py

import sys, os, getopt


def main (argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt (argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):
cpp_file = a + '.cpp'
exe_file = a + '.exe'
run (cpp_file, exe_file)
def run(cpp_file, exe_file):
print ("Compiling " + cpp_file)
os.system ('g++ ' + cpp_file + ' -o ' + exe_file)
print ("Running " + exe_file)
print ("-------------------")
print
os.system (exe_file)
print
if __name__ =='__main__':
main (sys.argv[1:])

Alpha Karumpalagai +2 Computer Science – Hands on Practice 55


C:\Python27>Python classpy.py -i border
Compiling border.cpp
Running border.exe
-------------------

Number of Rows? 5
Number of Columns? 5
enter the value for array[1][1] :1
enter the value for array[1][2] :5
enter the value for array[1][3] :8
enter the value for array[1][4] :6
enter the value for array[1][5] :2
enter the value for array[2][1] :9
enter the value for array[2][2] :0
enter the value for array[2][3] :6
enter the value for array[2][4] :4
enter the value for array[2][5] :2
enter the value for array[3][1] :1
enter the value for array[3][2] :4
enter the value for array[3][3] :8
enter the value for array[3][4] :6
enter the value for array[3][5] :9
enter the value for array[4][1] :2
enter the value for array[4][2] :1
enter the value for array[4][3] :4
enter the value for array[4][4] :3
enter the value for array[4][5] :9
enter the value for array[5][1] :5
enter the value for array[5][2] :2
enter the value for array[5][3] :0
enter the value for array[5][4] :1
enter the value for array[5][5] :6

Alpha Karumpalagai +2 Computer Science – Hands on Practice 56


The Matrix
15862
90642
14869
21439
52016
The Boundary Elements are
1586292192952016

Alpha Karumpalagai +2 Computer Science – Hands on Practice 57


Chapter 15 Data Manipulation Through SQL

1. Create an interactive program to accept the details from user and store it in a csv file
using Python for the following table.
Database name:- DB1
Table name : Customer
Cust_Id Cust_Name Address Phone_no City
C008 Sandeep 14/1 Pritam Pura 41206819 Delhi
C010 Anurag Basu 15A, Park Road 61281921 Kolkata
C012 Hrithik 7/2 Vasant Nagar 26121949 Delhi

# code for executing query using input data


import sqlite3
import csv
# creates a database in RAM
con =sqlite3.connect("DB1.db")
cur =con.cursor()
cur.execute("DROP TABLE customer;")
cur.execute("create table customer (Cust_Id char(5), Cust_Name char(20), Address
char(20),Phone_no char(10),City char(20))")
for i in range(3):
custId = input("Customer Id? ")
custName = input("Customer Name? ")
custAddress = input("Customer Address? ")
custPhoneNo =input("Customer Phone No? ")
custCity =input("Customer City? ")
cur.execute("insert into customer values (?, ?, ?,?,?)", (custId, custName,
custAddress,custPhoneNo,custCity))
cur.execute("select * from customer")
# Fetches all entries from table
print("Records From Customer Table")
print (cur.fetchall())

Alpha Karumpalagai +2 Computer Science – Hands on Practice 58


# CREATING CSV FILE
csvfile=open('c:/pyprg/customer.csv','w')
cw=csv.writer(csvfile)
cur.execute("select * from customer")
heading = [i[0] for i in cur.description]
cw.writerow(heading)
data=cur.fetchall()
for item in data:
cw.writerow(item)
csvfile.close()

Customer Id? C008


Customer Name? Sandeep
Customer Address? 14/1 Pritam Pura
Customer Phone No? 41206819
Customer City? Delhi
Customer Id? C010
Customer Name? Anurag Basu
Customer Address? 15A, Park Road
Customer Phone No? 61281921
Customer City? Kolkata
Customer Id? C012
Customer Name? Hrithik
Customer Address? 7/2 Vasant Nagar
Customer Phone No? 26121949
Customer City? Delhi
Records From Customer Table
(C008, Sandeep, 14/1 Pritam Pura, 41206819, Delhi)
(C010, Anurag Basu, 15A, Park Road, 61281921, Kolkata)
(C012, Hrithik, 7/2 Vasant Nagar, 26121949, Delhi)]

Alpha Karumpalagai +2 Computer Science – Hands on Practice 59


Csv file opened in Excel

Alpha Karumpalagai +2 Computer Science – Hands on Practice 60


2. Consider the following table GAMES. Write a python program to display the records
for question (i) to (iv) and give output for SQL queries (v)
Table: GAMES
Gcode Name GameName Number PrizeMoney ScheduleDate
101 Padmaja Carom Board 2 5000 01-23-2014
102 Vidhya Badminton 2 12000 12-12-2013
103 Guru Table Tennis 4 8000 02-14-2014
105 Keerthana Carom Board 2 9000 01-01-2014
108 Krishna Table Tennis 4 25000 03-19-2014

(i) To display the name of all Games with their Gcodes in descending order of their
schedule date.

import sqlite3
connection = sqlite3.connect("DB2.db")
cursor = connection.cursor()
cursor.execute("SELECT Gcode, GameName FROM Games ORDER BY scheduleDate
DESC")
result = cursor.fetchall()
print(*result,sep="\n")

(ii) To display details of those games which are having Prize Money more than 7000.

import sqlite3
connection = sqlite3.connect("DB2.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM Games WHERE PrizeMoney>7000")
result = cursor.fetchall()
print(*result,sep="\n")

Alpha Karumpalagai +2 Computer Science – Hands on Practice 61


(iii) To display the name and gamename of the Players in the ascending order of
Gamename.

import sqlite3
connection = sqlite3.connect("DB2.db")
cursor = connection.cursor()
cursor.execute("SELECT Name, GameName FROM Games ORDER BY GameName")
result = cursor.fetchall()
print(*result,sep="\n")

(iv) To display sum of PrizeMoney for each of the Number of participation groupings (as
shown in column Number 4)

import sqlite3
connection = sqlite3.connect("DB2.db")
cursor = connection.cursor()
cursor.execute("SELECT Number, sum(PrizeMoney) FROM Games GROUP BY
NUMBER")
result = cursor.fetchall()
print(*result,sep="\n")

(v) Display all the records based on GameName


Gcode Name GameName Number PrizeMoney ScheduleDate
102 Vidhya Badminton 2 12000 12-12-2013
101 Padmaja Carom Board 2 5000 01-23-2014
105 Keerthana Carom Board 2 9000 01-01-2014
103 Guru Table Tennis 4 8000 02-14-2014
108 Krishna Table Tennis 4 25000 03-19-2014

Alpha Karumpalagai +2 Computer Science – Hands on Practice 62


Chapter 16 Data Visualization Using Pyplot : Line Chart,
Pie Chart and Bar Chart

1. Create a plot. Set the title, the x and y labels for both axes.

import matplotlib.pyplot as plt


x = [1,2,3]
y = [5,7,4]
plt.plot(x, y, label='Line 1')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('LINE GRAPH')
plt.legend()
plt.show()

Alpha Karumpalagai +2 Computer Science – Hands on Practice 63


2. Plot a pie chart for your marks in the recent examination.

import matplotlib.pyplot as plt


sizes = [89, 80, 100, 91, 96,98]
labels = ["Tamil", "English", "Maths", "Physcis", "Chemistry", "Computer Science"]
plt.pie (sizes, labels = labels, autopct = "%.2f ")
plt.axes().set_aspect ("equal")
plt.show()

Alpha Karumpalagai +2 Computer Science – Hands on Practice 64


3. Plot a line chart on the academic performance of Class 12 students in Computer
Science for the past 10 years.

import matplotlib.pyplot as plt


years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019]
marks = [89, 93, 91, 96, 95,94,93,91,91,93]
plt.plot (years, marks)
plt.title ("Academic Performance of Class 12 Students in Computer Science for the Past
10 Years")
plt.xlabel ("Year")
plt.ylabel ("Marks")
plt.show()

Alpha Karumpalagai +2 Computer Science – Hands on Practice 65


4. Plot a bar chart for the number of computer science periods in a week.

import matplotlib.pyplot as plt


labels = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
usage = [1, 2, 1, 2, 2, 1]
# Generating the y positions. Later, we'll use them to replace them with labels.
y_positions = range (len(labels))
# Creating our bar plot
plt.bar (y_positions, usage)
plt.xticks (y_positions, labels)
plt.ylabel ("Periods")
plt.title ("Number of Computer Science Periods in a Week")
plt.show()

Alpha Karumpalagai +2 Computer Science – Hands on Practice 66

You might also like