XII CS Report File
XII CS Report File
XII
Session: 2023-24
TABLE OF CONTENTS
➢Certificate
➢Python Programs
➢Python-SQL Connectivity Programs
➢ SQL Queries
Certificate of Completion
_____________________ _____________________
PROGRAMS
Question: 1
Write a python script 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
Question: 2
Write a python script 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
Question:3
Write a python script to take input for 3 numbers, check and print the largest
number?
Method:1
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
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
elif(b>c):
m=b
else:
m=c
print("Max no = ",m)
Output:
Enter 1st no 25
Enter 2nd no 98
Enter 3rd no 63
Max no = 98
Question:4
Write a python script 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")
Output 1:
Enter 1st no 10
Enter 2nd no 20
Enter the operator (+,-,*,/) : +
Sum = 30
Output 2:
Enter 1st no 10
Enter 2nd no 36
Enter the operator (+,-,*,/) : –
Difference = 26
Question:5
Write a python script to take input for name and age of a person check and print
whether the person can vote or not?
name=input("Enter name: ")
age=int(input("Enter age: "))
if(age>=18):
print("you can vote")
else:
print("you cannot vote")
Output 1:
Enter name: Python
Enter age: 19
you can vote
Output 2:
Enter name: Python
Enter age: 14
you cannot vote
Question:6
Write a python script to take input for a number and print its table?
n=int(input("Enter any no "))
i=1
while(i<=10):
t=n*i
print(n," * ",i," = ",t)
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
Questions:7
Write a python script 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
Question:8
Write a python script 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")
Output 1:
Enter the number to check : 153
Armstrong Number
Output 2:
Enter the number to check : 152
Not an Armstrong Number
Question: 9
Write a python script 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
Question:10
Write a python script 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 = 10
#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
Question: 11
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
Question: 12
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
Question:13
Write a python program to read a file named “story.txt”, count and print total
alphabets in the file?
def count_alpha():
al=0
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if((c>='A' and c<='Z') or (c>='a' and c<='z')):
al=al+1
print("total alphabets ",al)
#function calling
count_alpha()
Output:
Hello how are you
12123
bye
total lower case alphabets 17
Question:14
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("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
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
elif(c>='0' and c<='9'):
d=d+1
elif(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()
Question: 15
Write a python program to read a file named “story.txt”, count and print total
words starting with “a” or “A” in the file?
def count_words():
w=0
with open("story.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:
are
Ankur
Amit
Aman
total words starting with ‘a’ are 4
Question: 16
Write a python program to read a file named “story.txt”, count and print total
lines starting with vowels in the file?
Sol:
vowels="AEIOUaeiou"
with open(“story.txt”) 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
Question: 17
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 pymysql
# Open database connection
#conn=pymysql.connect(host='localhost',user='root',password='',db='test')
db = pymysql.connect("localhost","root","","test4")
# prepare a cursor object using cursor() method
c = db.cursor()
r=int(input("Enter roll no "))
n=input("Enter name ")
p=int(input("Enter per "))
try:
# execute SQL query using execute() method.
c.execute("insert into student (roll,name,per) values
(%s,%s,%s)",(r,n,p))
#to save the data
db.commit()
print("Record saved")
except:
db.rollback()
# disconnect from server
db.close()
# function calling
insert_data()
Output:
Enter roll no 101
Enter name amit
Enter per 97
Record saved
Program 18:
Python interface with MySQL
Write a function to display all the records stored in a table using python and
MySQL interface.
Sol:
def display_all():
#display the records from a table
#field by field
import pymysql
# Open database connection
#conn=pymysql.connect(host='localhost',user='root',password='',db='test')
db = pymysql.connect("localhost","root","","test4")
# prepare a cursor object using cursor() method
try:
c = db.cursor()
sql='select * from student;'
c.execute(sql)
countrow=c.execute(sql)
print("number of rows : ",countrow)
#data=a.fetchone()
data=c.fetchall()
#print(data)
print("=========================")
print("Roll No Name Per ")
print("=========================")
for eachrow in data:
r=eachrow[0]
n=eachrow[1]
p=eachrow[2]
# Now print fetched result
print(r,' ',n,' ',p)
print("=========================")
except:
db.rollback()
# disconnect from server
db.close()
# function calling
display_all()
Output:
number of rows : 2
=========================
Roll No Name Per
=========================
102 aaa 99
101 amit 97
=========================
Program: 19
Python interface with MySQL
Write a function to search a record stored in a table using python and MySQL
interface.
Sol:
def search_roll():
#searching a record by roll no
#display the records from a table
#field by field
import pymysql
#Open database connection
#conn=pymysql.connect(host='localhost',user='root',password='',db='test')
db = pymysql.connect("localhost","root","","test4")
# prepare a cursor object using cursor() method
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=a.fetchone()
data=c.fetchall()
#print(data)
for eachrow in data:
r=eachrow[0]
n=eachrow[1]
p=eachrow[2]
# Now print fetched result
if(r==roll):
z=1
print(r,n,p)
if(z==0):
print("Record is not present")
except:
db.rollback()
# disconnect from server
db.close()
# function calling
search_roll()
Output:
Enter roll no to search 101
number of rows : 2
101 amit 97
SQL Questions
Problem: 1
Consider the following tables product and client. Further answer the questions
given below.
TABLE:PRODUCT
P_ID PRODUCTNAME MANUFACTURER PRICE
TP01 TALCOM POWDER LAK 40
FW05 FACE WASH ABC 45
BS01 BATH SOAP ABC 55
SH06 SHAMPOO XYZ 120
FW12 FACE WASH XYZ 95
TABLE:CLIENT
C_ID CLIENTNAME City P_ID
01 COSMETIC SHOP Delhi FW05
06 TOTAL HEALTH Mumbai BS01
12 LIVE LIFE Delhi SH06
15 PRETTY WOMAN Delhi FW12
16 DREAMS Banglore TP01
Queries
Q.1.
To display the details of those clients whose city is “delhi”
Ans:
Select * from client where city=’Delhi’;
Q.2
To display the details of products whose price is in the range of 50 to 100
Ans:
Select * from product where price between 50 and 100;
select * from product where price>=50 and price<=100;
Q.3
TO DISPLAY THE client name ,city from table client and productname and
price from the table product with their corresponding matching p_id
Ans:
Select clientname, city, productname, price from client, product
where client.p_id=product.p_id;
Q.4
To increase the price of the product by 10
Ans:
Update product set price=price+10;
Q.5.
Select distinct city from client;
Ans:
Delhi
Mumbai
Banglore
Problem:2
Consider the following tables CONSIGNOR and CONSIGNEE. Further answer
the questions given below.
TABLE:CONSIGNOR
CNORID CNORNAME CNORADDRESS CITY
24; NEW
ND01 R SINGHAL
ABC ENCLAVE DELHI
AMIT 123; PALM NEW
ND02
KUMAR AVENUE DELHI
5/A; SOUTH
MU15 R KOHLI MUMBAI
STREET
MU50 S KAUR 27-K; WESTEND MUMBAI
TABLE:CONSIGNEE
CNEEID CNORID CNEENAME CNEEADDRESS CNEECITY
RAHUL
MU05 ND01 5; PARK AVENUE MUMBAI
KISHORE
16/J; NEW
ND08 ND02 P DHINGRA
MOORE ENCLAVE DELHI
2A; CENTRAL
KO19 MU15 A P ROY KOLKATA
AVENUE
P 245;
MU32 ND02 S MITTAL MUMBAI
AB COLONY
13; BLOCK D; A NEW
ND48 MU50 B P JAIN
VIHAR DELHI
Queries
Q1.
To display the names of all the consignors from Mumbai
Ans
Select cnorname From consignor Where city=’mumbai’;
Q2.
To display the cneeid,cnorname,cnoradress,cneenmae,cneeaddress for every
consignee
Ans
Select cneeid,cnoraddress,cneename,cneeaddess From consignor, consignee
Where consignor.cnorid=consignee.cnorid;
Q3.
To display consignee details in ascending order of cneename.
Ans
Select * From consignee Order by cneename;
Q4.
To display number of consignee from each city.
Ans
Select cneecity,count(cneecity) From consignee Group by cneecity;
Q5.
Select distinct cneecity from consignee;
Ans
Mumbai