PracticalsPrgms12A (1)
PracticalsPrgms12A (1)
List of Practical –
1. Write a Python program to take three numbers from user and print their
average.
Output-
Enter first number : 10
Enter second number : 20
Enter third number : 30
Average of 10 20 and 30 = 20.0
2. Write a Python program to read a line and print number of uppercase letters,
number of lowercase letters, number of alphabets and number of digits in it.
Output
Enter some text : I Am 15 YearS Old
Number of alphabets = 11
Number of uppercase letters = 5
Number of lowercase letters = 6
Number of digits = 2
Number of spaces = 4
3. Write a Python program to create a dictionary whose keys are months names
and values are number of days in the corresponding months. Ask the user to
enter a month name and use dictionary to print number of days in that
month.
Output-
Enter first three characters of month name : Mar
Number of days in Mar = 31
4. Given 3 lists L1, L2 and L3, Write a Python program to add individual
elements of L1 and L2 to L3. The order of elements in the resultant list should
be elements of L3, L1 and L2.
#Program to add individual elements of L2 and L3 to L1
L1 = [1, 3, 5, 7]
L2 = [2, 4, 6, 8]
L3 = [10, 20, 30, 40]
print("L1 = ", L1)
print("L2 = ", L2)
print("L3 = ", L3)
L3.extend(L1)
L3.extend(L2)
print("Modified list, L3 = ", L3)
Output –
L1 = [1, 3, 5, 7]
L2 = [2, 4, 6, 8]
L3 = [10, 20, 30, 40]
Modified list, L3 = [10, 20, 30, 40, 1, 3, 5, 7, 2, 4, 6, 8]
Output-
Enter a number : 25
25 is an odd number.
Output-
Enter a number : 15
Square of 15 = 225
7. Write a Python program to create a function to print sum of squares of first n
natural numbers.
Output –
Enter the number of terms : 6
1 4 9 16 25 36
Sum of Squares of first 6 numbers = 91
8. Write a python program to read a text file line by line and display each word
separated by #.
#to read a text file line by line and display each word separated by #
f1 = open("D:\\PythonPr\\abc.txt","r")
while True:
ln = f1.readline()
if ln!="":
L=ln.split()
for i in L:
print(i,end="#")
else:
break
f1.close()
Output-
Twinkle#twinkle#little#star#How#I#wonder#what#you#are#Up#above
#the#world#so#high#Like#a#diamond#in#the#sky#
9. Write a python program to read a text file and display the number of vowels
/consonants/ uppercase /lowercase characters in the file.
Output-
Number of alphabets = 85
Number of uppercase letters = 5
Number of lowercase letters = 80
Number of vowels = 32
Number of consonants = 53
10. Write a python program to write all the lines that contain the characters ‘a' in
another file.
#To write all the lines that contain the characters ‘a' in another file.
f1 = open("D:\\PythonPr\\abc.txt","r")
f2 = open("D:\\PythonPr\\xyz.txt","w")
while True:
ln = f1.readline()
if ln != "":
for i in ln:
if i == 'a' or i == 'A':
f2.write(ln)
else:
break
f1.close()
f2.close()
Output-
abc.txt –
Twinkle, twinkle, little star
How I wonder wht you re
Up bove the world so high
Like A dimond in the sky
Xyz.txt-
Twinkle, twinkle, little star
Like A dimond in the sky
11. Write a python program to create a binary file with name and roll number.
Search for a given roll number and display the name. If not found display
appropriate message.
import pickle
f1 = open("D:\\PythonPr\\myfile.dat","wb")
stud = {}
ans = 'y'
while ans == 'y' or ans == 'Y' :
s_roll = int(input("Enter Roll Number : "))
sname = input("Enter Name of Student : ")
marks = float(input("Enter marks : "))
stud["Roll"] = s_roll
stud["Name"] = sname
stud["Marks"] = marks
pickle.dump(stud, f1)
ans = input("Do you want to enter more records? (y/n)")
f1.close()
f2 = open("D:\\PythonPr\\myfile.dat","rb")
stud={}
found = False
print("--------------------------------------------")
print()
n = int(input("Enter the Roll Number to search : "))
try:
while True:
stud = pickle.load(f2)
if stud["Roll"] == n:
print("Record Found")
print("Student Details - ")
print("\tRoll No", stud["Roll"])
print("\tStudent's Name: ", stud["Name"])
print("\tMarks: ", stud["Marks"])
found = True
break
except:
if found == False:
print("Record Not Found")
f2.close()
Output-
Enter Roll Number : 1
Enter Name of Student : Ajay
Enter marks : 65
Do you want to enter more records? (y/n)y
Enter Roll Number : 2
Enter Name of Student : Amar
Enter marks : 87
Do you want to enter more records? (y/n)y
Enter Roll Number : 3
Enter Name of Student : Amit
Enter marks : 45
Do you want to enter more records? (y/n)n
--------------------------------------------
f1 = open("D:\\PythonPr\\myfile.dat","wb")
stud = {}
ans = 'y'
while ans == 'y' or ans == 'Y':
s_roll = int(input("Enter Roll Number : "))
sname = input("Enter Name of Student : ")
marks = float(input("Enter marks : "))
stud["Roll"] = s_roll
stud["Name"] = sname
stud["Marks"] = marks
pickle.dump(stud, f1)
ans = input("Do you want to enter more records? (y/n)")
f1.close()
f2 = open("D:\\PythonPr\\myfile.dat","rb+")
stud={}
found = False
print("--------------------------------------------")
print()
n = int(input("Enter the Roll Number to search : "))
try:
while True:
rpos = f2.tell()
stud = pickle.load(f2)
if stud["Roll"] == n:
print("Record Found")
print("Student Details - ")
print("\tRoll No", stud["Roll"])
print("\tStudent's Name: ", stud["Name"])
print("\tMarks: ", stud["Marks"])
marks = float(input("Enter the new marks : "))
stud["Marks"] = marks
f2.seek(rpos)
pickle.dump(stud, f2)
print("Updated Record -")
print("\tRoll No", stud["Roll"])
print("\tStudent's Name: ", stud["Name"])
print("\tMarks: ", stud["Marks"])
found = True
break
except:
if found == False:
print("Record Not Found")
f2.close()
Output -
Enter Roll Number : 1
Enter Name of Student : abc
Enter marks : 34
Do you want to enter more records? (y/n)y
Enter Roll Number : 2
Enter Name of Student : pqr
Enter marks : 45
Do you want to enter more records? (y/n)y
Enter Roll Number : 3
Enter Name of Student : xyz
Enter marks : 67
Do you want to enter more records? (y/n)n
--------------------------------------------
import csv
f1= open("Product.csv", "w")
rec = []
iwriter = csv.writer(f1)
#Writing header row
iwriter.writerow(['ProductId', 'ProductName', 'Quantity', 'Price'])
ch = 'y'
cnt = 0
while ch == 'y' or ch == 'Y':
print("Enter Product Details : #", cnt + 1)
PId = input("Enter Product Id : ")
PName = input("Enter Product Name : ")
qty = int(input("Enter Quantity : "))
price = float(input("Enter Price : "))
Pr_rec = [PId, PName, qty, price]
rec.append(Pr_rec)
cnt += 1
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")
ch = input("Do you want to enter more records ? (y/n)")
iwriter.writerows(rec)
f1.close()
print("Record saved in csv file.")
Output -
Enter Product Details : # 1
Enter Product Id : P101
Enter Product Name : GelPen
Enter Quantity : 5
Enter Price : 30
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Do you want to enter more records ? (y/n)y
Enter Product Details : # 2
Enter Product Id : P102
Enter Product Name : Notebook
Enter Quantity : 3
Enter Price : 60
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Do you want to enter more records ? (y/n)y
Enter Product Details : # 3
Enter Product Id : P103
Enter Product Name : Eraser
Enter Quantity : 6
Enter Price : 10
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Do you want to enter more records ? (y/n)n
Record saved in csv file.
Product.csv -
ProductId,ProductName,Quantity,Price
P101,GelPen,5,30.0
P102,Notebook,3,60.0
P103,Eraser,6,10.0
14. Write a Python program to read data from a csv file(Product.csv) and display
them.
import csv
with open("Product.csv", "r", newline = "\r\n") as f1:
creader = csv.reader(f1)
for rec in creader:
if rec[0] != "ProductId":
print("Product Id - ", rec[0])
print("Product Name - ", rec[1])
print("Quantity - ", rec[2])
print("Price - ", rec[3])
print("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")
Output -
Product Id - P101
Product Name - GelPen
Quantity - 5
Price - 30.0
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Product Id - P102
Product Name - Notebook
Quantity - 3
Price - 60.0
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Product Id - P103
Product Name - Eraser
Quantity - 6
Price - 10.0
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
15. Write a random number generator that generates random numbers between
1 and 6.
import random
n = random.randrange(1,7)
print("Guess the number on the dice ....(between 1 and 6):")
guess = int(input("Enter a number: "))
while n!= guess:
if guess > 6:
print("Invalid number!!!")
guess = int(input("Enter number again: "))
if guess < n:
print("Too low")
guess = int(input("Enter number again: "))
elif guess > n:
print("Too high!")
guess = int(input("Enter number again: "))
else:
break
print("You guessed it right!!!")
Output-
Guess the number on the dice ....(between 1 and 6):
Enter a number: 4
Too high!
Enter number again: 1
Too low
Enter number again: 2
You guessed it right!!!
16. Write a python program to implement a stack (stack of students name) using
list.
#Function to display elements of stack
def display(st):
if(isEmpty(st)):
print('Stack is empty!!!')
else:
print("Elements of the Stack are :")
for x in range(len(st)-1,-1,-1):
print('\t\t',st[x])
# Program starts
st = []
top = None
print("Stack Operations")
print("************")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display Stack")
print("5. Exit")
while True:
choice=input("Enter your choice...")
if choice=='1':
val = int(input("Enter an element : "))
push(st, val)
elif choice=='2':
pop(st)
elif choice=='3':
peek(st)
elif choice=='4':
display(st)
elif choice == '5':
print('Thankyou...')
break
else:
print("Invalid choice!!!")
Output-
Stack Operations
************
1. Push
2. Pop
3. Peek
4. Display Stack
5. Exit
Enter your choice...1
Enter an element : 12
Enter your choice...1
Enter an element : 14
Enter your choice...1
Enter an element : 16
Enter your choice...4
Elements of the Stack are :
16
14
12
Enter your choice...3
Top element of stack is = 16
Enter your choice...2
Popped value = 16
Enter your choice...4
Elements of the Stack are :
14
12
Enter your choice...2
Popped value = 14
Enter your choice...4
Elements of the Stack are :
12
Enter your choice...3
Top element of stack is = 12
Enter your choice...5
Thankyou...
17. Write a python program to integrate SQL with python and extract and print data
from the table student.(columns – roll int, sname char(20), class int, marks decimal )
import mysql.connector as sq
mycon = sq.connect(host='localhost', user='root', passwd = 'root', database =
'stud')
if mycon.is_connected() == False:
print("Error connecting to MySQL Database")
cur = mycon.cursor()
st = "Select * from student;"
cur.execute(st)
data = cur.fetchall()
print('Student\'s Records : \n')
for i in data:
print('Roll No : ', i[0])
print('Student\'s Name : ', i[1])
print('Class : ', i[2])
print('Marks : ', i[3])
print('_________________________')
mycon.close()
Output-
Student's Records :
Roll No : 101
Student's Name : Amar
Class : 12
Marks : 77.00
_________________________
Roll No : 102
Student's Name : Riya
Class : 12
Marks : 82.00
_________________________
Roll No : 103
Student's Name : Sima
Class : 11
Marks : 66.00
_________________________
18. Write a python program to insert a record in MySQL table stud using database
connectivity.
import mysql.connector as sq
mycon = sq.connect(host='localhost', user='root', passwd = 'root', database =
'stud')
if mycon.is_connected() == False:
print("Error connecting to MySQL Database")
cur = mycon.cursor()
roll = int(input("Enter Roll No. : "))
nm = input("Enter Name : ")
cls = int(input("Enter class : "))
mk = float(input("Enter marks : "))
st = "insert into student values(%s, '%s', %s, %s);"%(roll, nm, cls, mk)
cur.execute(st)
print('Student\'s Records entered successfully.')
mycon.commit()
mycon.close()
Output-
Enter Roll No. : 104
Enter Name : Ajay
Enter class : 11
Enter marks : 69
Student's Records entered successfully.
Database-
19. Write a python program to integrate SQL with python and search a
student using rollno, if it is present, display the record.
import mysql.connector as sq
mycon = sq.connect(host='localhost', user='root', passwd = 'root', database =
'stud')
if mycon.is_connected() == False:
print("Error connecting to MySQL Database")
roll = int(input("Enter roll number to search : "))
cur = mycon.cursor()
st = "Select * from student where roll = {};".format(roll)
cur.execute(st)
data = cur.fetchone()
print('Student\'s Records : \n')
print('Roll No : ', data[0])
print('Student\'s Name : ', data[1])
print('Class : ', data[2])
print('Marks : ', data[3])
mycon.close()
Output –
Enter roll number to search : 102
Student's Records :
Roll No : 102
Student's Name : Riya
Class : 12
Marks : 82.00
20. Write a python database connectivity script that deletes records from emp table
of employee database.
import mysql.connector as sq
mycon = sq.connect(host='localhost', user='root', passwd = 'root', database =
'stud')
if mycon.is_connected() == False:
print("Error connecting to MySQL Database")
roll = int(input("Enter roll number to delete : "))
cur = mycon.cursor()
st = "Delete from student where roll = {};".format(roll)
cur.execute(st)
print('Record deleted successfully.')
mycon.commit()
mycon.close()
Output –
Enter roll number to delete : 103
Record deleted successfully.
Database –
SQL-
1. Write a SQL query to create a table student with following specifications-
Fied name data-type size constraint
S_Roll integer -- Primary key, Not Null
S_Name char 20 Not null
Class integer -- --
Marks decimal -- --
DESC student;
5. Display Name and class of the students whose name starts with letter ‘A'.
SELECT S_Name, Class FROM student
WHERE S_Name LIKE ‘A%’ ;
Consider following table emp and dept
Table - emp
ename empno age deptno salary gender
Nitin 101 42 20 22000 M
Saransh 103 36 30 28000 M
Kavita 107 41 20 35000 F
Aparna 108 34 30 38000 F
Aman 112 31 10 31000 M
Table – dept
deptno department
10 Sales
20 Production
30 IT
40 HR
10. Display name, department and age of all the female employees of Sales
department in descending order of their age.