0% found this document useful (0 votes)
36 views

G12 - Computer Science - Lab Programs 1 To 20

The document describes 12 programs written in Python. Program 1 creates a simple calculator with functions for addition, subtraction, division and multiplication. It takes user input for two numbers and an operation and prints the result. Program 2 generates a random number between 1 and 6 to simulate rolling a dice.

Uploaded by

Shaibaaz Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

G12 - Computer Science - Lab Programs 1 To 20

The document describes 12 programs written in Python. Program 1 creates a simple calculator with functions for addition, subtraction, division and multiplication. It takes user input for two numbers and an operation and prints the result. Program 2 generates a random number between 1 and 6 to simulate rolling a dice.

Uploaded by

Shaibaaz Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Program No: 01

Program Name: Simple Calculator in Python

Aim: To Create a Simple Calculator in Python

Source Code:

def Add(a,b):
print(a+b)
def Sub(a,b):
print(a-b)
def Div(a,b):
print(a/b)
def Mul(a,b):
print(a*b)
Num_1 = int(input("Enter no.1:"))
Num_2 = int(input("Enter no.2:"))
print("Type 1: Addition")
print("Type 2: Subtraction")
print("Type 3: Division")
print("Type 4: Multiplication")
ch=int(input("Enter your Choice 1,2,3,4:"))
if ch==1:
Add(Num_1, Num_2)
elif ch==2:
Sub(Num_1, Num_2)
elif ch==3:
Div(Num_1, Num_2)
elif ch==4:
Mul(Num_1, Num_2)
else:
print("Wrong Input Choice")
Program No: 02

Program Name: Random Number Generator

Aim: To write a program in python to generate random number between 1 and 6 (stimulation a dice)

Source Code:
import random
print("To roll the dice, hit enter...!!!")
a=input()
print(random.randint(1,6))

Program No: 03

Program Name: Reading a Text File (line by line)

Aim: To write a program in python to read a text file line by line and print it

Source Code:

file=open('Forest.txt','r')
a=file.readlines()
for i in a:
print(i)
Note: Forest.txt file should contain at least 5 to 6 lines

Program No: 04

Program Name: Moving Lines from a Text File To Another Which Has 'A'
Aim: To write a python program to move all the lines that contains the character 'a' in a text
file(old_text.txt)

Source Code:
A=open("C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python38-32\\old_text.txt","r")
B=open("C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python38-32\\new_text.txt","w")
lines=A.readlines()
for i in lines:
if 'a' in i or 'A' in i:
B.write(i)
print("Copying or Moving lines which has 'a' in it Completed Successfully")
A. close()

B. close()

Program No: 05

Program Name: Read and Display words in the Text File separated by ‘#’

Aim: To write a program in python to read a text file line by line and display each word separated by a
‘#’

Source Code:
file=open('Forest.txt','r')
for i in file:
for word in i.split():
print(word, end=" # ")

Program No: 06

Program Name: Display the number of Vowels/Consonants/Lowercase/Uppercase Characters in a


Text File

Aim: To write a python program to read the text files line by line and to find the number of vowels,
consonants, lower and upper case characters

Source Code:
A=open("C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python38-32\\old_text.txt","r")

x=A.read()

print(x)

vow=0

cons=0

small=0
capital=0

for ch in x:

if(ch.islower()):

small=small+1

elif(ch.isupper()):

capital=capital+1

ch=ch.lower()

if(ch in ['a', 'e', 'i', 'o', 'u']):

vow=vow+1

elif (ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']):

cons=cons+1

print("Number of Vowels: ",vow)

print("Number of Consonanats: ",cons)

print("Number of Lower case characters: ",small)

print("Number of Upper case characters: ",capital)

Program No: 07

Program Name: Searching in a binary file

Aim: To write a Python program to create a binary file with the name and roll number. Search for a
given roll number and display the name, if not found, display an appropriate message.

Source Code:
import pickle

def BinaryWrite():

Records = []

with open('record.dat', "wb") as File:

while True:

roll_num = int(input("Enter the Roll Number:

")) name = input("Enter the Name: ")

record = [roll_num, name]

Records.append(record)

choice = input("Do you want to continue? y/n: ")

if choice in "NOno" and choice != "":


break

pickle.dump(Records, File)

print("Record Written Successfully!")

File.close()

def BinarySearch():

with open('record.dat', "rb") as File:

Records = pickle.load(File)

roll_num = int(input("Enter the Roll Number to be searched: "))

match = False

for record in Records:

if record[0] == roll_num:

print("Record matched!")

print(record)

match = True

break

if match == False:

print("Record not found ... ")

File.close()

BinaryWrite()

BinarySearch()
Program No: 08

Program Name: Updating record in a binary file

Aim: To write a Python program to create a binary file with roll number, name and marks. Input a roll
number and update the marks.

Source Code:
import pickle

def Bwrite():

f=open("Binfile.dat","wb")

sturec=[]

while True:

rno=int(input("Enter the roll no"))

name=input("Enter the name")

mark=float(input("Enter aggregate mark"))

sturec=[rno,name,mark]

pickle.dump(sturec,f)

ch=input("Do you want to continue : Y/N ")

if ch== "N":

break

f.close()

def Bupdate():

f=open("Binfile.dat","rb+")

found=False

rno=int(input("Enter the rollno to be searched"))

mark=float(input("Enter aggregate marks to be updated"))

try:

while True:

rpos=f.tell()

stu=pickle.load(f)

if stu[0]==rno:

print("Record Found... Updating...")


stu[2]=mark

f.seek(rpos)

pickle.dump(stu,f)

found=True

except EOFError:

if found==False:

print("Sorry,No matching record found")

else:

print("Record successfully updated.")

f.close()

def BRead():

f=open("Binfile.dat",'rb')

try:

while True:

rec=pickle.load(f)

for i in rec:

print(i)

except Exception:

f.close()

Bwrite()

print("Data has been written successfully")

Bupdate()

BRead()
Program No: 09

Program Name: Appending record into a binary file

Aim: To write a Python program to append student records [roll number, name, mark] to a binary file,
by getting data from the user.

Source Code:
import pickle

def BinaryAppend():

Records = []

with open("record.dat", "ab") as File:

while True:

roll_num = int(input("Enter the Roll Number:

")) name = input("Enter the Name: ")

marks = int(input("Enter the Marks: "))

record = [roll_num, name, marks]

Records.append(record)

choice = input("Do you want to continue? y/n: ")

if choice in "NOno" and choice != "":

break

pickle.dump(Records, File)

print("Record Appended Successfully!")

File.close()

def BinaryRead():

try:

with open("record.dat","rb") as File:

while True:

rec=pickle.load(File)
for i in rec:

print(i)

except Exception:

File.close()

BinaryAppend()

#BinaryAppend()

BinaryRead()

Program No: 10

Program Name: Searching in a CSV file

Aim: To create a CSV file by entering the user-id and password, read and search the password for the
given user-id.

Source Code:
import csv

def CSVWrite():

Records = []

while True:

userID = int(input("Enter UserID: "))

password = input("Enter Password: ")

Records.append([userID, password])

choice = input("Do you want to continue? y/n: ")

if choice in "NOno":

break

with open("Imdad.csv", "w", newline = '') as File:

Writer =csv.writer(File)

Writer.writerow(("UserID","Password"))

Writer.writerows(Records)

File.close()

def CSVRead():

with open("Imdad.csv","r") as File:

Records =csv.reader(File)
for details in Records:

print(details)

File.close()

def CSVSearch():

flag=0

search=input("Enter the UserID for the password:")

with open("Imdad.csv","r") as File:

new=csv.reader(File)

for i in new:

if i[0]==search:

print("THe password is:",i[1])

flag=1

break

if flag==0:

print("Record not found")

File.close()

CSVWrite()

CSVRead()

CSVSearch()

Program No: 11

Program Name: Reading CSV file – tab delimiter

Aim: To write a Python program to read a CSV file having a tab delimiter.

Source Code:
import csv

def CSVWrite():

Records = []

while True:

userID = int(input("Enter UserID: "))


password = input("Enter Password: ")

Records.append([userID, password])

choice = input("Do you want to continue? y/n: ")

if choice in "NOno":

break

with open("User.csv", "w", newline = '') as File:

Writer =csv.writer(File,delimiter='\t')

Writer.writerow(("UserID","Password"))

Writer.writerows(Records)

File.close()

def CSVRead():

with open("User.csv","r") as File:

Records = csv.reader(File, delimiter='\t')

for details in Records:

print(details)

CSVWrite()

CSVRead()

Program No: 12

Program Name: Arithmetic Progression using functions

Aim: To write a Python program that generates 4 terms of an AP by providing initial and steps values to
a function that returns the first four terms of the series.

Source Code:
def Arithemetic_Progression( start = 0, terms = 0, step = 1 ):

Progression = []

for term in range( 1, terms + 1 ):

Progression.append(start + (term-1)*step)

return Progression

start = int(input("Enter the Starting Value: "))


terms = int(input("Enter the Total Number of Terms: "))

step = int(input("Enter the Step value: "))

print(Arithemetic_Progression(start,terms,step))

Program No: 13

Program Name: Stack Implementation using Lists

Aim: To write a Python program to implement a stack using a list data structure. (push, pop and peek)

Source Code:
def IsEmpty(stack): # Checks if the given stack is empty or not:

if stack == []:

return True

else:

return False

def Push(stack, item): # Appends a given value on top of the stack:

stack.append(item);TOP = len(stack) - 1

def Pop(stack): # Removes the topmost value in a given stack:

if IsEmpty(stack):

return "Underflow"

else:

item = stack.pop()

if len(stack) == 0:

TOP = None

else:

TOP = len(stack) - 1

return item

def Peek(stack): # Displays the topmost value in a given stack:

if IsEmpty(stack):

return "Underflow"

else:

TOP = len(stack) - 1

return stack[TOP]
def Display(stack):

if IsEmpty(stack):

print("Given Stack is Empty.")

else:

TOP = len(stack) - 1 print("\

t",stack[TOP], "<-= Top") for

value in range(TOP - 1, -1, -1):

print("\t",stack[value])

def StackGUI(Stack = []):

stack = Stack

TOP = None

leave = False

choice = 0

while leave != True:

print("X===={STACK:OPERTATIONS}====X")

print("X X")
print("X 1. Push X")

print("X 2. Pop X")

print("X 3. Peek X")

print("X 4. Display X")

print("X 5. Exit X")


print("X X")

print("X========----------========X\n")

choice = int(input(" Enter your choice: "))

print("\nX========----------========X\n")

if choice == 1:

item = int(input("Enter item (integer): "))

print("\nX========----------========X\n")

Push(stack, item)

elif choice == 2:
item = Pop(stack)

if item == "Underflow":

print("Stack Underflow! The Stack is Empty:")

print("\nX========----------========X\n")

else:

print("Item has been popped:",item)

print("\nX========----------========X\n")

elif choice == 3:

item = Peek(stack)

if item == "Underflow":

print("Stack Underflow! The Stack is Empty:")

print("\nX========----------========X\n")

else:

print("Topmost Item:",item) print("\

nX========--------------------========X\n")

elif choice == 4:

Display(stack)

print("\nX========----------========X\n")

elif choice == 5:

leave = True

else:

print("Choice is Invalid: Try again!")

print("\nX========----------========X\n")

return stack

StackGUI()
Program No: 14

Program Name: Push and pop operations in Dictionary using functions

Aim: To write a Python program to create a dictionary containing names and marks as key value pairs of
5 students. Define two user defined functions to perform the following operations:

i) Push the keys (name of the student) of the dictionary into a stack, where the corresponding value
(marks) is greater than 75.

ii) Pop and display the content of the stack.

Source Code:
def DictPush(stack,name):

stack.append(name)

def DictPop(stack):

if stack!=[]:

return stack.pop()

else:

return None

stu_dict={}

for i in range(5):

keys=input("Enter the Student Name:")

value=int(input("Enter the Mark:"))

stu_dict[keys]=value

print(stu_dict)

stack=[]

for i in stu_dict:

if stu_dict[i]>=75:

DictPush(stack,i)

while True:

if stack!=[]:
print(DictPop(stack),end=" ")

else:

break

Program No: 15

Program Name: Push and pop operations in Lists using functions

Aim: Write a Python program with user defined functions to perform the following operations based on
the list.

A list is having 10 integers.

i) To push the even numbers from the list into a stack.

ii) Pop and display the content of the stack.

Source Code:
import random

def LISTPUSH(stack,element):

stack.append(element)

def LISTPOP(stack):

return stack.pop()

List1=[]

for i in range(11):

List1.append(random.randint(1,100))

print(List1)

stack=[]

for i in List1:

if i%2==0:

LISTPUSH(stack,i)

while True:

if stack!=[]:

print(LISTPOP(stack),end=" ")

else:

break
Program No: 16

Program Name: Interfacing SQL with Python – Connection Establishment

Aim: To Integrate SQL with Python by importing suitable module and display the successful connection
established message.

Source Code:
import mysql.connector as sql

mycon=sql.connect(host='localhost',user='root',passwd='root',database='xii_22_23')

if mycon.is_connected():

print("Connection has been established successfully")

Program No: 17

Program Name: Interfacing SQL with Python – Retrieval of records using fetchone() method

Aim:

To Integrate SQL with Python by importing suitable module and display the records from the table
PLAYER using fetchone().

Source Code:
import mysql.connector as sql

mycon=sql.connect(host='localhost',user='root',passwd='root',database='xii_22_23')

if mycon.is_connected():

print("Connection has been established successfully")

mycur=mycon.cursor()

mycur.execute("select * from player")

data=mycur.fetchone()

for row in data:

print(row,end=" ")
Program No: 18

Program Name: Interfacing SQL with Python – Retrieval of records using fetchall() method

Aim:

To Integrate SQL with Python by importing suitable module and display the records from the table
PLAYER using fetchall().

Source Code:
import mysql.connector as sql

mycon=sql.connect(host='localhost',user='root',passwd='root',database='xii_22_23')

if mycon.is_connected():

print("Connection has been established successfully")

mycur=mycon.cursor()

mycur.execute("select * from student")

data=mycur.fetchall()

for row in data:

print(row)

Program No: 19

Program Name: Interfacing SQL with Python – Deletion of record from the table

Aim:

Integrate SQL with python by importing the suitable module, input player code, and delete the record
from the table PLAYER.

Source Code:
import mysql.connector as sql

mycon=sql.connect(host='localhost',user='root',passwd='root',database='xii_22_23')

if mycon.is_connected():

print("Connection has been established successfully")

mycur=mycon.cursor()

a=int(input("Enter the Player Code to delete"))

sql="delete from student where rollno='%d'"%(a)

data=mycur.execute(sql)

mycon.commit()

mycur.execute("select * from student")

print(mycur.fetchall())
Program No: 20

Program Name: SQL Commands

Aim: To write SQL commands create and insert the data into the table STUDENT and to execute the
query for the problem statement given.

SQL Command:

i) To display the records from table student in alphabetical order as per the name of the student.
SELECT * FROM STUDENT ORDER BY NAME;
ii) To display Class and total number of students who have secured more than 450 marks, class
wise.
SELECT CLASS,COUNT(*) FROM STUDENT WHERE MARKS>450 GROUP BY CLASS ;
iii) To increase marks of all students by 20 whose class is “XII”.
UPDATE STUDENT SET MARKS=MARKS+20 WHERE CLASS="XII";
iv) To display the count and city where number of city is more than 1.
SELECT COUNT(*),CITY FROM STUDENT GROUP BY CITY HAVING COUNT(*)>1;
v) To display maximum and minimum DOB of female students.
SELECT MAX(DOB),MIN(DOB) FROM STUDENT WHERE GENDER='F';
TABLE to be drawn on the left side of the record notebook.

Table : STUDENT

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy