CBSE Computer science practical file for class 12 

In this section CBSE students of class 12 Computer science can check the important python programs that must be prepare before the practical examination. Here are 20+ python programs with output, for Computer science practical file Term 1.

 

Program:1

Write a python Program to take input for a number, calculate and print its square and cube?

a=int(input("Enter any no "))
b=a*a
c=a*a*a
print("Square = ",b)
print("cube = ",c)

 

Output:

Enter any no 10
Square = 100
cube = 1000
>>>

 

Computer science practical file for class 12

Program:2

Write a python program to take input for 2 numbers, calculate and print their sum, product and difference?

a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
s=a+b
p=a*b
if(a>b):
    d=a-b
else:
    d=b-a
print("Sum = ",s)
print("Product = ",p)
print("Difference = ",d)

Output:

Enter 1st no 10
Enter 2nd no 20
Sum = 30
Product = 200
Difference = 10
>>>

 

You may also check: Class 12 Computer Science Project in Python

 

Program:3

Write a python program to take input for 3 numbers, check and print the largest number?

 

a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
c=int(input("Enter 3rd no "))
if(a>b and a>c):
    m=a
else:
    if(b>c):
        m=b
    else:
        m=c
print("Max no = ",m)

 

Output:

Enter 1st no 25
Enter 2nd no 63
Enter 3rd no 24
Max no = 63
>>>

Method:2

num1=int(input("Enter 1st no "))
num2=int(input("Enter 2nd no "))
num3=int(input("Enter 3rd no "))
if(num1>num2 and num1>num3):
    max=num1
elif(num2>num3):
    max=num2
else:
    max=num3
print("Max no = ",max)

 

Output:

Enter 1st no 25
Enter 2nd no 98
Enter 3rd no 63
Max no = 98
>>>

 

Program:4

Write a python program to take input for 2 numbers and an operator (+ , – , * , / ). Based on the operator calculate and print the result?

a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
op=input("Enter the operator (+,-,*,/) ")
if(op=="+"):
    c=a+b
    print("Sum = ",c)
elif(op=="*"):
    c=a*b
    print("Product = ",c)
elif(op=="-"):
    if(a>b):
        c=a-b
    else:
        c=b-a
    print("Difference = ",c)
elif(op=="/"):
    c=a/b
    print("Division = ",c)
else:
    print("Invalid operator")

 

First Run Output:

Enter 1st no 10
Enter 2nd no 20
Enter the operator (+,-,*,/) +
Sum = 30
>>>

 

Second Run Output:

Enter 1st no 10
Enter 2nd no 36
Enter the operator (+,-,*,/) –
Difference = 26
>>>

computer science lab manual class 12

Program: 5

Write a python program to take input for a number and print its table?

num=int(input("Enter any no "))
i=1
while(i<=10):
    table=num*i
    print(num," * ",i," = ",table)
    i=i+1

 

 

Output:

Enter any no 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
>>>

 

Program:6

Write a python program to take input for a number and print its factorial?

n=int(input("Enter any no "))
i=1
f=1
while(i<=n):
    f=f*i
    i=i+1
print("Factorial = ",f)

 

Output:

Enter any no 5
Factorial = 120
>>>

Program:7

Write a python program to take input for a number check if the entered number is Armstrong or not.

 

n=int(input("Enter the number to check : "))
n1=n
s=0
while(n>0):
    d=n%10
    s=s + (d *d * d)
    n=int(n/10)
if s==n1:
    print("Armstrong Number")
else:
    print("Not an Armstrong Number")

 

First Run Output:

Enter the number to check : 153
Armstrong Number
>>>

Second Run Output:

Enter the number to check : 152
Not an Armstrong Number
>>>

 

Program:8

Write a python program to take input for a number and print its factorial using recursion?

 

#Factorial of a number using recursion
def recur_factorial(n):
    if n == 1:
        return n
    else:
        return n*recur_factorial(n-1)
#for fixed number
num = 7
#using user input
num=int(input("Enter any no "))
#check if the number is negative
if num < 0:
    print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    print("The factorial of", num, "is", recur_factorial(num))

 

Output:

Enter any no 5
The factorial of 5 is 120
>>>

 

Program:9

Write a python program to Display Fibonacci Sequence Using Recursion?

#Python program to display the Fibonacci sequence
def recur_fibo(n):
    if n <= 1:
        return n
    else:
        return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = int(input("Enter upto which term you want to print"))
#check if the number of terms is valid
if (nterms <= 0):
    print("Plese enter a positive integer")
else:
    print("Fibonacci sequence:")
for i in range(nterms):
    print(recur_fibo(i))

 

Output:

Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
>>>

 

Program: 10

Write a python program to maintain book details like book code, book title and price using stacks data structures? (implement push(), pop() and traverse() functions)

"""
push
pop
traverse
"""
book=[]

def push():
    bcode=input("Enter bcode ")
    btitle=input("Enter btitle ")
    price=input("Enter price ")
    bk=(bcode,btitle,price)
    book.append(bk)

def pop():
    if(book==[]):
        print("Underflow / Book Stack in empty")
    else:
        bcode,btitle,price=book.pop()
    print("poped element is ")
    print("bcode ",bcode," btitle ",btitle," price ",price)

def traverse():
    if not (book==[]):
        n=len(book)
        for i in range(n-1,-1,-1):
            print(book[i])
    else:
        print("Empty , No book to display")
while True:
    print("1. Push")
    print("2. Pop")
    print("3. Traversal")
    print("4. Exit")

    ch=int(input("Enter your choice "))
    if(ch==1):
        push()
    elif(ch==2):
        pop()
    elif(ch==3):
        traverse()
    elif(ch==4):
        print("End")
        break
    else:
        print("Invalid choice")

 

 

Output:

1. Push
2. Pop
3. Traversal
4. Exit

Enter your choice 1

Enter bcode 101

Enter btitle python

Enter price 254

1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 3

(‘101’, ‘python’, ‘254’)

1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice

 

Program:11

Write a python program to maintain employee details like empno,name and salary using Queues data structure? (implement insert(), delete() and traverse() functions)

#queue implementation (using functions)
#program to create a queue of employee(empno,name,sal).
"""
add employee
delete employee
traverse / display all employees
"""
employee=[]
def add_element():
    empno=input("Enter empno ")
    name=input("Enter name ")
    sal=input("Enter sal ")
    emp=(empno,name,sal)
    employee.append(emp)

def del_element():
    if(employee==[]):
        print("Underflow / Employee Stack in empty")
    else:
        empno,name,sal=employee.pop(0)
        print("poped element is ")
        print("empno ",empno," name ",name," salary ",sal)

def traverse():
    if not (employee==[]):
        n=len(employee)
        for i in range(0,n):
            print(employee[i])
    else:
        print("Empty , No employee to display")

while True:
    print("1. Add employee")
    print("2. Delete employee")
    print("3. Traversal")
    print("4. Exit")
    ch=int(input("Enter your choice "))
    if(ch==1):
        add_element()
    elif(ch==2):
        del_element();
    elif(ch==3):
        traverse()
    elif(ch==4):
        print("End")
        break
    else:
        print("Invalid choice")

 

Output:

1. Add employee
2. Delete employee
3. Traversal
4. Exit

Enter your choice 1
Enter empno 101
Enter name Amit
Enter sal 45000

1. Add employee
2. Delete employee
3. Traversal
4. Exit
Enter your choice 3
(‘101’, ‘Amit’, ‘45000’)

1. Add employee
2. Delete employee
3. Traversal
4. Exit
Enter your choice

 

Program:12

Write a python program to read a file named “article.txt”, count and print total alphabets in the file?

def count_alpha():
    lo=0
    with open("article.txt") as f:
        while True:
            c=f.read(1)
            if not c:
                break
            print(c)
            if((c>='A' and c<='Z') or (c>='a' and c<='z')):
                lo=lo+1
        print("total lower case alphabets ",lo)
#function calling
count_alpha()

 

Output:

Hello how are you
12123
bye
total lower case alphabets 17
>>>

Program:13

Write a python program to read a file named “article.txt”, count and print the following:
(i) length of the file(total characters in file)
(ii)total alphabets
(iii) total upper case alphabets
(iv) total lower case alphabets
(v) total digits
(vi) total spaces
(vii) total special characters

 

def count():
    a=0
    ua=0
    la=0
    d=0
    sp=0
    spl=0
    with open("article.txt") as f:
        while True:
            c=f.read(1)
            if not c:
                break
            print(c)
            if((c>='A' and c<='Z') or (c>='a' and c<='z')):
                a=a+1
            if(c>='A' and c<='Z'):
                ua=ua+1
            else:
                la=la+1

            if(c>='0' and c<='9'):
                d=d+1
            if(c==''):
                sp=sp+1
            else:
                spl=spl+1
    print("total alphabets ",a)
    print("total upper case alphabets ",ua)
    print("total lower case alphabets ",la)
    print("total digits ",d)
    print("total spaces ",sp)
    print("total special characters ",spl)
# function calling
count()

 

Output:

Welcome to cbsepython.
('total alphabets ', 19)
('total upper case alphabets ', 1)
('total lower case alphabets ', 21)
('total digits ', 0)
('total spaces ', 0)
('total special characters ', 22)
>>>

 

Program: 14

Write a python program to read a file named “article.txt”, count and print total words starting with “a” or “A” in the file?

def count_words():
    w=0
    with open("article.txt") as f:
        for line in f:
            for word in line.split():
                if(word[0]=="a" or word[0]=="A"):
                    print(word)
                    w=w+1
        print("total words starting with 'a' are ",w)
# function calling
count_words()

 

Output:

Amit
Ankur
and
Ajay
("total words starting with 'a' are ", 4)
>>>>

computer science practical file for class 12 python 2021-22

 

Program: 15

Write a python program to read a file named “article.txt”, count and print total lines starting with vowels in the file?

 

filepath = 'article.txt'
vowels="AEIOUaeiou"
with open(filepath) as fp:
    line = fp.readline()
    cnt = 1
    while line:
        if(line[0] in vowels):
            #print(line)
            print("Line {}: {}".format(cnt, line.strip()))
            cnt=cnt+1
        line = fp.readline()

 

Output:

Line 1: amit
Line 2: owl
Line 3: Eat apple a day and stay healthy
Line 4: Anmol

 

Program:16

Python interface with MySQL

Write a function to insert a record in table using python  and MySQL interface.

 

def insert_data():
#take input for the details and then save the record in the databse
#to insert data into the existing table in an existing database
    import mysql.connector
    db = mysql.connector.connect(host="localhost",user="root",password="admin")
    c = db.cursor()
    r=int(input("Enter roll no "))
    n=input("Enter name ")
    p=int(input("Enter per "))
    try:
        c.execute("insert into student (roll,name,per) values (%s,%s,%s)",(r,n,p))
        db.commit()
        print("Record saved")
    except:
        db.rollback()
        db.close()
# function calling
insert_data()

 

Output:

Enter roll no 101
Enter name amit
Enter per 97
Record saved
>>>

Program 17:

Python interface with MySQL

Write a function to display all the records stored in a table using python  and MySQL interface.

def display_all():
    import mysql.connector
    db = mysql.connector.connect(host='localhost',user='root',passwd='admin',database='test4')
    try:
        c = db.cursor()
        sql='select * from student;'
        c.execute(sql)
        countrow=c.execute(sql)
        print("number of rows : ",countrow)
        data=c.fetchall()
        print("=========================")
        print("Roll No Name Per ")
        print("=========================")
        for eachrow in data:
            r=eachrow[0]
            n=eachrow[1]
            p=eachrow[2]
            print(r,' ',n,' ',p)
            print("=========================")
    except:
        db.rollback()
        db.close()
# function calling
display_all()

 

Output:

number of rows : 2
=========================
Roll No Name Per
=========================
102 aaa 99
101 amit 97
=========================
>>>

Program :18

Python interface with MySQL

Write a function to search a record stored in a table using python  and MySQL interface.

def search_roll():
    import mysql.connector
    db = mysql.connector.connect(host="localhost",user="root",passwd="admin",database="test")
    try:
        z=0
        roll=int(input("Enter roll no to search "))
        c = db.cursor()
        sql='select * from student;'
        c.execute(sql)
        countrow=c.execute(sql)
        print("number of rows : ",countrow)
        data=c.fetchall()
        for eachrow in data:
            r=eachrow[0]
            n=eachrow[1]
            p=eachrow[2]
        if(r==roll):
            z=1
            print(r,n,p)
        if(z==0):
            print("Record is not present")
    except:
        db.rollback()
        db.close()
# function calling
search_roll()

 

Output:

Enter roll no to search 101
number of rows : 2
101 amit 97
>>>

 

MySQL programs for class 12 practical file

STRUCTURED QUERY LANGUAGE

It is a simple query language used to accessing, handling and managing data in relational databases. It enables to create and operate on rational databases, which are sets of related information stored in tables.

PROCESSING CAPABILITIES OF SQL

1. DDL: The SQL DDL Provides commands for – defining relation, deleting relation, creating indexes and modifying.

2. I-DML: It includes programs to insert, delete or modify Tuples.

3. E-DML: It is a form of SQL designed for general purpose programming such as Pascal etc.

4. View Definitions: It includes commands for defining views.

5. Integrity- It includes that we you integrity checking.

6. Authorization – It includes commands for specifying excess rights to relations and views.

7. Transaction Control: It includes commands for specify the beginning and ending of transactions.

 

DATA DEFINATION LANGUAGE

DATA DICTIONARY: It is a file that contain “metadata” ie, data about data.

DDL provides a set of definitions to specify the storage structure and access methods used by the database system.

 

DATA MANIPULATION LANGUAGE

DML is language that enables users to access or manipulate data as organised by the appropriate data method.

 

COMMANDS IN SQL

1. Create Table Command: It is used to create a new column name and its data type.

CREATE TABLE EMPLOYEE

(EMPNO INTEGER PRIMARY KEY,

EMPNAME CHAR(20) NOT NULL,

JOB CHAR (25) NOT NULL,

MGR INTEGER,

HIREDATE DATE,

SAL DOUBLE CHECK (SAL>5000),

COMM REAL,

DEPTNO INTEGER);

 

INSERT INTO – It is used to add records.

Example –

INSERT INTO employee value (1008, “XYZ”, “CLERK”, 850, {23/12/2013}, 7500, 10, 5)

TABLE EMPLOYEE

EmpNo Emp Name Job Mgr HireDate Sal Comm Dept No
7839 King President 07-Nov-81 5000 10
7698 Blake Manager 7839 01-May-81 2850 30
7782 Clark Manager 7839 09-Jun-81 2450 10
7566 Jones Manager 7839 02-April-81 2975 20
7654 Martin Salesman 9698 02-April-81 1250 1400 30
7499 Allen Salesman 7698 20-Feb-81 1600 300 30
7844 Turner Salesman 7698 08-Sep-81 1500 0 30
7900 James Clerk 7698 03-Dec-81 950 30
7521 Ward Salesman 7698 02-Feb-81 1250 500 30

 

2. The SELECT Command:This is used to display or print the contents of the table on the screen. Clauses available with SELECT statements are:

a) WHERE

b) ORDER BY

 

SQL COMMANDS

i) To show all the details from table employee

SELECT * from employee;

 

ii) To show specific column data from table employee

SELECT EMPNO, EMPNAME, SAL from employee;

 

iii) To show those records where salary range from 5000 to 10000

SELECT * from employee where SAL >=5000 and SAL <= 10000;

 

iv) To show records whose name is BLAKE

SELECT * from employee whore EMPNAME = “BLAKE”;

 

v) To show records of those whose name does not start with “A”.

SELECT * from employee where EMPNAME not like “A%”;

 

vi) To show those records whose name starts with “A”.

SELECT * from employee where EMPNAME like “A”;

 

vii) To show records in the alphabetical order of EMPNAME

SELECT * from employee order by EMPNAME;

 

viii) To Show the records by avoiding duplicate EMPNAME.

SELECT DISTINCT EMPNAME from employee;

 

OTHER SQL COMMANDS

 

ix) To show Book name, Author name and Price of books of first publ. publishers.

SELECT Book NAME, Author NAME, Price FROM Books WHERE Publishers = “first Publ.”

 

x) To list the names from books of Text Type

SELECT Book Name FROM Books WHERE BOOKS Type = “Text”;

 

xi) To display the names and price from books in ascending order of their price.

SELECT Book Name, Price FROM Books ORDER BY Price;

 

xii) To increase the price of all book of EPB Publishers by 50.

UPDATE Books SET Price = Price +50 WHERE Publisher = “EPB”

 

xiii) To display BOOK ID, BOOK NAME for all books which have been issued.

SELECT BOOKS.BOOK ID, BOOK NAME FROM BOOKISSUED

WHERE BOOKS.BOOK. ID = ISSUED. BOOKID;

 

xiv) To insert new row in the table Issued having data “F0003”, 1.

INSERT INTO Issued VALUES (“F0003”, 1);

 

* In above command two different tables are used , Table: BOOKS and Table: ISSUED with different data.

 

 

You may also check: Class 12 Computer Science Viva Voce Questions with answer

Comments are closed.

Copywrite © 2020-2024, CBSE Python,
All Rights Reserved
error: Content is protected !!