0% found this document useful (0 votes)
31 views101 pages

Final Prac File

Here are the steps to solve this problem: 1. Take input from the user and store it in a variable say text 2. Split the text on whitespace to get a list of words using text.split() 3. Count the number of words using len() on the list obtained above 4. Count the total characters in the text using len(text) 5. Count the alphanumeric characters in the text using sum(c.isalnum() for c in text) 6. Calculate percentage of alphanumeric characters as (alphanumeric count/total characters) * 100 7. Print the input text, number of words, total characters, percentage of alphanumeric characters So the complete code would

Uploaded by

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

Final Prac File

Here are the steps to solve this problem: 1. Take input from the user and store it in a variable say text 2. Split the text on whitespace to get a list of words using text.split() 3. Count the number of words using len() on the list obtained above 4. Count the total characters in the text using len(text) 5. Count the alphanumeric characters in the text using sum(c.isalnum() for c in text) 6. Calculate percentage of alphanumeric characters as (alphanumeric count/total characters) * 100 7. Print the input text, number of words, total characters, percentage of alphanumeric characters So the complete code would

Uploaded by

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

SINDHI HIGH SCHOOL, HEBBAL

BANGALORE

COMPUTER SCIENCE
PRACTICAL FILE
2023-24
Name: ARNAV GOYAL
Class: 12A
Registration number:
Page 1 of 101
CERTIFICATE OF COMPLETION

This is to certify that Arnav Goyal of class XII A of Sindhi High School,

Hebbal has satisfactorily completed his Computer Science Practical

File as prescribed by CBSE for AISSCE board practical examination

for the year 2023-24.

Date:

Registration No:

Signature of external examiner:

Signature of internal examiner:

Page 2 of 101
ACKNOWLEDGEMENT

I would like to thank the Principal, Mrs. Rachna Sharma ma’am, my

Computer Science teacher, Lavanya S ma’am for giving me an opportunity to

do the Practical File.

I am grateful for all your help, support and guidance in completing this

practical file successfully on time.

Date :

Place : Bangalore

Page 3 of 101
INDEX

SR.NO CHAPTER NAME PAGE NO.

1. PYTHON REVISION TOUR I 5

2. PYTHON REVISION TOUR II 17

3. WORKING WITH FUNCTIONS 33

4. FILE HANDLING 42

5. DATA STRUCTURES 53

6. DATABASE QUERIES WITH MYSQL 59

7. TABLE CREATION AND DATA MANIPULATION COMANDS 80

8. GROUPING RECORDS, JOINS IN SQL 83

9 PYTHON-MYSQL INTERFACE 91

Page 4 of 101
PYTHON REVISION TOUR – I
Q1) Write a program to print one of the words negative, zero or positive,
according to whether variable x is less than zero, zero or greater than zero,
respectively.

Source Code:
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0: print("Zero")
else: print("Negative number")

Output:

***

Q2) Write a program that returns True if the input number is an even
number, False otherwise.

Source code:
x = int(input(“Enter a number: “))
if x % 2 == 0:
print(“True”) else: print(“False”)

Page 5 of 101
Output:

***

Q3) Write a python program that calculates and prints the number of
seconds in a year.

Source Code:
days = 365
hours = 24
mins = 60
secs = 60
secsInYear = days * hours * mins * secs
print(“Number of seconds in a year =”, secsInYear)

Output:

***

Page 6 of 101
Q4) Write a python program that accepts two integers from the user and
prints a message saying if first number is divisible by second number or if it
is not.

Source Code:
a = int(input(“Enter first number: “))
b = int(input(“Enter second number: “))
if a % b == 0:
print(a, “is divisible by”, b) else: print(a, “is not divisible by”, b)

Output:

***

Q5) Write a program that asks the user the day number in a year in the
range 2 to 365 and asks the first day of the year — Sunday or Monday or
Tuesday etc. Then the program should display the day on the day-number
that has been input.

Source Code:
dayNames = [”MONDAY”, “TUESDAY”, “WEDNESDAY”, “THURSDAY”,
“FRIDAY”, “SATURDAY”, “SUNDAY”] dayNum = int(input(“Enter day
number: “)) firstDay = input(“First day of year: “)
if dayNum < 2 or dayNum > 365:
Page 7 of 101
print(“Invalid Input”) else: startDayIdx =
dayNames.index(str.upper(firstDay))
currDayIdx = dayNum % 7 + startDayIdx - 1
if currDayIdx >= 7:
currDayIdx = currDayIdx - 7
print(“Day on day number”, dayNum, “:”, dayNames[currDayIdx])

Output:

***

Q6) One foot equals 12 inches. Write a function that accepts a length
written in feet as an argument and returns this length written in inches.
Write a second function that asks the user for a number of feet and returns
this value. Write a third function that accepts a number of inches and
displays this to the screen. Use these three functions to write a program
that asks the user for a number of feet and tells them the corresponding
number of inches.

Source Code:
def feetToInches(lenFeet):
lenInch = lenFeet * 12
return lenInch
def getInput():
len = int(input(“Enter length in feet: “))
return len
Page 8 of 101
def displayLength(l):
print(“Length in inches =”, l) ipLen = getInput() inchLen =
feetToInches(ipLen) displayLength(inchLen)

Output:

***

Q7) Write a program that reads an integer N from the keyboard computes
and displays the sum of the numbers from N to (2 * N) if N is nonnegative. If
N is a negative number, then it's the sum of the numbers from (2 * N) to N.
The starting and ending points are included in the sum.

Source Code:

n = int(input("Enter N: ")) sum = 0

if n < 0:

for i in range(2 * n, n + 1):

sum += i

else:

for i in range(n, 2 * n + 1):

sum += i

print("Sum =", sum)


Page 9 of 101
Output:

***

Q8) Write a program that reads a date as an integer in the format


MMDDYYYY. The program will call a function that prints print out the date
in the format <Month Name> <day>, <year>.

Sample run :

Enter date : 12252019

December 25, 2019

Source Code:

months = ["January", "February", "March", "April", "May", "June",

"July", "August", "September", "October", "November", "December"]

dateStr = input("Enter date in MMDDYYYY format: ")

monthIndex = int(dateStr[:2]) - 1

month = months[monthIndex]

day = dateStr[2:4]

Page 10 of 101
year = dateStr[4:]

newDateStr = month + ' ' + day + ', ' + year

print(newDateStr)

Output:

***

Q9) Write a program that prints a table on two columns — table that helps
converting miles into kilometres.

Source Code:

print('Miles | Kilometres')

print(1, "\t", 1.60934)

for i in range(10, 101, 10):

print(i, "\t", i * 1.60934)

Page 11 of 101
Output:

***

Q10) Write another program printing a table with two columns that helps
convert pounds in kilograms.

Source Code:

print('Pounds | Kilograms')

print(1, "\t", 0.4535)

for i in range(10, 101, 10):

print(i, "\t", i * 0.4535)

Page 12 of 101
Output:

***

Q11) Write a program to check whether the given string is palindrome or


not.

Source code:

def ispalindrome(str1):
for i in range(0,int(len(str1)/2)):
if str1[i]!=str1[len(str1)-i-1]:
return False
return True
s=input("Enter string:")
ans=ispalindrome(s)
if (ans):
print("The given string is palindrome")
else:
print("The given string is not a palindrome")

Page 13 of 101
Output:

Q12) Write a program to find Fibonacci series for a given number.

Source code:

First=0
Second=1
num= int(input("How many Fibonacci numbers you want to display? "))
if num<0:
print("Please enter a positive integer")
else:
print(First)
print(Second)
for i in range(2,num):
Third-First+Second
First-Second
Second-Third
print(Third)

Page 14 of 101
Output:

Q13) Write a program that reads two times in military format (0900, 1730)
and prints the number of hours and minutes between the two times.

A sample run is being given below :

Please enter the first time : 0900

Please enter the second time : 1730

8 hours 30 minutes

Source Code:

ft = input("Please enter the first time : ")

st = input("Please enter the second time : ")

# Converts both times to minutes

fMins = int(ft[:2]) * 60 + int(ft[2:])

sMins = int(st[:2]) * 60 + int(st[2:])

# Subtract the minutes, this will give

Page 15 of 101
# th e time duration between the two times

diff = sMins - fMins;

# Convert the difference to hours & mins

hrs = diff // 60

mins = diff % 60

print (hrs, "hours", mins, "minutes")

Output:

***

Page 16 of 101
PYTHON REVISION TOUR – II
Q14) Write a program that prompts for a phone number of 10 digits and two
dashes, with dashes after the area code and the next three numbers. For
example, 017-555-1212 is a legal input. Display if the phone number
entered is valid format or not and display if the phone number is valid or
not (i.e., contains just the digits and dash at specific places.)

Source code:

phNo = input("Enter the phone number: ")

length = len(phNo)

if length == 12 \

and phNo[3] == "-" \

and phNo[7] == "-" \

and phNo[:3].isdigit() \

and phNo[4:7].isdigit() \

and phNo[8:].isdigit() :

print("Valid Phone Number")

else :

print("Invalid Phone Number")

Page 17 of 101
Output:

***

Q15) Write a program that should prompt the user to type some sentence(s)
followed by "enter". It should then print the original sentence(s) and the
following statistics relating to the sentence(s) :

Number of words

Number of characters (including white-space and punctuation)

Percentage of characters that are alphanumeric

Hints: Assume any consecutive sequence of non-blank characters is a word.

Source Code:

str = input("Enter a few sentences: ")

length = len(str)

spaceCount = 0

alnumCount = 0

for ch in str :
Page 18 of 101
if ch.isspace() :

spaceCount += 1

elif ch.isalnum() :

alnumCount += 1

alnumPercent = alnumCount / length * 100

print("Original Sentences:")

print(str)

print("Number of words =", (spaceCount + 1))

print("Number of characters =", (length + 1))

print("Alphanumeric Percentage =", alnumPercent)

Output:

***

Page 19 of 101
Q16) Write a program that takes any two lists L and M of the same size and
adds their elements together to form a new list N whose elements are sums
of the corresponding elements in L and M. For instance, if L = [3, 1, 4] and
M = [1, 5, 9], then N should equal [4,6,13].

Source Code:

print("Enter two lists of same size")

L = eval(input("Enter first list(L): "))

M = eval(input("Enter second list(M): "))

N = []

for i in range(len(L)):

N.append(L[i] + M[i])

print("List N:")

print(N)

Output:

***

Page 20 of 101
Q17) Write a program rotates the elements of a list so that the element at
the first index moves to the second index, the element in the second index
moves to the third index, etc., and the element in the last index moves to
the first index.

Source Code:

l = eval(input("Enter the list: ")) print("Original List")

print(l)

l = l[-1:] + l[:-1]

print("Rotated List")

print(l)

Output:

***

Page 21 of 101
Q18) Write a program to input a line of text and print the biggest word
(length wise) from it.

Source Code:

str = input("Enter a string: ")

words = str.split()

longWord = ''

for w in words :

if len(w) > len(longWord) :

longWord = w

print("Longest Word =", longWord)

Output:

***

Page 22 of 101
Q19) Write a program that creates a list of all integers less then 100 that
are multiples of 3 or 5.

Source Code:

lst = [ ]

for i in range (1,100):

if i % 3 == 0 or i % 5 == 0 :

lst += [ i ]

print (lst)

Output:

***

Page 23 of 101
Q20) Define two variables first and second show that first = "jimmy" and
second = "johny". Write a short python code segment that swaps the values
assigned to these two variable and print the results.

Source Code:

first = "jimmy "

second= "johny"

first , second = second , first

print("first = ", first )

print("second = " , second )

Output:

***

Q21) Write python that create a tuple storing first 9 term of Fibonacci
series.

Source Code:

fib = (0,1,1)

for i in range(6):

fib = fib + ( fib [ i +1] + fib [ i + 2 ] ,)

print(fib)

Page 24 of 101
Output:

***

Q22) To generate random numbers from 1 to 6 using a python program.

Source code:

import random

guess=True

while guess:

n=random.randint(1.6)

userinput=int(input(“Enter a number between 1 to 6”))

if userinput==n:

print(“Congratulations!!You won the game”)

else:

print(“Sorry, try again. The number was:”,n)

val=input(“Do you want to continue to game (y/n):”)

if val==’y’ or val==’Y’:

guess=True

else:

guess=False

Page 25 of 101
Output:

Q23) Write a function called addDict(dict 1,dict 2 ) which computes the


union of to dictionaries. it should return a new dictionary, with all the items
in both its argument. if the same key appear in both arguments, feel free to
pick a value from either.

Source Code:

def adddict(dict1,dict2) :

dic = {}

for i in dict1 :

dic [ i ] = dict1 [i]

for j in dict2 :

dic [ j ] = dict2 [ j ]

return dic

dict1=eval(input("Enter First Dictionary :- "))

dict2=eval(input("Enter Second Dictionary :- "))

print(adddict(dict1,dict2))

Page 26 of 101
Output:

***

Q24) Write a program to sort a dictionary’s keys using bubble sort and
produce the sorted keys as a list.

Source Code:

dic = eval (input("Enter a dictionary : "))

key = list(dic.keys())

for j in range (len(key)):

for i in range ( len ( key ) - 1) :

if key [ i ] > key [ i + 1 ] :

key [ i ] , key [ i + 1 ] = key [ i + 1 ] , key [ i ]

print(key)

Output:

***

Page 27 of 101
Q25) Write a program to sort a dictionary’s value using bubble sort and
produce the sorted values as a list.

Source Code:

dic = eval (input("Enter a dictionary : "))

val = list(dic.values())

for i in range ( len ( val ) - 1 ) :

if val [ i ] > val [ i + 1 ] :

val [ i ] , val [ i + 1 ] = val [ i + 1 ] , val [ i ]

print(val)

Output:

***

Page 28 of 101
Q26) Write a menu drive program to calculate area of different shapes.

Source code:

def circle(r):
Area 3.14*(r**2)
print("The Area of circle is:",Area)
def Rectangle(L,B):
R=L*B
print("The Area of rectangle is:",R)
def Triangle(B,H):
R=0.5*B*H
print("The Area of triangle is:",R)
print("1.Area of circle")
print("2.Area of Rectangle")
print("3.Area of Triangle")
ch=int(input("Enter your choice:"))
if ch==1:
a=float(input("Enter the radius value:"))
circle(a)
elif ch==2:
L=float(input("Enter the length of rectangle:"))
B=float(input("Enter the breath of rectangle:"))
Rectangle(L,B)
elif ch==3:
B=float(input("Enter the Base of Triangle:"))
H=float(input("Enter the Height of Triangle:"))
Triangle(B,H)
else:
print("Invalid option")

Page 29 of 101
Output:

Page 30 of 101
Q27) Write a menu driven program to perform arithmetic operations.

Source code:

print("1.Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4.Division")
opt=int(input("Enter your choice:"}}
a=int(input("Enter the 1st Number:"))
b=int(input("Enter the 2st Number:"))
if opt==1:
c=a+b
print("The Addition of 2 number is:",c)
elif opt==2:
c-a-b
print("The Subtraction of 2 number is:",c)
elif opt==3:
c=a*b
print("The Multiplication of 2 number is:",c)
elif opt==4:
if b==0:
print("Enter any other number other than zero:"}
else:
c=a/b
print("The Division of 2 number is:",c)
else:
print("Invalid option")

Page 31 of 101
Output:

Page 32 of 101
WORKING WITH FUNCTIONS

Q28) Write a function that takes amount-in-dollars and dollar-to-rupee


conversion price ; it then returns the amount converted to rupees. Create
the function in both void and non-void forms.

Source Code:

def rup(doll) : #void


print("(void ) rupees in ",doll ,"dollar = ",doll * 72)

def rupee(doll) : # non Void


return doll * 72

doll = float(input("Enter dollar : "))

rup(doll) #void

print("( non void ) rupees in ",doll ,"dollar = ", rupee(doll) ) # non Void

Output:

***

Page 33 of 101
Q29) Write a function to calculate volume of a box with appropriate default
values for its parameters.
Your function should have the following input parameters:
(a) length of box ;
(b) width of box ;
(c) height of box.
Test it by writing complete program to invoke it.

Source Code:

def vol( l = 1, w = 1 , h = 1 ) :
return l * w * h

length = int(input("Enter the length : "))


width = int(input("Enter the width : "))
height = int(input("Enter the height : "))

print("volume of box = ", vol( length , width , height ))

Output:

***

Page 34 of 101
Q30) Write a program to have following functions :
(i) A function that takes a number as argument and calculates cube for it.
The function does not return a value. If there is no value passed to the
function in function call, the function should calculate cube of 2.
(ii) A function that takes two char arguments and returns True if both the
arguments are equal otherwise False.
Test both these functions by giving appropriate function call statements.

Source Code:

def cube( a = 2 ) :
print( "Cube of ", a ,"=" , a ** 3 )

num = input("Enter a number (For empty press Enter ) :")

if num == "" :
cube()
else :
cube( int (num) )

def chr(char1,char2) :
if char1 == char2 :
return "True"
else:
return"False "

char1 = input("Enter a Char 1 : ")


char2 = input("Enter a Char 2 : ")
print(chr(char1,char2))

Page 35 of 101
Output:

***

Q31) Q. Write a function that receives two numbers and generates a


random number from that range Using this function, the main program
should be able to print three numbers randomly.

Source Code:

import random

def ran(a , b) :
print( random . randint(a , b ) )

first = int(input("Enter a number = "))


second = int(input("Enter second number = "))

ran(first , second )
ran(first , second )
ran(first , second )

Page 36 of 101
Output:

Enter Frist number = 2


Enter Second number = 9
3
9
4

***

Q32) Write a function that receives two string arguments and checks
whether they are same-length strings (returns True in this case otherwise
false).

Source Code:

def chr(a , b) :
print( len(a ) == len(b) )

first = input("Enter First String :-")


second = input("Enter Second String :-")
chr(first , second )

Output:

***

Page 37 of 101
Q33) Write a function namely nthRoot () that receives two parameters x and
n and returns nth root of x i.e., X**1/n . The default value of n is 2.

Source Code:

def root(x , n = 2 ) :
print( x ** (1 / n) )

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


n = int(input("Enter nthRoot (For empty Enter 0 )= "))

if n == 0 :
root( x)

else :
root(x,n)

Output:

***

Page 38 of 101
Q34) Write a function that takes a number n and then returns a randomly
generated number having exactly n digits (not starting with zero)

Source Code:

import random

def ran( x ) :
a = 10 ** (x - 1 )
b= 10 ** (x )
print( random.randint ( a , b ) )

n = int(input("Enter number of digit : "))

ran(n)

Output :-

***

Page 39 of 101
Q35) Write a function that takes two numbers and returns the number that
has minimum one's digit.

Source Code:

def min(x , y ) :
a = x % 10
b = y % 10
if a < b :
return x
else :
return y

first = int(input("Enter first number = "))


second = int(input("Enter second number = "))

print ( "Minimum one's digit number = " , min( first , second ) )

Output:

***

Page 40 of 101
Q36) Write a program that generates a series using a function which takes
first and last values of the series and then generates four terms that are
equidistant e.g., if two numbers passed are 1 and 7 then function returns 1
3 5 7.

Source Code:

def ser( a ,b):


d = int ( ( b - a ) / 3 )
print("Series = " , a , a + d , a + 2*d , b )

first = int(input("Enter first Term = "))


last = int(input("Enter last Term = "))

ser(first , last )

Output:

***

Page 41 of 101
FILE HANDLING
Q37) Write a program that reads a text file and creates another file that is
identical except that every sequence of consecutive blank spaces is replaced
by a single space.

Source Code:

file1 = open("portal.txt","r")
file2 = open("Express.txt","w")
lst = file1.readlines()

for i in lst :
word = i.split()
for j in word :
file2.write( j + " ")
file2.write("\n")

print("Program has successfully run")

file2.close()
file1.close()

Page 42 of 101
Output:

***

Q38) A file sports.dat contains information in following format :


Event ~ Participant
Write a function that would read contents from file sports.dat and creates a
file named Atheletic.dat copying only those records from sports.dat where
the event name is "Athletics".

Source Code:

import pickle
def portal( ) :
file1 = open("sports.dat","rb")
file2 = open("Athletics.dat","wb")
try :
while True :

data = pickle.load( file1 )


word = data.split(" ~ ")

Page 43 of 101
if data [ : 9 ] == "atheletic" or data [ : 9 ] == "Atheletic":
pickle.dump( data, file2 )
except EOFError :
file1.close()
file2.close()
print("Pragram Run Succesfully !!")
portal()

File sports.dat:

File Athletics.dat:

Page 44 of 101
Q39) A file contains a list of telephone numbers in the following form:
Arvind 7258031
Sachin 7259197
The names contain only one word the names and telephone numbers are
separated by white spaces Write program to read a file and display its
contents in two columns.
print("Name\t|\tPhone no. ")

Source Code:

file = open("Ph.txt", "r")


lst = file.readlines()

for i in lst :
data = i.split()
print( data[0] ,end = "\t" )
print("|" , end = "\t")
print ( data[1] )

file.close()

Output:

***
Page 45 of 101
Q40) Write a program to count the words "to" and "the" present in a text file
"Poem.txt".

Source Code:

to_no = 0
the_no = 0

file = open("Poem.txt", "r")


lst = file.readlines()

for i in lst :
word = i.split()
for j in word :
if j == "to" or j == "To" :
to_no += 1
elif j == "the" or j == "The" :
the_no += 1

print("Number 'to' : " , to_no)


print("Number 'the' : " , the_no)

file.close()

Page 46 of 101
Poem.txt contains:

Output:

Page 47 of 101
Q41) A binary file "Book.dat" has structure [BookNo, Book Name, Author,
Price].
(i) Write a user defined function CreateFile() to input data for a record and
add to Book.dat.
(ii) Write a function CountRec(Author) in Python which accepts the Author
name as a parameter and count and return number of books by the given
Author are stored in the binary file "Book.dat".

Source Code:

import pickle

def CreateFile():
f = open("Book.dat", "wb")
while True :
num = int(input("Enter Book Number :- "))
name = input ("Enter Book Name :- ")
aut = input("Enter Author :- ")
pri = float(input("Enter Price of Book :- "))
lst= [ num, name, aut, pri]
pickle.dump( lst, f)
choice = input("For exit (Enter exit):- ")
print()
if choice == "exit" or choice == "Exit":
print("Thank you")
print()
break
f.close()

def CoutRec(aut):
Page 48 of 101
f = open("Book.dat", "rb")
count = 0

try :
while True:
data = pickle.load(f)
if data[2] == aut :
count += 1
except EOFError:
f.close()
print("Number of Book with Author name", aut , "=", count)

CreateFile()
print("For Searching -")

aut = input("Enter Author :- ")


CoutRec(aut)

Output:

Page 49 of 101
Q42) Write a program that counts the number of characters up to the first $
in a text file.

Source Code:

file = open("Ishika.txt","r")

data = file.read()
for i in range( len( data ) ):
if data [ i ] == "$" :
break

print( "Total number of characters up to the first $ before = ",i )

Output:

***

Page 50 of 101
Q43) Write a function that reads a csv file and creates another csv file with
the same content, but with a different delimiter.

Source Code:

import csv

def Copy( file1 ):


file2 = open( "File.csv","w",newline="" )
File_write = csv.writer( file2 , delimiter = ",")

data = csv.reader(file1)

for i in data :
if i[0][:5] != "check" :
File_write.writerow( i )
file2.close()

file1 = open( "Copy.csv","r" )


Copy( file1 )

Page 51 of 101
Q44) Write a Python program to write a nested Python list to a csv file in
one go. After writing the CSV read the CSV file and display the content

Source Code:

import csv

file = open( "Dest.csv","w",newline="" )


lst = eval(input("Enter a nested list :- "))
path_write = csv.writer( file)
path_write.writerows( lst )
file.close()
print()
print("Content of Dest.csv :-")
print()
file = open( "Dest.csv","r" )
data = csv.reader(file ,)
for i in data :
print(i)
file.close()

Output:

***

Page 52 of 101
DATA STRUCTURES [STACKS]

Q45) Write a program that depending upon user's choice, either pushes or
pops an element in a stack.

Source Code:

stack = [ ]
while True :
com = input("Enter ( Push or Pop ) : ")

if com == "push" or com == "Push" :


num = int(input("Enter a number : "))
stack.append(num)

elif len(stack) == 0 :
print("Underflow")

elif com == "pop" or com == "Pop" :


stack.pop()

yes = input ("Enter ( Yes or no ) : ")

if yes == "No" or yes == "no":


print("Thank you !!!!")
break
print(stack)

Page 53 of 101
Output:

***

Q46) Write a function in Python POP(Arr), where Arr is a stack implemented


by a list of numbers. The function returns the value deleted from the stack.

Source Code:

def POP(Arr):

Arr.pop()
return Arr
Stack=[4,5,6,7]
POP(Stack)
print("Now our stack = ",Stack)

Page 54 of 101
Output:

***

Q47) Write a program that depending upon user's choice, either pushes or
pops an element in a stack the elements are shifted towards right so that
top always remains at 0th (zero) index.

Source Code:

stack = [ ]
while True :
com = input("Enter ( Push or Pop ) : ")

if com == "push" or com == "Push" :


num = int(input("Enter a number : "))
stack.insert(0,num)

elif len(stack) == 0 :
print("Underflow")

elif com == "pop" or com == "Pop" :


stack.pop(0)
print("Your Stack :-",stack)

Page 55 of 101
yes = input ("Enter ( Yes or no ) : ")

if yes == "No" or yes == "no":


print("Thank you !!!!")
break

Output:

***

Page 56 of 101
Q48) Write a program that depending upon user's choice, either pushes or
pops an element in a stack the elements are shifted towards right so that
top always remains at 0th (zero) index.

Source Code:
stack = [ ]
while True :
com = input("Enter ( Push or Pop ) : ")

if com == "push" or com == "Push" :


num = int(input("Enter a number : "))
stack.insert(0,num)

elif len(stack) == 0 :
print("Underflow")

elif com == "pop" or com == "Pop" :


stack.pop(0)
print("Your Stack :-",stack)

yes = input ("Enter ( Yes or no ) : ")

if yes == "No" or yes == "no":


print("Thank you !!!!")
break

Page 57 of 101
Output:

***

Page 58 of 101
DATABASE QUERY W/ SQL

Q49) Create a student table with the student id, name, and marks as
attributes where the student id is the primary key.

***

Q50) Insert the details of a new student in the table ‘student’.

***

Page 59 of 101
Q51) Delete the details of a particular student from the table ‘student’
whose name is ‘rahul’.

***

Q52) Use the select query to get the details of the customers from the table
order details.

***

Page 60 of 101
Q53) Find the min, max, sum, and average of the marks from student table.

***

Q54) Use the select query to get the details of the students with marks more
than 80.

***

Page 61 of 101
Q55) Write a SQL query to order (student id, marks) table in descending
order of the marks.

***
Q56) Create a new table (order id, customer name, and order date ) by
joining two tables (order id, customer id , and order date) and (customer id ,
customer name).

***

Page 62 of 101
Q57) Find the total number of customers from the table (customer id,
customer name) using group by clause.

***

Q59) Write a query to display current date on your system.

***

Page 63 of 101
Q60) Write a query to display name of the month for date 01-05-2020

Employee table

***

Page 64 of 101
Q61) Write a SQL query to display the sum of salary of all the employees
present in employee table.

Select SUM (salary) from employee;

***

Q62) Write a SQL query to display the sum of salary of all the employees
present in employee table where the dept = sales

Select SUM (salary) from employee where dept = ‘sales’;

***

Page 65 of 101
Q63) Write a SQL query to display the average of the salary column in
employee table.

Select AVG (salary) from employee

***

Q64) Write a SQL query to display the average of the salary column where
dept = sales

Select AVG (salary) from employee where dept = ‘sales’;

***

Page 66 of 101
Q65) Write a SQL query to display the maximum of the salary column in
employee tables

Select MAX(Salary) from employee;

***

Q66) Write a SQL query to display the maximum of the salary column in the
employee table where dept = sales

Select MAX(salary) from employee where dept= ‘Sales’;

***

Page 67 of 101
Q67) Write a SQL query to display the minimum of the salary column in the
employee table.

Select MIN(Salary) from employee;

***

Q68) Write a SQL query to display the number of rows present in the
employee table.

Select COUNT(*) from employee;

***

Page 68 of 101
Q69) Write a SQL query to display the number of rows present in the salary
column of the employee table.

Select COUNT(salary) from employee;

***

Q70) Write a SQL query to display the details of depid ,sum of salary and
group by depid from emp1

SELECT deptid, SUM(salary) FROM emp1 GROUP BY deptid;

***
Page 69 of 101
Q71) Write a SQL query to display empid, empname, salary from emp1table
and order by empname

SELECT empid, empname, salary FROM emp1 ORDER BY empname DESC;

***

Page 70 of 101
Q72) Write a SQL query to display the details of depid and count of
employees from emp1

SELECTdeptid "Department Code", COUNT(*) "No of Employees" FROM


emp1

***

Q73) Write a SQL query to display the details of depid, count of employees,
sum(salary) from emp1and group by deptid

SELECT deptid "Department Code", COUNT(*) "No of Employees",


SUM(salary) "Total Salary" FROM emp1 GROUP BY deptid;
salary of managerid=103 group by depid

SELECT deptid "Department Code", SUM(salary) "Total Salary" FROM emp1


WHERE managerid = 103 GROUP BY deptid;

***

Page 71 of 101
Q74) Using select show the details of Emp1 table and perform the order by
clause functions

SELECT empid, empname, salary FROM emp1 ORDER BY empname;

***

Page 72 of 101
Q75) Write a SQL query to display the details of depid and count of
employees from emp1 and group by deptid having count(*)>3

SELECT deptid, count(*) "No. of Employee" FROM emp1 GROUP BY deptid


HAVING count(*)>3;

ORDERS TABLES

***

Page 73 of 101
Q76) Write an SQL query to display the names of the customer name
ordered by customer name.

SELECT * FROM orders ORDER BY customer_name;

***

Page 74 of 101
Q77) Write an SQL query to display the dates of the orders ordered by order
date.

SELECT * FROM orders order BY order_date;

***

Q78) Write a SQL command to display city, sum(order_total) ’revenue’ from


orders table and group by city having sum(order_total) >=150

SELECT city, SUM(order_total) ‘revenue’ FROM orders GROUP BY city


HAVING SUM(order_total) >= 150;

***

Page 75 of 101
Q79) Write a SQL command to display city, count(*) ’no_of_orders’ from
orders table and group by city

SELECT city, COUNT(*) 'no_of_orders' FROM orders GROUP BY city;

***

Q80) Write a SQL command to display city, count(*) ’no_of_orders’ from


orders table and group by city having count(*)>1

SELECT city, COUNT(*) 'no_of_orders' FROM orders GROUP BY city having


COUNT(*)>1;

***

Page 76 of 101
Q81) Write a SQL command to display city, sum(order total) ’revenue’ from
orders table and group by city

SELECT city, SUM(order_total) ‘revenue’ FROM orders GROUP BY city;

***
Q82) Write a SQL command to display city, min(order_total),
max(order_total) from orders table and group by city
SELECT city, min(order_total) ,max(order_total) FROM orders GROUP BY
city;

***
Page 77 of 101
Q83) Write a query to convert and display string ‘large’ into uppercase.

***
Q84) Write a query to remove leading and trailing spaces from string ‘Bar
One’

***

Page 78 of 101
Q85) Display names ‘MR. OBAMA’ and ‘MS. Gandhi’ into lowercase

***

Page 79 of 101
SQL database1 :
1. select * from students;

2. desc students

Page 80 of 101
3. Select* from students where stream like ‘commerce’;

4. Select * from student order by avg_marks desc

Page 81 of 101
5. Select name, stream from student where name=’Mohan’;

6. Select * from passenger;

Page 82 of 101
SQL Database 2:

1. desc empl

2. Select* from empl;

Page 83 of 101
3. select empno, ename from empl;

Page 84 of 101
4. select ename, sal,sal+comm from empl;

5. Select ename, sal, deptno from empl where comm is Nul

Page 85 of 101
6. Select empo, ename, sal, sal*12 from empl where comm IS Null;

7. Select deptno from empl;

Page 86 of 101
8. select distinct deptno from empl;

9. select * from empl where job=’Clerk’;

Page 87 of 101
10. Select * from empl where sal*12 between 25000 and 40000

11. select distinct job from empl;

Page 88 of 101
12. select * from empl where comm > sal;

13. select ename, job,sal from empl where mgr IS NULL;

14. select ename from empl where enamelike’%t’;

Page 89 of 101
15. select ename from empl where ename like

Page 90 of 101
PYTHON AND SQL INTERFACE

1. To create a program to integrate MYSQL with python to display


the details of the employees
import mysql.connector as
mysql db1 =
mysql.connect(host="localhost",user="root",passwd="arnav",database

="12A" )

cursor = db1.cursor()

sql = "CREATE TABLE EMPS(empno integer primary key,ename


varchar(25) not null,salary float);"

cursor.execute(sql)

print("Table created successfully")

sql = "INSERT INTO EMPS VALUES(1,'Anil PS',86000),(2,'Anil


PS',86500),(3,'Vicky',90000),(4,'Ram',99000),(5,'Karthick',92000);"

try:

cursor.execute(sql)
db1.commit()
except:

db1.rollback()
db1.close()

Page 91 of 101
Page 92 of 101
2. To create a program to integrate MYSQL with python to display
the details of the employees
import mysql.connector as
mysql db1=
mysql.connect(host="localhost",user="root",passwd='arnav',datab
ase='12A ')

cursor= db1.cursor()
cursor.execute("select * from
emps") print("Data of table emps
displayed") for i in
cursor.fetchmany(3):
print(i)

print("\nTotal records: ",cursor.rowcount())

Page 93 of 101
3. To create a program to integrate MYSQL with python to update
and delete the records in the table

4. WAP TO CHECK THE MYSQLCONNECTION AND DISPLAY


SUCCESS

#CONNECTION CHECK
import sys
import mysql.connector as ms
mycon-ms.connect(host="localhost",user="root",passwd="root",d
atabase="class12")
if mycon.is_connected():
print("success")
mycon.close()

Page 94 of 101
OUTPUT:
Success

5. WAP TO FETCH NO OF ROWS USING FETCHALL

import sys
import mysql.connector as mis
con=ms.connect(host="localhost",user="learner",
passwd="fast",dat
abase="student")
cur con.cursor()
cur.execute("select * from emp')
data=cur.fetchmany(3)
print(data) connection.close()

OUTPUT:
1876: Jack: 12: A: PCMB: [email protected]: 9876567812:
200
1897: Jill: 12: B: PCMB: [email protected]: 8907865343:
200 1857: Sam: 12:8: PCMB: [email protected] :
8907865373:
200

Page 95 of 101
6. WAP TO RETRIVE ALL DATA USING FETCHALL

import sys
import mysql.connector as ms
con=ms.connect(host="localhost",user="root",passwd="root",data
b
ase='class12")
curecon.cursor()
n-intlinput("enter salary:"}]
cur.execute("select * from emp where sal >[sal} and deptno
(deptno)".format(salan,deptno=a)}
data=cur.fetchall()
rec cur.rowcount
if data ! None:
print("data,sep="")
else:
print("no records")

OUTPUT:

enter empo 12
enter dept no 10
(Decimal('7782'), 'clark', 'manager', Decimal(7839"),
datetime.date(1981, 6, 9), Decimal('4450.00'), None,
Decimal('10')): (Decimal(7839'), 'king', 'president', None,
datetime.date(1981, 11, 17), Decimal(7000.00'), None,
Decimal('10'))

Page 96 of 101
7. WAP USING FORMAT FUNCTION

import sys
import mysql.connector as ms
con=ms.connect(host="localhost", user="root",passwd="root",
datab
ase="class12")
cur=con.cursor()
n=int(input("enter empo"))
a=int(input("enter dept no"))
cur.execute("select * from emp where sal >[sal) and deptno
(deptno)".format(salen,deptno=a)}
data=cur.fetchall()
rec cur.rowcount
if data ! None:
print("data,sep=":")
else:
print("no records")

OUTPUT:
enter empo 12
enter dept no 10
(Decimal('7782'), 'clark', 'manager', Decimal('7839"),
datetime.date(1981, 6, 9), Decimal('4450.00'), None,
Decimal('10")): (Decimal(7839'), 'king', 'president', None,
datetime.date(1981, 11, 17), Decimal(7000.00'), None,
Decimal('10'))
Page 97 of 101
8. WAP TO RETRIVE DATA USING STRING TEMPLATE

import sys

import mysql.connector as ms

con=ms.connect(host

ase="class12")

"localhost",user="root",passwd="root", datab

cur=con.cursor()

cur.execute("select from emp where sal>% and

sal<%s %300,4000))

data-cur.fetchall)

for i in data:

print(*)

Page 98 of 101
OUTPUT:

7876 adams clerk 7788 1983-01-12 1100.00 None 20

7499 allen saleman 7698 1981-02-20 1600.00 300.00 30

7698 blake manager 7839 1981-05-01 2850.00 None 30

7902 ford analyst 7566 1981-12-03 3000.00 None 20

7900 james clerk 7698 1981-12-03 950.00 None 30

7566 jones manager 7839 1981-04-02 2975.00 None 20

7654 martin salesman 7698 1981-09-28 1250.00 1400.00 30

7934 miller clerk 7788 1983-01-12 1100.00 None 20

7788 scott analyst 7566 1982-12-09 3000.00 None 20

7369 smith clerk 7902 1980-12-17 800.00 None 20

7844 turner salesman 7698 1981-09-08 1500.00 0.00 30

7521 ward salesman 7698 1981-02-22 1250.00 500.00 30

Page 99 of 101
9. WAP TO INPUT SALARY AND JOB USING FORMAT FUNCTION

import sys
import mysql.connector as ms
con=ms.connect(host "localhost",user="root",passwd="root",
datab
ase="class12")
cur=con.cursor()
cur.execute("select from emp where sal<l) and
job=(.format(2000,"clerk"})
data=cur.fetchall()
for i in data:
print(i)

OUTPUT:

(Decimal('7876'), 'adams', 'clerk, Decimal(7788),


datetime.date(1983, 1, 12), Decimal('1100.00'), None,
Decimal('20'))
(Decimal('7900'), 'james', 'clerk, Decimal(7698'),
datetime.date(1981, 12, 3), Decimal('950.00), None,
Decimal('30'))
(Decimal(7934), 'miller', 'clerk', Decimal(7788'),
datetime.date(1983, 1, 12), Decimal('1100.00'), None,
Decimal('20'))
(Decimal('7369'), 'smith', 'clerk, Decimal("7902"),
datetime.date(1980, 12, 17), Decimal('800.00), None,
Decimal('20'))
Page 100 of 101
10. WAP TO DISPLAY NO OF RETRIVED RECORDS TILL NOW

import sys

Import mysql.connector as ms

conems.connect(host="localhost",user="root",passwd="root",datab

ase="class12")

cur-con.cursor()

cur.execute("select from emp")

data-cur.fetchall()

d-cur.rowcount #this will show the no of rows that ARE


RETREIVED FROM THE TABLE

print(d)

OUTPUT:

SQL QUERIES

14

Page 101 of 101

You might also like