CS - PRAC
CS - PRAC
Write a Python program to function with key and value, and 15.07.2024
5.
update value at that key in the dictionary entered by the user.
Write a python program to remove all the lines that contain 15.08.2024
14.
the character “a‟ in a file and write it to another file.
Input
n=int(input("Enter the length of list: "))
l1=[]
for i in range(0,n):
el=input("Enter a element: ")
l1.append(el)
def lin(l1,n):
se=input("Enter the element you want to search for: ")
count=0
f=0
for i in range(0,n):
if l1[i]==se:
count+=1
print(f"Found at: {i+1} position")
f=1
if f==0:
print("Not found!")
print(f"{se} has occured {count} times")
lin(l1,n)
Output
Enter the length of list: 3
Enter a element: 1
Enter a element: 2
Enter a element: 1
Enter the element you want to search for: 1
Found at: 1 position
Found at: 3 position
1 has occured 2 times
AIM
Write a python program to search an element in a list and display
the frequency of elements present in the list and their location using
binary search by using a user defined function.
Input
Input
a=int(input("Enter the No. of elements in the list: " ))
L0=[]
L1=[]
for i in range(0,a):
b=int(input("Enter the element: "))
L0.append(b)
def fun(e):
for i in e:
if i%2==0:
c=int(i/2)
L1.append(c)
else:
d=i*2
L1.append(d)
return L1
print("Updated List! \n",fun(L0))
Output
Enter the No. of elements in the list: 4
Enter the element: 1
Enter the element: 2
Enter the element: 3
Enter the element: 4
Updated List!
[2, 1, 6, 2]
AIM
Write a Python to program input n numbers in tuple and pass it to a
function to count how many even and odd numbers were entered.
Input
l1=[]
od=0
ev=0
a=int(input("Enter no. elements in the tuple: "))
for i in range(0,a):
b=int(input("Enter the element: "))
l1.append(b)
t1=tuple(l1)
for i in t1:
if i==0:
ze+=1
elif i%2==0:
ev+=1
else:
od+=1
print("no. of odd elements input: ",od)
print("no. of even elements input: ",ev)
Output
Enter no. elements in the tuple: 4
Enter the element: 1
Enter the element: 3
Enter the element: 4
Enter the element: 1080
no. of odd elements input: 2
no. of even elements input: 2
AIM
Write a Python program to a function with key and
value, and update value at that key in the dictionary
entered by the user.
Input
dic={"Name":"Gulshan","class":12,"roll":30}
k=input("Enter key of the value you want to update: ")
def fun(d,c):
d[c]=input("Enter new Value: ")
return d
print("New Dictionary: \n",fun(dic,k))
Output
Enter key of the value you want to update: roll
Enter new Value: 31
New Dictionary:
{'Name': 'Gulshan', 'class': 12, 'roll': '31'}
AIM
Write a Python program to pass a string to a function and
count how many vowels are present in the string.
Input
a=input("Enter a string: ")
def fun(b):
vow=0
for i in a:
if i.lower() in 'aeiou':
vow+=1
return vow
print("No. of vowels in the string: ",fun(a))
Output
Enter a string: My name is Gulshan! How are you?
No. of vowels in the string: 10
AIM
Write a Python program to generate (Random Number) that
generates random numbers between 1 and 6 (simulates a dice)
using a user defined function.
Input
import random
def die():
while True:
ch=input("roll the die? (y/n):")
if ch.lower() == 'n':
break
elif ch=="":
continue
elif ch not in 'yYnN':
print("INVALID CHOICE!")
continue
num=random.randint(1,6)
print("You got :",num)
die()
print("THANK YOU!")
Output
rroll the die? (y/n):y
You got : 3
roll the die? (y/n):y
You got : 4
roll the die? (y/n):hello
INVALID CHOICE!
roll the die? (y/n):n
THANK YOU!
AIM
Write a menu driven python program to implement 10 python
mathematical functions.
Input
import math as m
Menu="ENTER CHOICE!(1-11)\n\n1.Calculate
Sqaureroot\n2.Calculate X^Y\n3.round off to nearest larger
int\n4.round off to nearest smaller int\n5.Calculate
Factorial\n6.Evaluate GCD of X and Y\n7.Calculate LogX base
Y\n8.Calculate sinx(in rad.)\n9.Calculate cosx(in rad.)\n10.Value of
PI\n11.Exit"
print(Menu,"\n")
while True:
try:
ch=int(input("Enter Your choice:" ))
if ch==1:
num=int(input("Enter the Number: "))
print(m.sqrt(num))
elif ch==2:
num1=int(input("Enter X:"))
num2=int(input("Enter Y:"))
print(m.pow(num1,num2))
elif ch==3:
num=float(input("Enter the Number: "))
print(m.ceil(num))
elif ch==4:
num=float(input("Enter the Number: "))
print(m.floor(num))
elif ch==5:
num=int(input("Enter the Number: "))
print(m.factorial(num))
elif ch==6:
num1=int(input("Enter X:"))
num2=int(input("Enter Y:"))
print(m.gcd(num1,num2))
elif ch==7:
num1=int(input("Enter X:"))
num2=int(input("Enter Y:"))
print(m.log(num1,num2))
elif ch==8:
ang=float(input("Enter angle in radians: (coeffecient to pi);"))
print(m.sin(m.pi*ang))
elif ch==9:
ang=float(input("Enter angle in radians: (coeffecient to pi);"))
print(m.cos(m.pi*ang))
elif ch==10:
print(m.pi)
elif ch==11:
print("THANKS!","\n")
break
else:
print("ENTER VALID CHOICE!!\n")
except ValueError:
print("ENTER VALID CHOICE!!\n")
Output
ENTER CHOICE!(1-11)
1.Calculate Sqaureroot
2.Calculate X^Y
3.round off to nearest larger int
4.round off to nearest smaller int
5.Calculate Factorial
6.Evaluate GCD of X and Y
7.Calculate LogX base Y
8.Calculate sinx(in rad.)
9.Calculate cosx(in rad.)
10.Value of PI
11.Exit
Enter Your choice:1
Enter the Number: 16
4.0
Enter Your choice:2
Enter X:2
Enter Y:3
8.0
Enter Your choice:3
Enter the Number: 6.0
6
Enter Your choice:4
Enter the Number: 6.1
6
Enter Your choice:5
Enter the Number: 10
3628800
Enter Your choice:6
Enter X:10
Enter Y:100
10
Enter Your choice:7
Enter X:10
Enter Y:10
1.0
Enter Your choice:0.5
ENTER VALID CHOICE!!
Enter Your choice:8
Enter angle in radians: (coeffecient to pi);0.5
1.0
Enter Your choice:9
Enter angle in radians: (coeffecient to pi);2
1.0
Enter Your choice:10
3.141592653589793
Enter Your choice:gulshan
ENTER VALID CHOICE!!
Enter Your choice:11
THANKS!
AIM
Write a python program to implement python string functions.
Input
str="my name is Gulshan."
print("Some string Functions")
print(len(str))
print(str.capitalize())
print(str.title())
print(str.upper())
print(str.lower())
print(str.count('n'))
print(str.find('z'))
print(str.replace('Gulshan','Nobody') )
print(str.index('G'))
print(str.isalnum())
print(str.isalnum())
print(str.isalpha())
print(str.islower())
print(str.isnumeric())
print(str.isspace())
print(str.istitle())
print(str.isupper())
Output
Some string Functions False
19 False
My name is gulshan. False
My Name Is Gulshan. False
MY NAME IS GULSHAN. False
my name is gulshan. False
2 False
-1 False
my name is Nobody.
11
AIM
Write a menu driven program in python to delete the name of a
student from the dictionary and to search phone no of a student by
student name.
Input
students = {"Gulshan1": "1234567890","Gulshan2":
"9876543210","Gulshan3": "5678901234"}
menu="\tMENU\n1.Delete from Dictionary\n2.Search Phone number
using name from Dictionary\n3.Exit"
print(menu)
while True:
try:
ch=int(input("Enter choice[1-3]: "))
if ch==1:
name=input("Enter name of the student to delete phone no.: ")
if name in students:
del students[name]
print(name,"has been deleted from the dictionary.")
else:
print("Name not Found!")
elif ch==2:
name = input("Enter the name of the student to search for: ")
if name in students:
print("The phone number for ",name,"is",students[name])
else:
print(f"Student named '{name}' not found in the dictionary.")
elif ch==3:
print("Exiting the program. Thank you!")
break
else:
AIM
print("Invalid choice! Please select a valid option (1-3).")
except ValueError:
print("Invalid input! Please enter a numeric value.")
Output
MENU
1.Delete from Dictionary
2.Search Phone number using name from Dictionary
3.Exit
Enter choice[1-3]: q
Invalid input! Please enter a numeric value.
Enter choice[1-3]: 1
Enter name of the student to delete phone no.: Gulshan
Name not Found!
Enter choice[1-3]: Gulshan1
Invalid input! Please enter a numeric value.
Enter choice[1-3]: 1
Enter name of the student to delete phone no.: Gulshan1
Gulshan1 has been deleted from the dictionary.
Enter choice[1-3]: 2
Enter the name of the student to search for: Gulshan1
Student named 'Gulshan1' not found in the dictionary.
Enter choice[1-3]: Gulshan2
Invalid input! Please enter a numeric value.
Enter choice[1-3]: 2
Enter the name of the student to search for: Gulshan2
The phone number for Gulshan2 is 9876543210
Enter choice[1-3]: 3
Exiting the program. Thank you!
AIM
Write a python program to read and display file content line by
line with each word separated by #.
Input
f=open("brain.txt","r")
re=f.readlines()
for i in re:
wo=i.split()
for j in wo:
print(j+'#',end="")
print()
Output
The#brain#is#complex:#The#brain#is#the#most#complex#organ#i
n#the#human#body.#
It#controls#many#functions,#including#thought,#memory,#emoti
on,#touch,#motor#
skills,#vision,#breathing,#temperature,#and#hunger.#
AIM
Write a python program Read a text file and display the number of
vowels, consonants, uppercase, lowercase characters in the file
Input
f=open("brain.txt","r")
vow=0
con=0
upp=0
low=0
re=f.read()
for i in re:
if i in 'aeiou':
vow+=1
else:
con+=1
if i.isupper():
upp+=1
if i.islower():
low+=1
else:
continue
print("No. of vowels ",vow)
print("No. of consonatnts: ",con)
print("No. of uppercase characters: ",upp)
print("No. of lowercase characters:",low)
Output
No. of vowels 57
No. of consonatnts: 149
No. of uppercase characters: 3
No. of lowercase characters: 160
AIM
Write a Menu driven program in python to count spaces,
digits, words and lines from text file TOY.txt
Input
spa=0
words=0
digits=0
Menu="MENU:\n1. Count Spaces\n2. Count Digits\n3. Count
Words\n4. Count Lines\n5. Exit"
f=open("TOY.txt","r")
re=f.read()
for i in re:
if i==" ":
spa+=1
if i.isnumeric():
digits+=1
f.seek(0)
re1=f.readlines()
for i in re1:
wo=i.split()
for j in wo:
words+=1
print("No. of lines: ",len(re1))
print("No. of Spaces: ",spa)
print("No. of digits: ",digits)
print("No. of words: ",words)
Output
No. of lines: 3
No. of Spaces: 52
No. of digits: 2
No. of words: 54
AIM
Write a python program to remove all the lines that contain
the character “a‟ in a file and write it to another file.
Input
f=open("file.txt","r")
re=f.readlines()
f.close()
f1=open("file.txt","w")
f2=open("newfile","w")
for i in re:
if 'a' in i:
f2.write(i)
else:
f1.write(i)
f1.close()
f2.close()
print("SUCCESS!")
Output
SUCCESS!
AIM
Write a python program to create a binary file with name and roll
number. Search for a given roll number and display name, if not
found display appropriate message.
Input
students = {1: "Gulshan",2: "Gulshan1",3: "Gulshan2"}
import pickle
f=open("bin.dat","wb")
pickle.dump(students,f)
f.close()
f1=open("bin.dat","rb")
re=pickle.load(f1)
while True:
try:
ch=input("Search for name(y/n): ")
if ch.lower()=='y':
roll=int(input("Enter roll no.: "))
if roll in re:
print("The name of roll no.",roll,"is",re[roll])
continue
else:
print("Roll no. not found!!")
elif ch.lower()=='n':
print("Thank You!")
break Output
else:
print("Enter Valid Input!") Search for name(y/n): y
except EOFError: Enter roll no.: 1
break The name of roll no. 1 is Gulshan
Input
import pickle
student={}
for i in range(0,5):
roll=int(input("Enter Roll no.: "))
name=input("Enter name: ")
marks=float(input("Enter Marks: "))
student[roll]=(name,marks)
f=open("stud.dat","wb")
pickle.dump(student,f)
f.close()
print("Success!")
Output
Enter Roll no.: 1
Enter name: Gulshan
Enter Marks: 95
Enter Roll no.: 2
Enter name: Gulshan2
Enter Marks: 96
Enter Roll no.: 3
Enter name: Gulshan3
Enter Marks: 97
Enter Roll no.: 4
Enter name: Gulshan4
Enter Marks: 98
Enter Roll no.: 5
Enter name: Gulshan5
Enter Marks: 99
Success!
AIM
Write a python program to create a CSV file by entering user-id and
password, read and search the password for given user-id.
Input
import csv
n=int(input("How many record you want to enter: "))
data=[]
for i in range(0,n):
user_id=input("Enter userid: ")
password=input("Enter password: ")
data.append([user_id,password])
f=open("login.csv","w",newline="")
w=csv.writer(f,)
w.writerow(['userid','password'])
w.writerows(data)
f.close()
f1=open("login.csv","r")
re=csv.reader(f1)
next(re)
uid=input("Enter uid you want to search for: ")
rec=0
for i in re:
if i[0]==uid:
print("password is: ",i[1])
rec=1 Output
if rec==0:
How many record you want to enter: 3
print("No such record found!")
Enter userid: _gul101
Enter password: 12345678
Enter userid: gul_09
Enter password: qwerty
Enter userid: kv_chhawla
Enter password: bsf.camp
Enter uid you want to search for:
kv_chhawla
password is: bsf.camp
AIM
Write a menu driven python program to create a CSV file by
entering dept-id, name and city, read and search the record for
given dept-id.
Input
import csv
print("\tMenu\n1.Create CSV File\n2.Search record as per dept
no.\n3.Exit\n")
def create():
name=input("Enter file name: ")
f=open(name+".csv","w",newline="")
w=csv.writer(f)
w.writerow(["dept_id","name","city"])
n=int(input("Enter no. of records: "))
for i in range(0,n):
did=int(input("Enter dept_id: "))
na=input("Enter name: ")
city=input("Enter city: ")
w.writerow([did,na,city])
print("Success!\n")
def search():
name=input("Enter file name you want to search in: ")
d_id=input("Enter dept_id of emp you want to search: ")
f1=open(name+".csv","r")
re=csv.reader(f1)
next(re)
rec=0
for i in re:
if i[0]==d_id:
print("records\n",i,"\n")
rec=1
if rec==0:
print(f"No records associated with: {d_id}/n")
while True:
try:
ch=int(input("Enter choice (1-3): "))
if ch==1:
create()
elif ch==2:
search()
elif ch==3:
print("Thanks for using the system!")
break
else:
print("Invalid Choice!")
except ValueError:
print("Enter Numeric value!")
Output
Menu
1.Create CSV File
2.Search record as per dept no.
3.Exit
Input Output
class Stack: Options:
def __init__(self): 1. Push
self.stack = [] 2. Pop
def push(self, item): 3. Exit
self.stack.append(item) Enter your choice: 3
print(f"{item} pushed to stack") Exiting...
def pop(self):
if not self.is_empty():
item = self.stack.pop()
print(f"{item} popped from stack")
return item
else:
print("Stack is empty")
return None
def is_empty(self):
return len(self.stack) == 0
stack = Stack()
while True:
print("\nOptions:")
print("1. Push")
print("2. Pop")
print("3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
item = int(input("Enter the item to push: "))
stack.push(item)
elif choice == 2:
stack.pop()
elif choice == 3:
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
AIM
Write a python program using the function PUSH(Arr), where Arr is a list of
numbers. From this list push all numbers divisible by 5 into a stack
implemented by using a list. Display the stack if it has at least one element,
otherwise display appropriate error messages.
Input
def PUSH(Arr):
stack = []
for num in Arr:
if num % 5 == 0:
stack.append(num)
if stack:
print("Stack:", stack)
else:
print("No numbers divisible by 5 found in the list.")
# Example usage
Arr = list(map(int, input("Enter numbers separated by space: ").split()))
PUSH(Arr)
Output
Enter numbers separated by space: 3 8 13 17
Input
def PUSH(Arr):
stack = []
for num in Arr:
if num % 5 == 0:
stack.append(num)
if stack:
print("Stack:", stack)
else:
print("No numbers divisible by 5 found in the list.")
# Example usage
Arr = list(map(int, input("Enter numbers separated by space: ").split()))
PUSH(Arr)
Output
Enter numbers separated by space: 1 5 10 12 15
Input
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password='admin')
cur = con.cursor()
cur.execute("create database if not exists company")
cur.execute("use company")
cur.execute("create table if not exists employee(empno int, name
varchar(20), dept varchar(20),salary int)")
con.commit()
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
choice = int(input("Enter Choice :"))
if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
print("%10s"% "EMPNO","%20s"% "NAME","%15s"% "DEPARTMENT",
"%10s"% "SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
elif choice==0:
con.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")
Output
OUTPUT
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :1
Enter Name :GULSHAN1
Enter Department :SALES
Enter Salary :9000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :2
Enter Name :GULSHAN2
Enter Department :IT
Enter Salary :80000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
1 GULSHAN1 SALES 9000
2 GULSHAN2 IT 80000
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :0
## Bye!! ##
AIM
Integrate SQL with Python by importing the MySQL module to search
an employee using empno and if present in table display the record,
if not display appropriate method.
Input
import mysql.connector as mycon
con=mycon.connect(host='127.0.0.1',user='root',password="admin",databas
e="company")
cur = con.cursor()
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO", "%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row [2], "%10s"%row[3])
ans=input("SEARCH MORE (Y) :")
Output
ENTER EMPNO TO SEARCH :1
EMPNO NAME DEPARTMENT SALARY
1 GULSHAN1 SALES 9000
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :2
EMPNO NAME DEPARTMENT SALARY
2 GULSHAN2 IT 80000
Input
import mysql.connector as mycon
con=mycon.connect(host="127.0.0.1",user="root",password="admin",databas
e="school")
cur = con.cursor()
while True:
print("\n### STUDENT MANAGEMENT SYSTEM ###")
choice = int(input("1. Update Student Record\n2. Delete Student
Record\n3. Exit\nEnter your choice (1-3): "))
if choice in [1, 2]:
roll_no = int(input("ENTER ROLL NO: "))
query = "select * from student where roll_no={}".format(roll_no)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount == 0:
print("Sorry: Roll number not found")
continue
if input("ARE YOU SURE YOU WANT TO {}? (y/n): ".format("UPDATE" if
choice == 1 else "DELETE")).lower() == 'y':
if choice == 1: # Update
new_class = input("ENTER NEW CLASS (LEAVE BLANK TO KEEP
CURRENT): ") or result[0][2]
new_marks = input("ENTER NEW MARKS (LEAVE BLANK TO KEEP
CURRENT): ") or result[0][3]
query = "update student set class='{}', marks={} where roll_no=
{}".format(new_class, new_marks, roll_no)
else: # Delete
query = "delete from student where roll_no={}".format(roll_no)
cur.execute(query)
con.commit()
AIM
print("### RECORD {} SUCCESSFULLY ###".format("UPDATED" if choice
== 1 else "DELETED"))
elif choice == 3:
print("Thank you for using the Student Management System. Goodbye!")
break
else:
print("Invalid choice! Please try again.")
Output
### STUDENT MANAGEMENT SYSTEM ###
1. Update Student Record
2. Delete Student Record
3. Exit
Enter your choice (1-3): 1