CSCRecord Progs
CSCRecord Progs
PROGRAM DEFINITION:
A menu driven Python code to display n terms of following series using
functions
PROGRAM:
import math
def tarea(b,h):
a = 0.5 * b * h
return a
def carea(r):
a = math.pi * r *r
return a
def rarea(l,b):
a = l*b
return a
while(1):
print(" Menu")
print("1. Area of Triangle")
print("2. Area of Circle")
print("3. Area of Rectangle")
print("4. Exit")
ch = int(input("Enter your choice : "))
if(ch==1):
b = float(input("Enter the base of triangle : "))
h = float(input("Enter the height of triangle : "))
print("The area of triangle : ",tarea(b,h))
elif(ch==2):
r = float(input("Enter the radius of circle : "))
print("The area of circle : ",carea(r))
elif (ch==3):
n= int(input("Enter the length : "))
s = float(input("Enter the breadth : "))
print("The area of the rectangle : ",rarea(n,s))
elif(ch==4):
break
else:
print("Wrong Choice")
OUTPUT:
3. PROGRAM DEFINITION:
A menu driven program in Python using user defined functions to take a string
as input and
• Check if it is palindrome
PROGRAM:
import math
def palindrome(s):
rev = s[::-1]
if(rev == s):
print("The string is palindrome")
else:
print("The string is not a palindrome")
def countc(s,c):
c = s.count(c)
return c
def replacec(s,i):
c = s[i]
nc = input("Enter the character to replace :")
if(len(nc)==1):
ns = s.replace(c,nc)
print(ns)
return ns
else:
print("Enter only one character")
while(1):
print(" Menu")
print("1. Palindrome")
print("2. Number of Occurence")
print("3. Exit")
ch = int(input("Enter your choice:"))
if(ch==1):
s = input("Enter the string :")
palindrome(s)
elif(ch==2):
s = input("Enter the string :")
c = input("Enter a character :")
if(len(c)==1):
print("The character ",c," is in ",s, ",", countc(s,c), " times")
else:
print("Enter only one character")
elif(ch==3):
break
else:
print("Wrong Choice")
OUTPUT:
4. PROGRAM DEFINITION:
A menu driven program in Python using function to
• Display factorial of a number
• Display n terms of Fibonacci series
• Sum of digits of a number
PROGRAM:
def fact(n):
fact=1
for i in range(1,n+1):
fact=fact*i
return fact
def fibo(n):
a=-1
b=1
for i in range(n):
c=a+b
print(c,end=' ')
a,b=b,c
def sumd(n):
sum=0
while n>0:
d = n%10
n=n//10
sum=sum+d
return sum
while(1):
print('''Menu
1. Factorial of a number
2. Fibonacci Series
3. Sum of digits of a number
4. Exit''')
ch=int(input('Enter choice:'))
if (ch==1):
n = int(input("Enter the number : "))
if(n>=0):
print("The factorial of the number is : ",fact(n))
else:
print("The factorial of negative number is not defined")
elif (ch==2):
n = int(input("Enter the number of terms : "))
print("The Fibonacci Series is:")
for i in range(1,n-1):
x = fibo(i)
print(x)
elif (ch==3):
n = int(input("Enter the number : "))
print("The sum of digits is :",sumd(n))
elif (ch==4):
break
else:
print('invalid input')
OUTPUT:
5. PROGRAM DEFINITION:
A menu driven program in Python using function to
• Generate prime numbers
• Generate Armstrong numbers
PROGRAM:
def prime(s,l):
for i in range(s,l):
if i>1:
for j in range(2,i):
if i%j==0:
break
else:
print(i,end=" ")
break
def armstrong(p,q):
for num in range(p,q):
temp=num
sum=0
while temp>0:
digit=temp%10
sum=sum+digit**3
temp=temp//10
if sum==num:
print(num)
while(1):
print('''\nMenu
1. Prime Number
2. Armstrong Number
3. Exit''')
ch=int(input('Enter choice:'))
if (ch==1):
p = int(input("Enter the start value : "))
q= int(input("Enter the stop value : "))
prime(p,q)
elif (ch==2):
p = int(input("Enter the start value : "))
q= int(input("Enter the stop value : "))
armstrong(p,q)
elif (ch==3):
break
else:
print('invalid input')
OUTPUT:
6. PROGRAM DEFINITION:
A menu driven program in Python using function to perform linear and
binary search on a set of numbers
PROGRAM:
OUTPUT:
7. PROGRAM DEFINITION:
A menu driven program in Python using function to a read a text file and
PROGRAM:
def words(file):
cw = 0
ch='1'
while(ch):
ch = file.readline()
wd = ch.split()
cw = cw + len(wd)
print("The number of words are :",cw)
def vowels(file):
cv = 0
ch='1'
while(ch):
ch = file.read(1)
if(ch in ('a','e','i','o','u')):
cv = cv + 1
print("The number of vowels are :",cv)
def lines(file):
cl = 0
ch='1'
while(ch):
ch = file.readline()
cl = cl + 1
print("The number of lines are",cl)
def spcharacter(file):
cs = 0
ch='1'
while(ch):
ch = file.read(1)
if(ch.isalnum()==False):
cs = cs + 1
print("The number of special characters are :",cs)
file = open("read.txt","r")
while(1):
print('''Menu
1. Count number of words
2. Count number of vowels
3. Count number of lines
4. Count number of special characters
5. Exit''')
ch=int(input('Enter choice:'))
if (ch==1):
file.seek(0,0)
words(file)
elif (ch==2):
file.seek(0,0)
vowels(file)
elif (ch==3):
file.seek(0,0)
lines(file)
elif (ch==4):
file.seek(0,0)
spcharacter(file)
elif (ch==5):
break
else:
print('invalid input')
OUTPUT:
8. PROGRAM DEFINITON:
A menu driven program in Python using function to read a text file and
• Display number of times each word appears in the file.
• Display word with maximum and minimum length
PROGRAM:
def words(file):
wdict = {}
ch='1'
while(ch):
ch = file.readline()
wd = ch.split()
for w in wd:
if(w in wdict):
wdict[w] = wdict[w] + 1
else:
wdict[w] = 1
for k,v in wdict.items():
print("The word ",k, "appears ",v, " times")
def mmword(file):
max = 0
min = 100
ch='1'
while(ch):
ch = file.readline()
wd = ch.split()
for w in wd:
if(len(w) > max):
max = len(w)
mxword = w
if(len(w)<min):
min = len(w)
mnword = w
print("The word with maximum length is : ",mxword)
print("The word with minimum length is : ",mnword)
file = open("read.txt","r")
while(1):
print('''Menu
1. Number of occurance of each word
2. Maximum and minimum length word
3. Exit''')
ch=int(input('Enter choice:'))
if (ch==1):
file.seek(0,0)
words(file)
elif (ch==2):
file.seek(0,0)
mmword(file)
elif (ch==3):
break
else:
print('invalid input')
OUTPUT
9. PROGRAM DEFINITION:
A menu driven program in Python using Pickle library and
Create a binary file with following structure
• Admission number
• Student name
• Age
• Display the contents of the binary file
• Search a student by admission number given by user
PROGRAM:
import pickle
def writefile(file):
admno = int(input("Enter the admission number :"))
name = input("Enter the name of student :")
age = int(input("Enter the age of student "))
data = admno,name,age
pickle.dump(data,file)
def readfile(file):
while(1):
try:
data = pickle.load(file)
print(data)
except EOFError :
return
def search(file):
admno = int(input("Enter the admission number :"))
flag = 0
while(1):
try:
data = pickle.load(file)
if(data[0]==admno):
print(data)
flag = 1
return flag
except EOFError :
return flag
file = open("student.dat","ab+")
while(1):
print('''Menu
1. Write binary file
2. Read biary file
3. Search by admission number
4. Exit''')
ch=int(input('Enter choice:'))
if (ch==1):
file.seek(0,0)
writefile(file)
elif (ch==2):
file.seek(0,0)
readfile(file)
elif (ch==3):
file.seek(0,0)
res = search(file)
if(res == 0):
print("Record not found")
elif (ch==4):
break
else:
print('invalid input')
OUTPUT:
10. PROGRAM DEFINITON:
A menu driven program in Python using Pickle library and
• Create binary file with following structure
• Travelid
• From
• To
Append data to the file
Update a record based on travelid
Display all records
PROGRAM:
import pickle
import os
def writefile(file):
trid = int(input("Enter the travel id :"))
froms = input("Enter the starting point :")
to = input("Enter the destination ")
data = trid,froms,to
pickle.dump(data,file)
def readfile(file):
while(1):
try:
data = pickle.load(file)
print(data)
except EOFError :
print("End of file")
return
def upfile(file):
tid = int(input("Enter the travel id to update :"))
flag = 0
found=False
while(1):
try:
pos=file.tell()
data = pickle.load(file)
if(data[0]==tid):
print(data)
flag = 1
nf = input("Enter the new source: ")
nt = input("Enter the new destination")
ndata = tid,nf,nt
file.seek(pos)
pickle.dump(ndata,file)
print("Record updated")
found=True
except EOFError :
break
if found==False:
print("Record not found")
while(1):
print('''Menu
1. Write binary file
2. Update a record
3. Display all records
4. Exit''')
ch=int(input('Enter choice:'))
if (ch==1):
file = open("travel.dat","ab+")
file.seek(0,0)
writefile(file)
file.close()
elif (ch==2):
file = open("travel.dat","rb+")
file.seek(0,0)
upfile(file)
file.close()
elif (ch==3):
file = open("travel.dat","rb")
readfile(file)
file.close()
elif (ch==4):
break
else:
print('invalid input')
OUTPUT:
11. PROGRAM DEFINITION:
A menu driven program in Python to create a CSV file with following data
OUTPUT:
12. PROGRAM DEFINITION:
Take a sample of ten phishing e-mails as a text file and find most
commonly occurring word(s) using a menu driven Python program.
PROGRAM:
def Read_Email_File():
import collections
fin = open('phishing.txt','r')
a= fin.read()
d={ }
L=a.lower().split()
for word in L:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("&","")
word = word.replace("*","")
for k in L:
key=k
if key not in d:
count=L.count(key)
d[key]=count
n_print = int(input("How many most common words to print: "))
print("\nOK. The {} most common words are as follows\
n".format(n_print))
word_counter = collections.Counter(d)
for word, count in word_counter.most_common(n_print):
print(word, ": ", count)
fin.close()
#Driver Code
def main():
Read_Email_File()
main()
OUTPUT
13. PROGRAM DEFINITION:
A program that generates random numbers between 1 and 6 (simulates a
dice).
PROGRAM:
import random
def roll_dice():
print (random.randint(1, 6))
print("""Welcome to my python random dice program!
To start press enter! Whenever you are over, type quit.""")
flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()
OUTPUT
14. PROGRAM DEFINITION:
A python program to implement a stack using a list data structure.
PROGRAM:
def isempty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
returnstk[top]
def display(stk):
if isempty(stk):
print("stack is empty")
else:
for i in range(len(stk)-1,-1,-1):
print(stk[i],end=" ")
stk=[]
top=None
while True:
print('''\nStack operation
1. push
2. pop
3. peek
4. display
5. exit''')
ch=int(input("enter your choice"))
if ch==1:
item=int(input("enter item:"))
push(stk,item)
elif ch==2:
if len(stk)!=0:
item=pop(stk)
print("poped")
else:
print("Stack is underflow")
elif ch==3:
item=peek(stk)
print("top most item is:",item)
elif ch==4:
display(stk)
elif ch==5:
break
OUTPUT:
15. PROGRAM DEFINTION:
A menu driven program in Python to implement a stack using a list data-
structure.
Each node should have
• Book no
• Book name
• Book price
PROGRAM:
s = []
def push():
b_ID=int(input('enter book no.'))
b_NAME=input('enter book name')
b_PRICE=float(input('enter price'))
data=b_ID,b_NAME,b_PRICE
s.append(data)
print("Book added to stack")
def pop():
if len(s)==0:
print('Stack is empty')
else:
dn = s.pop()
print(dn)
def disp():
if len(s)==0:
print('empty stack')
else:
for i in range(len(s)):
print("Book Id :",s[i][0])
print("Book Name :",s[i][1])
print("Book Price :",s[i][2])
while(1):
print('''Menu
1. Push
2. Pop
3. Display
4. Exit''')
ch=int(input('Enter choice:'))
if (ch==1):
push()
elif (ch==2):
pop()
elif(ch==3):
disp()
elif (ch==4):
break
else:
print('invalid input')
`
OUTPUT:
16. PROGRAM DEFINITION:
PROGRAM:
PROGRAM:
def Connection():
Database=conn.connect(host="localhost",user="root",password="s12345",
database="school")
Exe=Database.cursor()
Query="USE school"
Exe.execute(Query)
Query="""CREATE TABLE if not exists Store(Storeid CHAR(5) PRIMARY
KEY,Name VARCHAR(20),Location VARCHAR(20),City VARCHAR(15),NoofEmp
INT(2),Dateofopen DATE,Sales INT)"""
Exe.execute(Query)
Database.commit()
def Inserting():
for i in range(1):
S_id=input("Enter Store id:")
name=input("Enter name:")
location=input("Enter Location:")
city=input("Enter city:")
emps=int(input("Enter no of emps:"))
date=input("Enter date of opening:")
sales=int(input("Enter sales:"))
Database=conn.connect(host="localhost",user="root",password="s12345",
database="school")
Exe=Database.cursor()
Query="USE school"
Exe.execute(Query)
Query="""CREATE TABLE if not exists Store(Storeid CHAR(5) PRIMARY
KEY,Name VARCHAR(20),Location VARCHAR(20),City
VARCHAR(15),NoofEmp
INT(2),Dateofopen DATE,Sales INT)"""
Exe.execute(Query)
Query="INSERT INTO Store values(%s,%s,%s,%s,%s,%s,%s)"
val=(S_id,name,location,city,emps,date,sales)
Exe.execute(Query,val)
Database.commit()
print("Your values are entered!!")
def Display():
Database=conn.connect(host="localhost",user="root",password="s12345",
database="school")
Exe=Database.cursor()
Query="USE school"
Exe=Database.cursor()
Query="SELECT * FROM Store"
Exe.execute(Query)
records=Exe.fetchall()
if records==[]:
print("\nNo records found:(\n")
else:
for i in records:
print(i)
# main
while True:
print("1. Insert 1 records\n2. Display all the records\n3. Exit")
ch=int(input("Enter choice:"))
if ch==1:
Connection()
Inserting()
elif ch==2:
Connection()
Display()
elif ch==3:
sys.exit()
else:
print("Invalid option entered!! Try Again!!")
OUTPUT:
18. PROGRAM DEFINITION:
A menu driven program in Python to establish connection between Python and
MySQL. Perform following operations using the connection using the ‘store’
table created above.
PROGRAM:
def ASC_order():
print("The columns are:\n1. Storeid\n2. Name\n3. Location\n
4.City\n5. NoofEmp\n6. Dateofopen\n7. Sales") col=input("Enter the column
name to be sorted with:")
Database=conn.connect(host="localhost",user="root",password=
"s12345",database="school")
Exe=Database.cursor()
Query="USE school"
Exe=Database.cursor()
Query="SELECT * FROM Store order by "+col+" asc"
Exe.execute(Query,col)
records=Exe.fetchall()
if records==[]:
print("\nNo records found:(\n")
else:
for i in records:
print(i)
def DESC_order():
print("The columns are:\n1. Storeid\n2. Name\n3. Location\n4.
City\n5. NoofEmp\n6. Dateofopen\n7. Sales")
col=input("Enter the column to be sorted with:")
Database=conn.connect(host="localhost",user="root",pa
ssword=
"s12345",database="school")
Exe=Database.cursor()
Query="USE school"
Exe=Database.cursor()
Query="SELECT * FROM Store order by "+col+" desc"
Exe.execute(Query,col)
records=Exe.fetchall()
if records==[]:
print("\nNo records found:(\n")
else:
for i in records:
print(i)
# main
while True:
print("1. Display the records in Ascending order of a column\n2.
Display the records in Descending order of a column\n3. Exit")
ch=int(input("Enter choice:"))
if ch==1:
ASC_order()
elif ch==2:
DESC_order()
elif ch==3:
sys.exit()
else:
print("Invalid option entered!! Try Again!!"
OUTPUT:
19. PROGRAM DEFINITON:
A menu driven program in Python to establish connection between Python and
MySQL. Perform following operations using the connection using the ‘store’
table created above.
PROGRAM:
def S_City():
Database=conn.connect(host="localhost",user="root",password="s12345",
database="school")
Exe=Database.cursor()
Query="USE school"
Exe=Database.cursor()
Query="SELECT City,Count(Name) FROM Store group by City"
Exe.execute(Query)
records=Exe.fetchall()
if records==[]:
print("\nNo records found:(\n")
else:
for i in records:
print(i)
def M_Sales():
Database=conn.connect(host="localhost",user="root",password="s12345",
database="school")
Exe=Database.cursor()
Query="USE school"
Exe=Database.cursor()
Query="SELECT max(Sales) FROM Store where NoofEmp>10"
Exe.execute(Query)
records=Exe.fetchall()
if records==[]:
print("\nNo records found:(\n")
else:
for i in records:
print(i)
#__main__
while True:
print("1. Total no of stores in each city\n2. Max of sales having emp>10\n3. Exit")
ch=int(input("Enter choice:"))
if ch==1:
S_City()
elif ch==2:
M_Sales()
elif ch==3:
sys.exit()
else:
print("Invalid option entered!! Try Again!!")
OUTPUT
20. PROGRAM DEFINITION:
A menu driven program in Python to establish connection between Python and
MySQL. Perform following operations using the connection using the ‘store’
table created above
PROGRAM:
Database=conn.connect(host="localhost",user="root",password="s12345",
database="school")
cursor=Database.cursor()
cursor.execute("select * from STORE")
row = cursor.fetchall()
pos=0
while True:
print("1. First\n2. Next\n3. Previous\n4. Last\n5. Exit")
ch=int(input('Enter choice:'))
if ch==1:
if row==[]:
print("No records:(")
else:
print(row[0])
elif ch==2:
if pos==9:
print("Only 10 records Available:(")
elif row==[]:
print("No records:(")
else:
pos = pos + 1
print(row[pos])
elif ch==3:
if pos==0:
print("No previous records found:(\nThe first record is",row[0])
elif row==[]:
print("No records:(")
else:
pos = pos - 1
print(row[pos])
elif ch==4:
if row==[]:
print("No records:(")
OUTPUT: