0% found this document useful (0 votes)
52 views36 pages

XII Practical File CS

The document contains a practical file on Python programs and MySQL with 36 problems. It includes problems on checking leap years, printing patterns, finding series sums, checking prime numbers, Fibonacci series, file handling, searching lists, functions, and MySQL connectivity. The problems cover concepts like loops, conditions, functions, files, lists, tuples, and SQL.

Uploaded by

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

XII Practical File CS

The document contains a practical file on Python programs and MySQL with 36 problems. It includes problems on checking leap years, printing patterns, finding series sums, checking prime numbers, Fibonacci series, file handling, searching lists, functions, and MySQL connectivity. The problems cover concepts like loops, conditions, functions, files, lists, tuples, and SQL.

Uploaded by

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

COMPUTER SCIENCE

PRACTICAL FILE

ON

PYTHON PROGRAMS & MYSQL

Submitted to:
Submitted by: Mr. Mahesh Upadhyay

---------------------------------------------

Roll No.-

Page | 1
INDEX

P1. WAP to input a year and check whether the year is leap year or not.
P2. WAP to print the following patterns
1
12
123
1234
12345
P3. WAP to input value of x and n and print the series along with its sum.
P4. WAP to input a number and check whether it is prime number or not.
P5. WAP to print fibonacci series upto n terms, also find sum of series.
P6. WAP to print the given patterns.
*****
****
***
**
*
P7. WAP to print a string and the number of vowels present in it.
P8. Write a program to read a file story.txt and print the contents of file along with
number of vowels present in it.
P9. Write a program to read a file book.txt print the contents of file along with numbers
of words and frequency of word computer in it.
P10 Write a program to read a file Top.txt and print the contents of file along with the
. number of lines starting with A.
P11 WAP to input a list of number and search for a given number using linear search.
.
P12 WAP to input a list of integers and search for a given number using binary search.
.
P13 Write a function DigitSum() that takes a number and returns its digit sum.
.
P14 Write a function Div3and5() that takes a 10 elements numeric tuple and return the
. sum of elements which are divisible by 3 and 5.
P15 Write a recursive function ChkPrime() that checks a number for Prime.
.
P16 Write a function to input a list & arrange the list in ascending order using Bubble
. sort.
P17 Assuming that a text file named first.txt contains some text written into it, write a
. function that reads the file first.txt and creates a new file named second.txt, to
contain only those words from the file first.txt which start with a lowercase vowel
(i.e. with 'a', 'e', 'i', 'o', 'u').
P18 Write a function in Python to count and display number of vowels in text file.
.
P19 Write a method in python to write multiple line of text contents into a text file
. mylife.txt.
P20 Write a function in Phyton to read lines from a text file diary.txt, and display only
. those lines, which are starting with an alphabet 'P'.
P21 Write a method in Python to read lines from a text file INDIA.TXT, to find and
. display the occurrence of the word 'India'.
P22 Program demonstrates how to pickle(serialize) dictionary object and write the
. object into the binary file.
P23 Program demonstrates how to read data from binary file and unpickle it.
.
P24 Pickling and unpickling the list object using file.
.
P25 Write a menu driven program in Python that asks the user to add, display, and
. search records of employee stored in a binary file. The employee record contains
employee code, name and salary. It should be stored in a list object.
P26 Write a menu driven program in Python that asks the user to add, display, and
. search records of students stored in a binary file. The student record contains roll
no, name and test score. It should be stored in a dictionary object.
P27 Reading data from a CSV file into a list.
.
P28 Reading data from a CSV file into a Dictionary.
.
P29 Writing data in CSV File using dictionary
.
P30 Writing data in CSV File using list
.
P31 Write a menu based program to demonstrate operation on a stack.
.
P32 Write a menu based program to demonstrate operations on a queue.
.
P33 Python –MYSQL Connectivity
.
P34 Integrate SQL with Python by importing the MySQL module.
.
P35 Integrate SQL with Python by importing the pymysql module.
.
P36 MySQL Queries.
.

P1. # WAP to input a year and check whether the year is leap year or not

y=int(input("Enter the year: "))


if y%400==0:
print("The year is a Century Leap Year")
elif y%100!=0 and y%4==0:
print("Year is a Leap year")
else:
print("Year is not a leap year")

Enter the year: 2000


The year is a Century Leap Year
P2. # WAP to print the patterns

for i in range(1,6):

for j in range(1,i+1):

print(j,end="")

print()

1
12
123
1234
12345

P3.# WAP to input value of x and n and print the series along with its sum

x=float(input("Enter the value of x"))

n=float(input("Enter the value of n"))

i=1

s=0

while i<n:

y=x**i

print(y, "+", end='')

s=s+y

i+=1

print(x**n) #to print the last element of series

s=s+(x**n) #to add the last element of series

print("Sum of series =", s)

Enter the value of x 4


Enter the value of n 2
4.0 +16.0
Sum of series = 20.0
P4. # WAP to input a number and check whether it is prime number or not

n=int(input("Enter the number"))


c=1
for i in range(2,n):
if n%i==0:
c=0
if c==1:
print("Number is prime")
else:
print("Number is not prime")

Enter the number 29


Number is prime

P5. #WAP to print fibonacci series upto n terms, also find sum of series

n=int(input("Enter the number of terms in fibonacci series"))

a,b=0,1

s=a+b

print(a,b,end=" ")

for i in range(n-2):

print(a+b, end=" ")

a,b=b,a+b

s=s+b

print()

print("Sum of",n,"terms of series =",s)

Enter the number of terms in fibonacci


series10 0112358132134

Sum of 10 terms of series = 88

P6#. program to print pattern


for i in range(5,0,-1):

for j in range(i):

print('*',end="")

print()

*****
****
***
**
*

P7.#WAP to print a string and the number of vowels present in it

st=input("Enter the string")


print("Entered string =",st)
st=st.lower()
c=0
v=['a','e','i','o','u']

for i in st:

if i in v:

c+=1
print("Number of vowels in entered string =",c)

Enter the stringI am a good boi


Entered string = I am a good boi
Number of vowels in entered string = 7
P8. #Write a program to read a file story.txt and print the contents of file along
with number of vowels present in it

f=open("story.txt",'r')
st=f.read()
print("Contents of file :")
print(st)
c=0
v=['a','e','i','o','u']
for i in st:
if i.lower() in v:
c=c+1
print("*****FILE END*****")
print()
print("Number of vowels in the file =",c)

f.close()

Contents of file :
Python is an interpreted, high-level, general-purpose programming language.
Created by Guido van Rossum and first released in 1991.
Python's design philosophy emphasizes code readability.

Its language constructs and object-oriented approach aim to help programmers


write clear, logical code.

*****FILE END*****

Number of vowels in the file = 114


P9. #Write a program to read a file book.txt print the contents of file along with
numbers of words and frequency of word computer in it.

f=open("book.txt","r")

L=f.readlines()

c=c1=0

v=['a','e','i','o','u']

print("Contents of file :")

for i in L:
print(i)
j=i.split()

for k in j:
if k.lower()=="computer":
c1=c1+1
for x in k:
if x .lower() in v:
c+=1
print("*****FILE END*****")

print()

print("Number of vowels in the file =",c)

print("Number of times 'computer' in the file =",c1)

f.close()

Contents of file :
Python is an interpreted, high-level, general-purpose computer programming
language.
Created by Guido van Rossum and first released in 1991.
Python's design philosophy emphasizes code readability.
Its language constructs and object-oriented approach aim to help programmers
write clear, logical code.
*****FILE END*****

Number of vowels in the file = 92

Number of times 'computer' in the file = 1


P10. #Write a program to read a file Top.txt and print the contents of file along
with the number of lines starting with A

f=open("Top.txt","r")
st=f.readlines()
c=0
print("Contents of file :")
for i in st:
print(i)

if i[0]=="A":
c+=1
print("\n*****FILE END*****")

print()

print("Number of lines starting with 'A' =",c)

Contents of file :
Python is an interpreted, high-level, general-purpose programming language.
Created by Guido van Rossum and first released in 1991.
Python's design philosophy emphasizes code readability.
Its language constructs and object-oriented approach aim to help programmers
write clear, logical code.
*****FILE END*****

Number of lines starting with 'A' = 0

P11. #WAP to input a list of number and search for a given number using linear
search

l=eval(input("Enter the list of numbers"))

x=int(input("Enter the number"))


for i in l:
if i==x:
print("ELement present")
break
else:

print("Element not found")

Enter the list of numbers [5,3,4,2,1]


Enter the number 3
Element present
P12. #WAP to input a list of integers and search for a given number using binary search
def bsearch(L,n):

start=0
end=len(L)-1
while start<=end:
mid=(start+end)//2
if L[mid]==n:
return True
elif L[mid]<=n:
start=mid+1
else:
end=mid-1
else:
return False

L=eval(input("Enter the list of numbers"))


n=int(input("Enter the number to find"))
L.sort()
if bsearch(L,n):
print("Element found")
else:
print("Element not found")

Enter the list of numbers[5,3,4,2,1]


Enter the number to find 6
Element not found

P13. #Write a function DigitSum() that takes a number and returns its digit
sum def DigitSum(n):
s=0
n=str(n)
for i in n:
s=s+int(i)
return s
n=int(input("Enter the number"))
print("Sum of digits =",DigitSum(n))

Enter the number69


Sum of digits = 15
P14. #Write a function Div3and5() that takes a 10 elements numeric tuple and return
the sum of elements which are divisible by 3 and 5

def Div3and5(t):
s=0
for i in t:
if i%3==0 and i%5==0:
s=s+i
return s
#main
l=[]
for i in range(10):
print("Enter the ",i+1,"th number of the tuple",end=" ",sep="")
e=int(input())
l.append(e)
t=tuple(l)

print("Entered tuple :",t)


print("Sum of numbers in tuple divisible by 3 and 5 =",Div3and5(t))

Enter the 1th number of the tuple 3


Enter the 2th number of the tuple 2
Enter the 3th number of the tuple 5
Enter the 4th number of the tuple 10
Enter the 5th number of the tuple 15
Enter the 6th number of the tuple 20
Enter the 7th number of the tuple 30
Enter the 8th number of the tuple 2
Enter the 9th number of the tuple 67
Enter the 10th number of the tuple 50
Entered tuple : (3, 2, 5, 10, 15, 20, 30, 2, 67, 50)
Sum of numbers in tuple divisible by 3 and 5 = 45

P15. #Write a recursive function ChkPrime() that checks a number


for Prime def ChkPrime(n,i):

while i<n:
if n%i==0:
return False
else:
i+=1
ChkPrime(n,i)
return True
n=int(input("Enter the number"))
if ChkPrime(n,2):
print("Number is prime")
else:
print("Number ain't prime")

Enter the number 23


Number is prime
P16. #Write a function to input a list and arrange the list in ascending order using
Bubble sort

l=eval(input("Enter the list to arrange"))


for i in range(len(l)-1):
for j in range(len(l)-1):
if l[j]>l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
print("Arranged list :",l)

Enter the list to arrange[5,4,2,3,0,1]


Arranged list : [0, 1, 2, 3, 4, 5]

P17. # Assuming that a text file named first.txt contains some text written into it,
write a function that reads the file first.txt and creates a new file named second.txt, to
contain only those words from the file first.txt which start with a lowercase vowel (i.e.
with 'a', 'e', 'i', 'o', 'u').

For example: if the file first.txt contains Carry umbrella and overcoat when it rains
Then the file second.txt shall contain umbrella and overcoat it.

def copy_file():
infile = open('first.txt','r')
outfile = open('second.txt','w')
for line in infile:
words = line.split()
for word in words:
if word[0] in 'aeiou':
outfile.write(word + ' ')

infile.close()
outfile.close()

# Call the copy_file function.


copy_file()

P18.# Write a function to count and display number of vowels in text file.

def count_vowels():
infile = open('first.txt','r')
count = 0
data = infile.read()
for letter in data:
if letter in 'aeiouAEIOU':
count += 1

print('Number of vowels are',count)


infile.close()
# Call the count_vowels function.
count_vowels()
P19. # Write a method in python to write multiple line of text contents into a text file
mylife.txt.

def writelines():
outfile = open('myfile.txt','w')
while True:
line = input('Enter line: ')
line += '\n'
outfile.write(line)
choice = input('Are there more lines y/n? ')
if choice == 'n':
break
outfile.close()

# Call the writelines function.


writelines()
Output

Enter line: Beautiful is better than ugly.


Are there more lines y/n? y
Enter line: Explicit is better than implicit.
Are there more lines y/n? y
Enter line: Simple is better than complex.
Are there more lines y/n? n
On opening the file myfile.txt the content of file will look like this:

P20. # Write a function in Phyton to read lines from a text file diary.txt, and display
only those lines, which are starting with an alphabet 'P'.

If the contents of file is :


I hope you will please write to me from all the cities you visit.
Please accept them with the love and good wishes of your friend.
He never thought something so simple could please him so much.

The output should be:

Please accept them with the love and good wishes of your friend.
def readlines():
file = open('diary.txt','r')
for line in file:
if line[0] == 'P':
print(line)

file.close()

# Call the readlines function.


readlines()

P21.# Write a method in Python to read lines from a text file INDIA.TXT, to find and
display the occurrence of the word 'India'. For example, if the content of the file is:

India is the fastest-growing economy. India is looking for more investments around the globe. The
whole world is looking at India as a great market. Most of the Indians can foresee the heights that
India is capable of reaching.

The output should be 4.

def count_word():
file = open('india.txt','r')
count = 0

for line in file:


words = line.split()
for word in words:
if word == 'India':
count += 1
print(count)
file.close()

# call the function count_word().


count_word()

Output
4

P22. # Program demonstrates how to pickle(serialize) dictionary object and write the
object into the binary file.

import pickle

phonebook = { 'Deepak':98107593, 'Saksham':92104584, 'John':87989898 }


outfile = open('phonebook.dat', 'wb') #open file in binary mode for writing.
pickle.dump(phonebook, outfile) #serialize the object and writing to file
outfile.close() #close the file
P23.# Program demonstrates how to read data from binary file and unpickle it.

import pickle

infile = open('phonebook.dat', 'rb') #open file in binary mode for reading


phonebook = pickle.load(infile) #reading the oject from file
print(phonebook) #display the phonebook
infile.close() #close the file

Output

{'Deepak': 98107593, 'Saksham': 92104584, 'John': 87989898}

P24.# Pickling and unpickling the list object using file.


import pickle

def write_record():
outfile = open('student.dat','wb') #opening a binary file in write mode
student = [1,'Nisha','XII'] #creating a list object
pickle.dump(student,outfile) #writing to file
outfile.close() #close the file

def read_record():

infile = open('student.dat','rb') #opening the binary file in read mode


student = pickle.load(infile) #read object from file and unpickle
print(student) #display student record
infile.close() #close the file

write_record()
read_record()

Output

[1, 'Nisha', 'XII']

P25.# Write a menu driven program in Python that asks the user to add, display, and
search records of employee stored in a binary file. The employee record contains
employee code, name and salary. It should be stored in a list object. Your program
should pickle the object and save it to a binary file.

import pickle

def set_data():
empcode = int(input('Enter Employee code: '))
name = input('Enter Employee name: ')
salary = int(input('Enter salary: '))
print()
employee = [empcode, name, salary] #create a list
return employee
def display_data(employee):
print('Employee code:', employee[0])
print('Employee name:', employee[1])
print('Salary:', employee[2])
print()

def write_record():
outfile = open('emp.dat', 'ab') #open file in binary mode for writing.
pickle.dump(set_data(), outfile) #serialize the object and writing to file
outfile.close() #close the file

def read_records():
infile = open('emp.dat', 'rb') #open file in binary mode for reading
while True: #read to the end of file.
try:
employee = pickle.load(infile) #reading the oject from file
display_data(employee) #display the object
except EOFError:
break
infile.close() #close the file

def search_record():
infile = open('emp.dat', 'rb')
empcode = int(input('Enter employee code to search: '))
flag = False

while True: #read to the end of file.


try:
employee = pickle.load(infile) #reading the oject from file
if employee[0] == empcode: #display record if found and set flag
display_data(employee)
flag = True
break

except EOFError:
break

if flag == False:
print('Record not Found')
print()

infile.close() #close the file

def show_choices():
print('Menu')
print('1. Add Record')
print('2. Display Records')
print('3. Search a Record')
print('4. Exit')

def main():
while(True):
show_choices()
choice = input('Enter choice(1-4): ')
print()

if choice == '1':
write_record()

elif choice == '2':


read_records()

elif choice == '3':


search_record()

elif choice == '4':


break

else:
print('Invalid input')

#call the main function.


main()

Output
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1

Enter Employee code: 100


Enter Employee name: Deepak
Enter salary: 23000

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1

Enter Employee code: 101


Enter Employee name: Saksham
Enter salary: 98000

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit

Enter choice(1-4): 2

Employee code: 100


Employee name: Deepak
Salary: 23000

Employee code: 101


Employee name: Saksham
Salary: 98000
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit

Enter choice(1-4): 3

Enter employee code to search: 101


Employee code: 101
Employee name: Saksham
Salary: 98000

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 4

P26. # Write a menu driven program in Python that asks the user to add, display, and
search records of students stored in a binary file. The student record contains roll no,
name and test score. It should be stored in a dictionary object. Your program should
pickle the object and save it to a binary file.

import pickle

def set_data():
rollno = int(input('Enter roll number: '))
name = input('Enter name: ')
test_score = int(input('Enter test score: '))
print()

#create a dictionary
student = {}
student['rollno'] = rollno
student['name'] = name
student['test_score'] = test_score
return student

def display_data(student):
print('Roll number:', student['rollno'])
print('Name:', student['name'])
print('Test Score:', student['test_score'])
print()

def write_record():
outfile = open('student.dat', 'ab') #open file in binary mode for writing.
pickle.dump(set_data(), outfile) #serialize the object and writing to file
outfile.close() #close the file

def read_records():
infile = open('student.dat', 'rb') #open file in binary mode for reading
while True: #read to the end of file.
try:
student = pickle.load(infile) #reading the oject from file
display_data(student) #display the object
except EOFError:
break

infile.close() #close the file

def search_record():
infile = open('student.dat', 'rb')
rollno = int(input('Enter rollno to search: '))
flag = False

while True: #read to the end of file.


try:
student = pickle.load(infile) #reading the oject from file
if student['rollno'] == rollno: #display record if found and set flag
display_data(student)
flag = True
break

except EOFError:
break

if flag == False:
print('Record not Found')
print()

infile.close() #close the file

def show_choices():
print('Menu')
print('1. Add Record')
print('2. Display Records')
print('3. Search a Record')
print('4. Exit')

def main():
while(True):
show_choices()
choice = input('Enter choice(1-4): ')
print()
if choice == '1':
write_record()

elif choice == '2':


read_records()

elif choice == '3':


search_record()

elif choice == '4':


break

else:
print('Invalid input')

#call the main function.


main()
Output

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1

Enter roll number: 21


Enter name: Deepak
Enter test score: 78

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1

Enter roll number: 22


Enter name: Saksham
Enter test score: 90

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 2
Roll number: 21
Name: Deepak
Test Score: 78

Roll number: 22
Name: Saksham
Test Score: 90

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice (1-4): 3

Enter rollno to search: 10


Record not Found

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 4

P27.# Reading data from a CSV file into a list.

Country,Played,Won,Lost,Tied,No Result
England,746,375,334,9,28
Australia,949,575,331,9,34
South Africa,625,385,216,6,18
West Indies,822,401,381,10,30
New Zealand,772,351,374,7,40
India,987,513,424,9,41

import csv

file = open("odi.csv")
table = csv.reader(file)
for row in table:
print(row)
file.close()

Output
['Country', 'Played', 'Won', 'Lost', 'Tied', 'No Result']
['England', '746', '375', '334', '9', '28']
['Australia', '949', '575', '331', '9', '34']
['South Africa', '625', '385', '216', '6', '18']
['West Indies', '822', '401', '381', '10', '30']
['New Zealand', '772', '351', '374', '7', '40']
['India', '987', '513', '424', '9', '41']

P28. # Reading data from a CSV file into a Dictionary.

import csv

file = open("odi.csv")
table = csv.DictReader(file)
for row in table:
print(row)

file.close()
Output

{'Country': 'England', 'Played': '746', 'Won': '375', 'Lost': '334', 'Tied': '9', 'No Result': '28'}
{'Country': 'Australia', 'Played': '949', 'Won': '575', 'Lost': '331', 'Tied': '9', 'No Result': '34'}
{'Country': 'South Africa', 'Played': '625', 'Won': '385', 'Lost': '216', 'Tied': '6', 'No Result': '18'}
{'Country': 'West Indies', 'Played': '822', 'Won': '401', 'Lost': '381', 'Tied': '10', 'No Result': '30'}
{'Country': 'New Zealand', 'Played': '772', 'Won': '351', 'Lost': '374', 'Tied': '7', 'No Result': '40'}
{'Country': 'India', 'Played': '987', 'Won': '513', 'Lost': '424', 'Tied': '9', 'No Result': '41'}

P29. # Writing data in CSV File using list

import csv

file = open("odi.csv",'a',newline='')
cwriter = csv.writer(file)

cwriter.writerow(['Pakistan','927','486','413','8','20'])
cwriter.writerow(['Sri Lanka','852','389','421','5','37'])
file.close()

Note: In the above program we used open function to open the file in append mode,
newline=' ' removes blank line between each row.

P30.# Writing data in CSV File using dictionary

import csv

file = open("odi.csv",'a',newline='')
cwriter = csv.DictWriter(file, fieldnames=['Country', 'Played', 'Won', 'Lost', 'Tied', 'No Result'])

cwriter.writerow({'Country': 'Bangladesh', 'Played': '376', 'Won': '128', 'Lost': '241', 'Tied': '0', 'No
Result': '7'})
cwriter.writerow({'Country': 'Afghanistan', 'Played': '126', 'Won': '59', 'Lost': '63', 'Tied': '1', 'No
Result': '3'})

file.close()

P31. #Write a menu based program to demonstrate operation on a stack.

def isEmpty(stk):

if len(stk)==0:
return True
else:
return False
#----------------------------------------------------------------------

def push(stk,n):
stk.append(n)
#----------------------------------------------------------------------

def pop(stk):
if isEmpty(stk):
print("UNDERFLOW CONDITION")
else:
print("Deleted element:",stk.pop())
#----------------------------------------------------------------------
def peek(stk):
return stk[-1]
#----------------------------------------------------------------------

def display(stk):
if isEmpty(stk):
print("No Element Present")
else:
for i in range(-1,-len(stk)-1,-1):
if i==-1:
print("TOP",stk[i])
else:
print(" ",stk[i])
#----------------------------------------------------------------------
#main
stk=[]
while True:
print("Stack operations")
print("1.PUSH")
print("2.POP")
print("3.PEEK")
print("4.DISPLAY STACK")
print("5.EXIT")
ch=int(input("Enter the choice"))

if ch==1:
n=input("Enter the element to PUSH")
push(stk,n)
print("Element pushed")
elif ch==2:
pop(stk)
elif ch==3:
if isEmpty(stk):
print("UNDERFLOW CONDITION")
else:
print(peek(stk))
elif ch==4:
display(stk)
elif ch==5:

break
else:
print("INVALID CHOICE ENTERED")
print("THANKS FOR USING MY SERVICES")
Stack operations
1.PUSH
2.POP
3.PEEK
4.DISPLAY STACK
5.EXIT
Enter the choice1
Enter the element to PUSH98
Element pushed
Stack operations
1.PUSH
2.POP
3.PEEK
4.DISPLAY STACK
5.EXIT
Enter the choice1

Enter the element to PUSH76


Element pushed
Stack operations
1.PUSH
2.POP
3.PEEK
4.DISPLAY STACK
5.EXIT
Enter the element to PUSH89
Element pushed
Stack operations
1.PUSH
2.POP
3.PEEK
4.DISPLAY STACK
5.EXIT
Enter the choice4
TOP 89
76
98
Stack operations
1.PUSH
2.POP
3.PEEK
4.DISPLAY STACK
5.EXIT
Enter the choice2
Enter Deleted element: 89
Stack operations
1.PUSH
2.POP
3.PEEK
4.DISPLAY STACK
5.EXIT
Enter the choice4
TOP 76
98
P32. # Write a menu based program to demonstrate operations on queue
def isEmpty(qu):
if len(qu)==0:
return True
else:
return False
#----------------------------------------------------------------------

def ENQUEUE(qu,item):
qu.append(item)
if len(qu)==1:
rear=front=0
else:
rear=len(qu)-1
front=0
#----------------------------------------------------------------------

def DEQUEUE(qu):
if isEmpty(qu):
print("UNDERFLOW CONDITION")
else:
a= qu.pop(0)
print("ELEMENT DELETED:",a)
#----------------------------------------------------------------------
def peek(stk):
return stk[-1]

def display(qu):
if isEmpty(qu):
print("NO ELEMENT PRESENT")
else:
for i in range(len(qu)):
if i==0:
print("FRONT",qu[i])
elif i==len(qu)-1:
print("REAR ",qu[i])
else:
print(" ",qu[i])
#----------------------------------------------------------------------

#main

qu=[]
while True:
print(“\t\t QUEUE OPERATIONS")
print("\t\t1.ENQUEUE")
print("\t\t2.DEQUEUE")
print("\t\t3.DISPLAY QUEUE")
print("\t\t4.PEEK")
print(“\t\t5.EXIT")
ch=int(input("\t\tEnter your choice: "))
if ch==1:
x=input("Enter the element to be inserted: ")
ENQUEUE(qu,x)
print("ELEMENT HAS BEEN INSERTED")

elif ch==2:
DEQUEUE(qu)
elif ch==3:
display(qu)
elif ch==4:
if isEmpty(qu):
print("UNDERFLOW CONDITION")
else:
print(peek(qu))
elif ch==5:
break
else:
print("INVALID CHOICE ENTERED")
print("THANKS FOR USING MY SERVICES")

QUEUE OPERATIONS
1.ENQUEUE
2.DEQUEUE
3.DISPLAY QUEUE
4.PEEK
5.EXIT
Enter your choice 1

Enter the element to be inserted: Mahesh

ELEMENT HAS BEEN INSERTED


QUEUE OPERATIONS
1.ENQUEUE
2.DEQUEUE
3.DISPLAY QUEUE
4.PEEK
5.EXIT
Enter your choice 1
Enter the element to be inserted: Python

ELEMENT HAS BEEN INSERTED


QUEUE OPERATIONS
1.ENQUEUE
2.DEQUEUE
3.DISPLAY QUEUE
4.PEEK
5.EXIT
Enter your choice 1
Enter the element to be inserted: Selenium
ELEMENT HAS BEEN INSERTED
QUEUE OPERATIONS
1.ENQUEUE
2.DEQUEUE
3.DISPLAY QUEUE
4.PEEK
5.EXIT
Enter your choice 3

FRONT Mahesh
Python
REAR Selenium

QUEUE OPERATIONS
1.ENQUEUE
2.DEQUEUE
3.DISPLAY QUEUE
4.PEEK
5.EXIT
Enter your choice 2

ELEMENT DELETED: Mahesh


QUEUE OPERATIONS
1.ENQUEUE
2.DEQUEUE
3.DISPLAY QUEUE
4.PEEK
5.EXIT
Enter your choice 3

FRONT Python
REAR Selenium
QUEUE OPERATIONS
1.ENQUEUE
2.DEQUEUE
3.DISPLAY QUEUE
4.PEEK
5.EXIT
Enter your choice 5
THANKS FOR USING MY SERVICES

P33. #Python –MYSQL Connectivity

import mysql.connector
#----------------------------------------------------------------------
def insert():
cur.execute("desc {}".format(table_name))
data=cur.fetchall()
full_input=" "
for i in data:
print("NOTE: Please enter string/varchar/date values (if any) in quotes")
print("Enter the",i[0],end=" ")
single_value=input()
full_input=full_input+single_value+","
full_input=full_input.rstrip(",")
cur.execute("Insert into {} values({})".format(table_name,full_input))
mycon.commit()
print("Record successfully inserted")
#----------------------------------------------------------------------
def display():
n=int(input("Enter the number of records to display "))
cur.execute("Select * from {}".format(table_name))
for i in cur.fetchmany(n):
print(i)

#----------------------------------------------------------------------
def search():
find=input("Enter the column name using which you want to find the record ")
print("Enter the",find,"of that record",end=" ")
find_value=input()
cur.execute("select * from {} where {}='{}'".format(table_name,find,find_value))
print(cur.fetchall())

#----------------------------------------------------------------------
def modify():
mod=input("Enter the field name to modify ")
find=input("Enter the column name using which you want to find the record ")
print("Enter the",find,"of that record",end=" ")
find_value=input()
print("Enter the new",mod,end=" ")
mod_value=input()
cur.execute("update {} set {}='{}' where {}='{}'".format(table_name, mod, mod_value, find,
find_value))
mycon.commit()
print("Record sucessfully modified")
#----------------------------------------------------------------------

def delete():
find=input("Enter the column name using which you want to find the record\nNOTE: NO TWO
RECORDS SHOULD HAVE SAME VALUE FOR THIS COLUMN: ")

print("Enter the",find,"of that record",end=" ")


find_value=input()
cur.execute("delete from {} where {}='{}'".format(table_name,find,find_value))
mycon.commit()
print("Record successfully deleted")

#----------------------------------------------------------------------
#__main__
database_name=input("Enter the database ")
my_sql_password=input("Enter the password for MySQL ")
table_name=input("Enter the table name ")
mycon=mysql.connector.connect(host="localhost",user="root",database=database_name,
p asswd=my_sql_password)
cur=mycon.cursor()
if mycon.is_connected():
print("Successfully Connected to Database")
else:
print("Connection Faliled")
while True:
print("\t\t1. Insert Record")
print("\t\t2. Display Record")
print("\t\t3. Search Record")
print("\t\t4. Modify Record")
print("\t\t5. Delete Recod")
print("\t\t6. Exit\n")
ch=int(input("Enter the choice "))
if ch==1:
insert()
elif ch==2:
display()
elif ch==3:
search()
elif ch==4:
modify()
elif ch==5:
delete()
elif ch==6:
mycon.close()
break
else:
print("Invalid choice entered")
Enter the database Mahesh
Enter the password for MySQL aps#1
Enter the table name EMP

Successfully Connected to Database


1. Insert Record
2. Display Record
3. Search Record
4. Modify Record
5. Delete Recod
6. Exit
Enter the choice 1

NOTE: Please enter string/varchar/date values (if any) in quotes Enter the EMPNO 120
NOTE: Please enter string/varchar/date values (if any) in quotes Enter the EMPNAME "Mahesh
Upadhyay"
NOTE: Please enter string/varchar/date values (if any) in quotes Enter the DEPT "Computer"
NOTE: Please enter string/varchar/date values (if any) in quotes Enter the DESIGN "Coder"
NOTE: Please enter string/varchar/date values (if any) in quotes Enter the basic 100000
NOTE: Please enter string/varchar/date values (if any) in quotes Enter the CITY "Nainital"
Record successfully inserted
1. Insert Record
2. Display Record
3. Search Record
4. Modify Record
5. Delete Recod
6. Exit
Enter the choice 2
Enter the number of records to display 10
(111, 'Akash Narang', 'Account', 'Manager', 50000, 'Dehradun')
(112, 'Vijay Duneja', 'Sales', 'Clerk', 21000, 'lucknow')
(113, 'Kunal Bose', 'Computer', 'Programmer', 45000, 'Delhi')
(114, 'Ajay Rathor', 'Account', 'Clerk', 26000, 'Noida')
(115, 'Kiran Kukreja', 'Computer', 'Operator', 30000, 'Dehradun')
(116, 'Piyush Sony', 'Sales', 'Manager', 55000, 'Noida')
(117, 'Makrand Gupta', 'Account', 'Clerk', 16000, 'Delhi')
(118, 'Harish Makhija', 'Computer', 'Programmer', 34000, 'Noida')
(120, 'Mahesh Upadhyay', 'Computer', 'Coder', 100000, 'Nainital')
1. Insert Record
2. Display Record
3. Search Record
4. Modify Record
5. Delete Recod
6. Exit
Enter the choice 3
Enter the column name using which you want to find the record EMPNO Enter the
EMPNO of that record 120
[(120, 'Mahesh Upadhyay', 'Computer', 'Coder', 100000, 'Nainital')]
1. Insert Record
2. Display Record
3. Search Record
4. Modify Record
5. Delete Recod
6. Exit
Enter the choice 4

Enter the field name to modify basic


Enter the column name using which you want to find the record EMPNAME Enter the
EMPNAME of that record Mahesh Upadhyay
Enter the new basic 200000
Record sucessfully modified
1. Insert Record
2. Display Record
3. Search Record
4. Modify Record
5. Delete Recod
6. Exit
Enter the choice 5
Enter the column name using which you want to find the record
NOTE: NO TWO RECORDS SHOULD HAVE SAME VALUE FOR THIS COLUMN: EMPNO
Enter the EMPNO of that record 120
Record successfully deleted

34#: Integrate SQL with Python by importing the MySQL module.


import mysql.connector as sqltor
mycon=sqltor.connect(host="localhost",user="root",passwd="tiger",database="gvkcv")
if mycon.is_connected()==False:
print("error connecting to database")
cursor=mycon.cursor()
cursor.execute("select *from student10")
data=cursor.fetchall()
for i in data:
print(i)
mycon.close()
35#: Integrate SQL with Python by importing the pymysql module.

import pymysql as pym


mycon=sqltor.connect(host="localhost",user="root",passwd="tiger",database="gvkcv"
)
cursor=mycon.cursor()
cursor.execute("select *from student10")
data=cursor.fetchall()
for i in data:
print(i)
mycon.close()

MYSQL QUERIES:

36# Create a student table and insert data. Implement the following SQL commands
on the student table:
 ALTER table to add new attributes / modify data type / drop attribute
 UPDATE table to modify data
 ORDER By to display data in ascending / descending order
 DELETE to remove tuple(s)
 GROUP BY and find the min, max, sum, count and average

#Switched to a database
mysql> USE GVKCV;
Database changed

#Creating table student


mysql> create table student
-> (ROLLNO INT NOT NULL PRIMARY KEY,
-> NAME CHAR(10),
-> TELUGU CHAR(10),
-> HINDI CHAR(10),
-> MATHS CHAR(10));
Query OK, 0 rows affected (1.38 sec)

#Inserting values into table


mysql> insert into student
-> values(101,"student1",50,51,52),
-> (102,"student2",60,61,62),
-> (103,"student3",70,71,72),
-> (104,"student4",80,81,82),
-> (105,"student5",90,91,92),
-> (106,"student6",40,41,42),
-> (107,"student7",63,64,65);
Query OK, 7 rows affected (0.24 sec)
Records: 7 Duplicates: 0 Warnings: 0

#Adding new attribute computers


mysql> alter table student
-> add (computers char(10));
Query OK, 0 rows affected (1.13 sec)
Records: 0 Duplicates: 0 Warnings: 0
#Describing table

mysql> desc student;


+------------+----------+-------+------+---------+-------+
| Field | Type | Null | Key| Default | Extra |
+------------+----------+-------+-----+-----------+-------+
| ROLLNO | int | NO | PRI | NULL | |
| NAME | char(10) | YES | | NULL | |
| TELUGU | char(10) | YES | | NULL | |
| HINDI | char(10) | YES | | NULL | |
| MATHS | char(10) | YES | | NULL | |
| computers| char(10) | YES | | NULL | |
+-----------+----------+------+-----+---------+-------+
6 rows in set (0.21 sec)

#Modifying the datatype

mysql> alter table student


-> modify column computers varchar(10);
Query OK, 7 rows affected (2.38 sec)
Records: 7 Duplicates: 0 Warnings: 0

mysql> desc student;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| ROLLNO | int | NO | PRI | NULL | |
| NAME | char(10) | YES | | NULL | |
| TELUGU | char(10) | YES | | NULL | |
| HINDI | char(10) | YES | | NULL | |
| MATHS | char(10) | YES | | NULL | |
| computers | varchar(10) | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
6 rows in set (0.11 sec)

#Droping a attribute
mysql> alter table student
-> drop column computers;
Query OK, 0 rows affected (0.93 sec)
Records: 0 Duplicates: 0 Warnings: 0

#Describing table
mysql> desc student;
+--------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| ROLLNO | int | NO | PRI | NULL | |
| NAME | char(10) | YES | | NULL | |
| TELUGU | char(10) | YES | | NULL | |
| HINDI | char(10) | YES | | NULL | |
| MATHS | char(10) | YES | | NULL | |
+--------+----------+------+-----+---------+-------+
5 rows in set (0.14 sec)

#UPDATE DATA TO MODIFY DATA


#ACTUAL DATA
mysql> select *from student;
+--------+----------+--------+-------+-------+
| ROLLNO | NAME | TELUGU | HINDI | MATHS |
+--------+----------+--------+-------+-------+
| 101 | student1 | 50 | 51 | 52 |
| 102 | student2 | 60 | 61 | 62 |
| 103 | student3 | 70 | 71 | 72 |
| 104 | student4 | 80 | 81 | 82 |
| 105 | student5 | 90 | 91 | 92 |
| 106 | student6 | 40 | 41 | 42 |
| 107 | student7 | 63 | 64 | 65 |
+--------+----------+--------+-------+-------+
7 rows in set (0.00 sec)

#UPDATE THE MARKS FOR ATTRIBUTE TELUGU FOR THE STUDENT101

mysql> UPDATE STUDENT


-> SET TELUGU=99
-> WHERE ROLLNO=101;
Query OK, 1 row affected (0.12 sec)
Rows matched: 1 Changed: 1 Warnings: 0

#DATA IN THE TABLE AFTER UPDATING


mysql> SELECT *FROM STUDENT;
+--------+----------+--------+-------+-------+
| ROLLNO | NAME | TELUGU | HINDI | MATHS |
+--------+----------+--------+-------+-------+
| 101 | student1 | 99 | 51 | 52 |
| 102 | student2 | 60 | 61 | 62 |
| 103 | student3 | 70 | 71 | 72 |
| 104 | student4 | 80 | 81 | 82 |
| 105 | student5 | 90 | 91 | 92 |
| 106 | student6 | 40 | 41 | 42 |
| 107 | student7 | 63 | 64 | 65 |
+--------+----------+--------+-------+-------+
7 rows in set (0.00 sec)

#ORDER BY DESCENDING ORDER


mysql> SELECT *FROM STUDENT
-> ORDER BY HINDI DESC;
+--------+----------+--------+-------+-------+
| ROLLNO | NAME | TELUGU | HINDI | MATHS |
+--------+----------+--------+-------+-------+
| 105 | student5 | 90 | 91 | 92 |
| 104 | student4 | 80 | 81 | 82 |
| 103 | student3 | 70 | 71 | 72 |
| 107 | student7 | 63 | 64 | 65 |
| 102 | student2 | 60 | 61 | 62 |
| 101 | student1 | 99 | 51 | 52 |
| 106 | student6 | 40 | 41 | 42 |
+--------+----------+--------+-------+-------+
7 rows in set (0.05 sec)

#ORDER BY ASCENDING ORDER


mysql> SELECT *FROM STUDENT
-> ORDER BY HINDI ASC;
+--------+----------+--------+-------+-------+
| ROLLNO | NAME | TELUGU | HINDI | MATHS |
+--------+----------+--------+-------+-------+
| 106 | student6 | 40 | 41 | 42 |
| 101 | student1 | 99 | 51 | 52 |
| 102 | student2 | 60 | 61 | 62 |
| 107 | student7 | 63 | 64 | 65 |
| 103 | student3 | 70 | 71 | 72 |
| 104 | student4 | 80 | 81 | 82 |
| 105 | student5 | 90 | 91 | 92 |
+--------+----------+--------+-------+-------+
7 rows in set (0.00 sec)

#DELETING A TUPLE FROM THE TABLE


mysql> DELETE FROM STUDENT
-> WHERE ROLLNO=101;
Query OK, 1 row affected (0.14 sec)

mysql> SELECT *FROM STUDENT;


+--------+----------+--------+-------+-------+
| ROLLNO | NAME | TELUGU | HINDI | MATHS |
+--------+----------+--------+-------+-------+
| 102 | student2 | 60 | 61 | 62 |
| 103 | student3 | 70 | 71 | 72 |
| 104 | student4 | 80 | 81 | 82 |
| 105 | student5 | 90 | 91 | 92 |
| 106 | student6 | 40 | 41 | 42 |
| 107 | student7 | 63 | 64 | 65 |
+--------+----------+--------+-------+-------+
6 rows in set (0.06 sec)

#ORDER BY BRANCH

#ACTUAL DATA
mysql> SELECT *FROM STUDENT;
+--------+--------+----------+--------+-------+-------+
| ROLL |BRANC |NAME | TELUGU| HINDI|MATHS|
+--------+--------+----------+--------+-------+-------+
| 102 | MPC | student2 | 60 | 61 | 62 |
| 103 | BIPC | student3 | 70 | 71 | 72 |
| 104 | BIPC | student4 | 80 | 81 | 82 |
| 105 | BIPC | student5 | 90 | 91 | 92 |
| 106 | BIPC | student6 | 40 | 41 | 42 |
| 107 | MPC | student7 | 63 | 64 | 65 |
+--------+--------+----------+--------+-------+-------+
6 rows in set (0.00 sec)

mysql> SELECT BRANCH,COUNT(*)


-> FROM STUDENT
-> GROUP BY BRANCH;
+--------+----------+
| BRANCH | COUNT(*) |
+--------+----------+
| MPC | 2|
| BIPC | 4|
+--------+----------+
2 rows in set (0.01 sec)

#e min, max, sum, count and average


mysql> SELECT MIN(TELUGU) "TELUGU MIN MARKS"
-> FROM STUDENT;
+------------------+
| TELUGU MIN MARKS |
+------------------+
| 40 |
+------------------+
1 row in set (0.00 sec)

mysql> SELECT MAX(TELUGU) "TELUGU MAX MARKS"


-> FROM STUDENT;
+------------------+
| TELUGU MAX MARKS |
+------------------+
| 90 |
+------------------+
1 row in set (0.00 sec)

mysql> SELECT SUM(TELUGU) "TELUGU TOTAL MARKS"


-> FROM STUDENT;
+--------------------+
| TELUGU TOTAL MARKS |
+--------------------+
| 403 |
+--------------------+
1 row in set (0.00 sec)

mysql> SELECT COUNT(ROLLNO)


-> FROM STUDENT;
+---------------+
| COUNT(ROLLNO) |
+---------------+
| 6|
+---------------+
1 row in set (0.01 sec)

mysql> SELECT AVG(TELUGU) "TELUGU AVG MARKS"


-> FROM STUDENT;
+-------------------+
| TELUGU AVG MARKS |
+-------------------+
| 67.16666666666667 |
+-------------------+

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