Computer Science Practical Notes
Computer Science Practical Notes
Computer Science Practical Notes
K. KANNAN,
CHENNAI G HR. SEC. SCHOOL,
ROTLER STREET, CHENNAI 600 112
INDEX
Page
Ex No Topic
No
PY1 (a) Calculate Factorial 4
2
INTERNAL CHOICES
Practical
Question Question 1 Question 2
Number
PY1(a) Calculate Factorial
CS1 (OR) PY9 - Python with SQL
PY1(b) Sum of Series
3
PY1(a) - Calculate Factorial
Write a program to calculate the factorial of the given number using for loop.
AIM: To calculate the factorial of the given number using for loop.
CODING:
num = int(input('Enter a Number: '))
if (num==0):
fact = 1
fact = 1
for i in range(1,num+1):
fact = fact * i
print("Factorial of ", num, " is ", fact)
OUTPUT:
Enter a Number: 12
Factorial of 12 is 479001600
4
5
PY1(b) - Sum of series
Write a program to sum the series: 1/1 + 22/2 + 33/3 + ……. nn/n
AIM: To calculate the sum of the series: 1/1 + 22/2 + 33/3 + ……. nn/n
CODING:
n = int(input("Enter a value of n: "))
s=0.0
for i in range(1,n+1):
a=float(i**i)/i
s=s+a
print("The sum of the series is ", s)
OUTPUT:
Enter a value of n: 4
The sum of the series is 76.0
6
PY2(a) - Odd or Even
Write a program using functions to check whether a number is even or odd.
AIM: To check whether a number is even or odd using user defined function
CODING:
def oddeven(a):
if (a%2==0):
return 1
else:
return 0
OUTPUT:
Enter a number: 7
The given number is Odd
Enter a number: 6
The given number is Even
7
8
PY2(b) - Reverse the string
Write a program to create reverse of the given string. For example, “wel” = “lew“.
CODING:
def rev(str1):
str2=''
i=len(str1)-1
while i>=0:
str2+=str1[i]
i-=1
return str2
OUTPUT:
Enter a String: school
The reverse of the given string is: loohcs
9
10
PY3. Generate values and remove odd numbers
Write a program to generate values from 1 to 10 and then remove all the odd
numbers from the list.
AIM:
To generate values from 1 to 10 and then remove all the odd numbers from the list.
CODING:
num1=[]
for i in range(1,11):
num1.append(i)
print("Numbers from 1 to 10.....\n",num1)
for j, i in enumerate(num1):
if(i%2==1):
del num1[j]
print("The values after removed odd numbers.....\n",num1)
OUTPUT:
Numbers from 1 to 10.....
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The values after removed odd numbers.....
[2, 4, 6, 8, 10]
11
12
PY4 - Generate prime numbers and set operations
Write a Program that generate a set of prime numbers and another set of odd
numbers. Display the result of union, intersection, difference and symmetric
difference operations.
AIM:
To generate a set of prime numbers and another set of odd numbers, and to display
the result of union, intersection, difference and symmetric difference operations.
CODING:
odd=set([x*2+1 for x in range(0,5)])
primes=set()
for i in range(2,10):
j=2
f=0
while j<=i/2:
if i%j==0:
f=1
j+=1
if f==0:
primes.add(i)
print("Odd Numbers: ", odd)
print("Prime Numbers: ", primes)
print("Union: ", odd.union(primes))
print("Intersection: ", odd.intersection(primes))
print("Difference: ", odd.difference(primes))
print("Symmetric Difference: ", odd.symmetric_difference(primes))
OUTPUT:
Odd Numbers: {1, 3, 5, 7, 9}
Prime Numbers: {2, 3, 5, 7}
Union: {1, 2, 3, 5, 7, 9}
Intersection: {3, 5, 7}
Difference: {1, 9}
Symmetric Difference: {1, 2, 9}
13
14
PY5 - Display a string elements – using class
Write a program to accept a string and print the number of uppercase, lowercase,
vowels, consonants and spaces in the given string using Class.
AIM:
To accept a string and print the number of uppercase, lowercase, vowels, consonants
and spaces in the given string using Class.
CODING:
class String:
def __init__(self):
self.uppercase=0
self.lowercase=0
self.vowels=0
self.consonants=0
self.spaces=0
self.string=""
def getstr(self):
self.string=str(input("Enter a String: "))
def count_upper(self):
for ch in self.string:
if (ch.isupper()):
self.uppercase+=1
def count_lower(self):
for ch in self.string:
if (ch.islower()):
self.lowercase+=1
def count_vowels(self):
for ch in self.string:
if (ch in ('A', 'a', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U')):
self.vowels+=1
def count_consonants(self):
for ch in self.string:
if (ch not in ('A', 'a', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', ' ')):
self.consonants+=1
def count_space(self):
for ch in self.string:
if (ch==" "):
self.spaces+=1
def execute(self):
self.count_upper()
self.count_lower()
self.count_vowels()
self.count_consonants()
15
self.count_space()
def display(self):
print("The given string contains...")
print("%d Uppercase letters"%self.uppercase)
print("%d Lowercase letters"%self.lowercase)
print("%d Vowels"%self.vowels)
print("%d Consonants"%self.consonants)
print("%d Spaces"%self.spaces)
S = String()
S.getstr()
S.execute()
S.display()
OUTPUT:
Enter a String: Welcome to Computer Science
The given string contains...
3 Uppercase letters
21 Lowercase letters
10 Vowels
14 Consonants
3 Spaces
16
17
18
DB6 - MySQL – Employee table
Create an Employee Table with the fields Empno, Empname, Desig, Dept, Age
and Place. Enter five records into the table.
Add two more records to the table.
Modify the table structure by adding one more field namely date of joining.
Check for Null value in doj of any record.
List the employees who joined after 01/01/2018.
AIM:
(1) Create employee table with Empno, Empname, Desig, Dept, Age and Place fields.
(2) Insert five records
(3) Add two more records
(4) Modify table structure
(5) Check for NULL values
(6) List required subset of records
19
mysql> Insert into employee values(1225, 'Rahul', 'Officer', 'Accounts', 31, 'Anna
Nagar');
desc employee;
+----------------------+---------------------+------+------+----------+---------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+---------------------+------+------+----------+---------+
| Empno | int(4) | NO | PRI | NULL | |
| Empname | varchar(20) | YES | | NULL | |
| Desig | varchar(10) | YES | | NULL | |
| Dept | varchar(10) | YES | | NULL | |
| Age | int(2) | YES | | NULL | |
20
| Place | varchar(10) | YES | | NULL | |
| doj | date | YES | | NULL | |
+----------------------+---------------------+------+------+----------+---------+
7 rows in set (0.00 sec)
+-----------+-----------------+-------------+-----------+------+-------------+---------------------+
| Empno | Empname | Desig | Dept | Age | Place | doj |
+-----------+-----------------+-------------+-----------+------+-------------+---------------------+
| 1221 | Sidharth | Officer | Accounts | 45 | Salem | 2010-03-21 |
| 1222 | Naveen | Manager | Admin | 32 | Erode | 2012-05-13 |
| 1223 | Ramesh | Clerk | Accounts | 33 | Ambathur | 2017-10-25 |
| 1224 | Abinaya | Manager | Admin | 28 | Anna Nagar | 2018-06-17 |
| 1225 | Rahul | Officer | Accounts | 31 | Anna Nagar | 2018-01-02 |
| 3226 | Sona | Manager | Accounts | 42 | Erode | 2017-12-31 |
| 3227 | Rekha | Officer | Admin | 34 | Salem | 2015-08-16 |
+-----------+-----------------+-------------+-----------+------+-------------+---------------------+
7 rows in set (0.00 sec)
+-----------+-----------------+-------------+-----------+------+-------------+---------------------+
| Empno | Empname | Desig | Dept | Age | Place | doj |
+-----------+-----------------+-------------+-----------+------+-------------+---------------------+
| 1224 | Abinaya | Manager | Admin | 28 | Anna Nagar | 2018-06-17 |
| 1225 | Rahul | Officer | Accounts | 31 | Anna Nagar | 2018-01-02 |
+-----------+-----------------+-------------+-----------+------+-------------+---------------------+
2 rows in set (0.00 sec)
21
DB7 - MySQL – Student table
Create a table with following fields and enter data as given in the table below.
-----------------------------------------------------------
Field Name Type Size
-----------------------------------------------------------
Reg_No char 5
Sname varchar 15
Age int 2
Dept varchar 10
Class char 3
-----------------------------------------------------------
Data to be entered
Reg_No Sname Age Dept Class
M1001 Harish 19 ME ME1
AIM:
(1) Create student table and inserting records
(2) List the students whose department is “Computer Science”.
(3) List all the students of age 20 and more in Mechanical department.
(4) List the students department wise.
(5) Modify the class M2 to M1.
(6) Check for the uniqueness of Register no.
22
SQL QUERIES AND OUTPUT:
(1) Creating Table - Student
mysql> Create table Student (Reg_No char(5), Sname varchar(20), Age integer(2),
Dept varchar(10), Class char(3));
+--------------+--------------+-------+------------+---------+
| Reg_No | Sname | Age | Dept | Class |
+--------------+--------------+-------+------------+---------+
| M1001 | Harish | 19 | ME | ME1 |
| E1002 | Leena | 21 | EEE | EE1 |
| E1001 | Ravi | 20 | ECE | EC1 |
| C1001 | Sneha | 20 | CSE | CS1 |
+--------------+--------------+-------+------------+---------+
4 rows in set (0.00 sec)
24
mysql> select * from Student;
+--------------+--------------+-------+------------+---------+
| Reg_No | Sname | Age | Dept | Class |
+--------------+--------------+-------+------------+---------+
| M1001 | Harish | 19 | ME | ME1 |
| M1002 | Akash | 20 | ME | ME1 |
| C1001 | Sneha | 20 | CSE | CS1 |
| C1002 | Lithya | 19 | CSE | CS2 |
| E1001 | Ravi | 20 | ECE | EC1 |
| E1002 | Leena | 21 | EEE | EE1 |
| E1003 | Rose | 20 | ECE | EC2 |
+--------------+--------------+-------+------------+---------+
7 rows in set (0.00 sec)
25
PY8 - Python with CSV
Write a program using python to get 10 players name and their score. Write the
input in a csv file. Accept a player name using python. Read the csv file to
display the name and the score. If the player name is not found give an
appropriate message.
AIM:
To get 10 players name and their score. Write the input in a csv file. Accept a player
name using python. Read the csv file to display the name and the score. If the player
name is not found give an appropriate message.
CODING:
import csv
with open('c:\\pyprg\\player.csv','w') as f:
w = csv.writer(f)
n=1
while (n<=10):
name = input("Player Name?:" )
score = int(input("Score: "))
w.writerow([name,score])
n+=1
print("Player File created")
f.close()
searchname=input("Enter the name to be searched ")
f=open('c:\\pyprg\\player.csv','r')
reader =csv.reader(f)
lst=[]
for row in reader:
lst.append(row)
q=0
for row in lst:
if searchname in row:
print(row)
q+=1
if(q==0):
print("string not found")
f.close()
26
OUTPUT:
27
28
29
30
PY9 - Python with SQL
Create a sql table using python and accept 10 names and age .sort in descending
order of age and display.
AIM:
To create a sql table using python and accept 10 names and age. sort in descending
order of age and display.
CODING:
import sqlite3
connection = sqlite3.connect("info.db")
cursor = connection.cursor()
cursor.execute("create table student(name, age)")
print("Enter 10 students names and their ages respectively:")
for i in range(10):
who =[input("Enter Name:")]
age =[int(input("Enter Age:"))]
n =len(who)
for i in range(n):
cursor.execute("insert into student values (?, ?)", (who[i],age[i]))
cursor.execute("select * from student order by age desc")
print("Displaying All the Records From student Table in Descending order of age")
print (*cursor.fetchall(),sep='\n' )
OUTPUT:
Enter 10 students names and their ages respectively:
Enter Name:Annamalai
Enter Age:17
Enter Name:Aashik Mathew
Enter Age:23
Enter Name:Kumaran
Enter Age:30
Enter Name:Sivasakthiya
Enter Age:28
Enter Name:Leena
Enter Age:45
Enter Name:Meena
Enter Age:65
Enter Name:Kamalakannan
Enter Age:35
Enter Name:Sowmyaa
Enter Age:20
31
Enter Name:Ramaa
Enter Age:70
Enter Name:Melvin
Enter Age:35
Displaying All the Records From student Table in Descending order of age
('Ramaa', 70)
('Meena', 65)
('Leena', 45)
('Kamalakannan', 35)
('Melvin', 35)
('Kumaran', 30)
('Sivasakthiya', 28)
('Aashik Mathew', 23)
('Sowmyaa', 20)
('Annamalai', 17)
32
33
PY10 - Python Graphics with Pip
Write a program to get five marks using list and display the marks in pie chart.
AIM:
To get five marks using list and display the marks in pie chart using matplot.
CODING:
import matplotlib.pyplot as plt
marks=[]
i=0
subjects = ["Tamil", "English", "Maths", "Science", "Social"]
while i<5:
marks.append(int(input("Enter Mark = ")))
i+=1
for j in range(len(marks)):
print("{}.{} Mark = {}".format(j+1, subjects[j],marks[j]))
OUTPUT:
Enter Mark = 67
Enter Mark = 31
Enter Mark = 45
Enter Mark = 89
Enter Mark = 73
1.Tamil Mark = 67
2.English Mark = 31
3.Maths Mark = 45
4.Science Mark = 89
5.Social Mark = 73
34
35