0% found this document useful (0 votes)
15 views17 pages

Practical Q&sol (14-25) 2024

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)
15 views17 pages

Practical Q&sol (14-25) 2024

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/ 17

Q14.

WRITE A PYTHON CODE TO ACCEPT A WORD IN LOWERCASE AND PASS


IT TO A FUNCTION. ARRANGE ALL THE LETTERS OF THE WORD IN THE
ALPHABETICAL ORDER AND DISPLAY THE RESULT

SAMPLE INPUT: computer


SAMPLE OUTPUT: cemoprtu

def Arrange(wd):

p=len(wd) word=''

for i in range(65,91):

for j in range(0,p):

ch=wd[j] if (ch==chr(i)

or ch==chr(i+32)):

word=word+ch

return word #main

program

wd=input("Enter a word in lowercase:")

wd=wd.lower() wd1=Arrange(wd)

print("Dictionary Order:") print(wd1)

Q15. WRITE A PYTHON CODE TO ACCEPT AN INTEGER NUMBER.PASS IT


TO A FUNCTION WHICH RETURNS ITS NUMBER OF FACTORS. FINALLY,
DISPLAY WHETHER THE NUMBER IS A PRIME NUMBER OR NOT def
Prime(n1): c=0 n=n1 for a in range(1, n+1): if(n%a==0):
c=c+1

return c

#main Program

n=int(input("Enter a number:"))

p=Prime(n) if (p==2):

print(n, "is a prime number")

else: print(n, "is not a prime

number")

Q16. Write a Program to count word he and she in a file.


import os

# Function to count word he and she def

CountHeShe():

if os.path.isfile("LIFE.TXT"):

fb = open("LIFE.TXT", 'r')

Ctr = 0
while True:

line = fb.readline() # Read a line

if not line:

break # Encounter EOF

# Line convert into a list

Str = line.rstrip().lower().split() # Words are checked in list

for i in range(len(Str)): if Str[i] == 'he' or Str[i] == 'he.' or Str[i]

== 'she' or Str[i] == 'she.': Ctr += 1 if Ctr > 0:


print("Total words he and she are:", Ctr)

else:

print("No word he and she in file")

else:

print ("File does not exist.")

CountHeShe()

Q17. Program by replacing more than one space by single space.

import os

def ReplaceSpace():

if os.path.isfile("SPACE.TXT"):

File1 = open("SPACE.TXT", 'r')

File2 = open("RSPACE.TXT", 'w')

Ctr = 0

while True:

line = File1.readline() # Read a line


if not line:

break # Encounter EOF

# Line convert into a list

Str = line.rstrip().split()

# Words are written into 'RSPACE.TXT' file with adding a single space instead
of multiple spaces

for i in range(len(Str)):

File2.write(Str[i] + " ")

File2.write("\n") # Write next line

File1.close()

File2.close()
else:

print ("File does not exist.")

ReplaceSpace()

Q18 # Program to perform stack operation on numbers.

Stack = list() # A default stack using list() functon.

Top = -1 # To know the current index position in Stack.

# Adding element into a stack.

def PushNumbers(Stack, Top):

Ch = 'Y'

while Ch == 'Y' or Ch == YES':

Num = int(input("Enter any number: "))


Stack.append(Num) # Adding number into stack.

Top += 1 # It know total number of elements.

print ("Want to add more number...<y/n>: ", end="")

Ch = input().upper()

if Ch == 'N' or Ch == 'NO':

break

return Top

# Removing stack elements. def

PopNumbers(Stack, Top):

Slen = len(Stack) # Finds total elements in the stack.

if Slen <= 0: # Checks if stack is empty or not.

print ("Stack is empty")

else:

Num = Stack.pop() # Removing from top of the stack.


Top = Top - 1

print("Number deleted from stack is", Num)

return Top

# Showing stack elements. def

ShowNumbers(Stack, Top):

Slen = len(Stack) # Finds total elements in the stack.

if Slen <= 0: # Checks if stack is empty or not.

print ("Stack is empty")

else:

print("The stack elements are...")

i = Top

while (i >= 0): # Stack elements process in reverse order.

print(Stack[i])

i -= 1

while (True):

print()
print ('Number Operation')

print ('- - - - - - - - - - - - - - - -')

print ('1. Adding Numbers')

print ('2. Removing Numbers')

print ('3. Showing Numbers')

print ('4. Exit')

Opt = input( "Enter your option: ")

print()

if (Opt == '1') :

# Push operation of stack.


Top = PushNumbers(Stack, Top)

elif (Opt == '2') :

# Pop operation of stack.

Top = PopNumbers(Stack, Top)

elif (Opt == '3') :

ShowNumbers(Stack, Top)

elif (Opt == '4') :

break

Q19.
PROGRAM NO 20:
Consider the following tables product and client. Further answer the questions given below.
Queries

Q.1.
To display the details of those clients whose city is “delhi”

Ans:
Select * from client where city=’Delhi’;

Q.2
To display the details of products whose price is in the range of 50 to 100 Ans:
Select * from product where price between 50 and 100; select
* from product where price>=50 and price<=100;

Q.3
TO DISPLAY THE client name ,city from table client and productname and price from the table
product with their corresponding matching p_id Ans:
Select clientname, city, productname, price from client, product where client.p_id=product.p_id;

Q.4
To increase the price of the product by 10 Ans:
Update product set price=price+10;

Q.5.
Select distinct city from client; Ans:
Delhi
Mumbai
Banglore

PROGRAM NO 21:

Consider the following tables CONSIGNOR and CONSIGNEE. Further answer the questions
given below.

TABLE:CONSIGNOR

CNORID CNORNAME CNORADDRESS CITY


ND01 R SINGHAL 24; ABC ENCLAVE NEW DELHI
ND02 AMIT KUMAR 123; PALM AVENUE NEW DELHI
MU15 R KOHLI 5/A; SOUTH STREET MUMBAI
MU50 S KAUR 27-K; WESTEND MUMBAI
TABLE:CONSIGNEE

CNEEID CNORID CNEENAME CNEEADDRESS CNEECITY


MU05 ND01 RAHUL KISHORE 5; PARK AVENUE MUMBAI
ND08 ND02 P DHINGRA 16/J; MOORE ENCLAVE NEW DELHI
KO19 MU15 A P ROY 2A; CENTRAL AVENUE KOLKATA
MU32 ND02 S MITTAL P 245; AB COLONY MUMBAI
ND48 MU50 B P JAIN 13; BLOCK D; A VIHAR NEW DELHI

Queries

Q1.
To display the names of all the consignors from Mumbai Ans
Select cnorname From consignor Where city=’mumbai’;

Q2.
To display the cneeid,cnorname,cnoradress,cneenmae,cneeaddress for every consignee Ans
Select cneeid,cnoraddress,cneename,cneeaddess From consignor, consignee
Where consignor.cnorid=consignee.cnorid;

Q3.
To display consignee details in ascending order of cneename. Ans
Select * From consignee Order by cneename;

Q4.
To display number of consignee from each city.
Ans
Select cneecity,count(cneecity) From consignee Group by cneecity;

Q5.
Select distinct cneecity from consignee;
Ans
Mumbai
Program 22:
def count_alpha():
lo=0
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if((c>='A' and c<='Z') or (c>='a' and c<='z')):
lo=lo+1
print("total lower case alphabets: “, lo)
#function calling
count_alpha()
Output:

Hello how are you


12123 bye
total lower case alphabets: 17
Program No 23:

Write a python program to read a file named “story.txt”, count and print total
words starting with “a” or “A” in the file?

Solution: def
count_words():
w=0 with
open("Poem.txt") as f:
for line in f:
for word in line.split():
if(word[0]=="a" or word[0]=="A"):
print(word) w=w+1
print("total words starting with 'a' are ",w)
# function calling count_words()

PROGRAM NO:21 Write records of customer into result.csv. The fields are as following:
Field 1 Data Type

StudentID Integer

StudentName String

Score Integer

from csv import writer


def pro4():
#Create Header First
f = open("students.csv","w", newline='\n')
dt = writer(f)
dt.writerow(['Student_ID','StudentName','Score'])
f.close()
#Insert Data
f = open("students.csv","a",newline='\n')
while True:
st_id= int(input("Enter Student ID:"))
st_name = input("Enter Student name:")
st_score = input("Enter score:")
dt = writer(f)
dt.writerow([st_id,st_name,st_score])
ch=input("Want to insert More records?(y or Y):")
ch=ch.lower()
if ch !='y':
break
print("Record has been added.")
f.close()
pro4()

OUTPUT:
PROGRAM 24:

Read a CSV file students.csv and print them with tab delimiter. Ignore first row header to print in
tabular form.

from csv import reader def


pro3(): f =
open("students.csv","r")
dt = reader(f,delimiter=',')
headr_row=next(dt)
data = list(dt)
f.close()
for i in data:
for j in i:
print(j,"\t",end=" ")
print()
pro3()

OUTPUT:
Q25.
The code given below inserts the following record in the table Student:
RollNo – Integer
Name – string
Clas – integer
Marks – integer
Note the following to establish connectivity between Python and MYSQL:
 Username is root
 Password is tiger
 The table exists in a MYSQL database named school.
 The details (RollNo, Name, Clas and Marks) are to be accepted from the user.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the table Student. Statement
3- to add the record permanently in the database
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root", 2+3 11 password="tiger",
database="school")
mycursor=_________________ #Statement 1
rno=int(input("Enter Roll Number :: "))
name=input("Enter name :: ")
clas=int(input("Enter class :: "))
marks=int(input("Enter Marks :: "))
querry="insert into student values({},'{}',{},{})".format(rno, name, clas, marks)
______________________ #Statement 2
______________________ # Statement 3
print("Data Added successfully")

SOLUTION.
Ans:
Statement 1: con1.cursor()
Statement 2: mycursor.execute(querry)
Statement 3: con1.commit()

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