Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
350 views

Practical File

The document contains a summary of coding questions and their solutions in Python. It includes 16 questions covering topics like functions, loops, strings, lists, conditional statements, etc. Each question has sample input/output to demonstrate the code. The questions involve tasks like checking if a number is prime, finding GCD and LCM, checking palindromes, calculating average, etc.

Uploaded by

Vishal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
350 views

Practical File

The document contains a summary of coding questions and their solutions in Python. It includes 16 questions covering topics like functions, loops, strings, lists, conditional statements, etc. Each question has sample input/output to demonstrate the code. The questions involve tasks like checking if a number is prime, finding GCD and LCM, checking palindromes, calculating average, etc.

Uploaded by

Vishal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

ST.

TERES
A
SCHOO
L
2022-2023
Subject
S.T. TERESA
Code: 083
SCHOOLINDEX

S.No. Topic No. of questions

1. Basics of PYTHON-LIST & FUNCTIONSA 30

2. Dictionary 5

3. Tuples 5

4. Structured Query Language for 1 table 3

5. CSV File Handling 4

6. Binary File Handling 4

7. Text File Handling 8

8. Python SQL Connectivity 8

9. SQL for 2 tables 5

10. Stack 5
-Coding-
Basics of PYTHON-LIST & FUNCTIONS
1) Input two numbers and display the larger / smaller number.
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
if a>=b:
print(a, "is larger and", b, "is smaller")
else:
print(b, "is larger and", a, "is smaller")
Output-
Enter the first number:33
Enter the second number:22
33 is larger and 22 is smaller

2) Input three numbers and display the largest / smallest number.


a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
c=int(input("Enter the third number:"))
if a>=b and a>=c:
print(a, "is largest number.")
elif b>=a and b>=c:
print(b, "is largest number.")
else:
print(c, "is largest number.")
if a<b and a<c:
print(a, "is smallest no.")
elif b<a and b<c:
print(b, "is smallest no.")
else:
print(c, "is smallest no.")
Output-
Enter the first number:33
Enter the second number:78
Enter the third number:12
78 is largest number.
12 is smallest no.

3) Generate the following patterns using nested loop.

Pattern-1 Pattern-2 Pattern-3


* 12345 A
** 1234 AB
*** 123 ABC
**** 12 ABCD
***** 1 ABCDE
Pattern-1
for i in range(0,5):
for j in range(0, i+1):
print("*", end="")
print()
Pattern-2
for i in range(1,7):
for j in range(1,i+2):
print(' ',end="\n")
for k in range(1,7-i):
print(k,end="")
print()

Pattern-3
n=6
for i in range(0,n):
a=65
for j in range(0,i):
print(chr(a),end=" ")
a=a+1
print()

4) Write a program to input the value of x and n and print the sum of the series.
o 1+x+x^2+x^3+x^4+. ..........x^n
n=int(input("Enter the limit="))
x=int(input("Enter the value of 'x'="))
s=0
for i in range(n+1):
s+=x**i
print("Sum of series", s)
Output-
Enter the limit=3
Enter the value of 'x'=4
Sum of series 85

o 1-x+x^2-x^3+x^4 .................................x^n
x=int(input("Enter value of x:"))
n=int(input("Enter value of limit:"))
s=0
for a in range(n+1):
if a%2==0:
s+=x**a
else:
s-=x**a
print("Sum of series", s)
Output-
Enter value of x:4
Enter value of limit:7
Sum of series -13107

o x – x^2/2 + x^3/3 – x^4/4 + ............x^n/n


x=int(input("Enter value of x:"))
n=int(input("Enter value of limit:"))
s=0
for a in range(n+1):
if a%2==0:
s+=x**a/n
else:
s-=x**a/n
print("Sum of series", s)
Output-
Enter value of x:5
Enter value of limit:4
Sum of series 130.25

o x + x^2/2!- x^3/3!+ x^4/4! ...................................x^n/n!


x=int(input("Enter value of x:"))
n=int(input("Enter value of n:"))
s=0
a=1
fact=1
for a in range(1,n+1):
fact=fact*a
if a%2==0:
s+=(x**a)/fact
else:
s-=(x**a)/fact
print("Sum of series", s)
Output-
Enter value of x:6
Enter value of n:4
Sum of series 30.0

5) Determine whether a number is a perfect number, an Armstrong number or a palindrome.


def palindrome(n):
temp=n
rev=0
while n>0:
dig=n%10
rev=rev*10+dig
n=n//10
if temp==rev:
print(temp,"-The number is a palindrome.")
else:
print(temp,"-The number isn't a palindrome.")
def armstrong(n):
count=0
temp=n
while temp>0:
digit=temp%10
count+=digit**3
temp//=10
if n==count:
print(n,"is an Armstrong no")
else:
print(n,"is not an Armstrong no")
def perfect(n):
count=0
for i in range(1,n):
if n%i==0:
count=count+i
if count==n:
print(n,"The no is a perfect number.")
else:
print(n,"The no is not a perfect no.")
if __name__=='__main__':
n=int(input("enter number:"))
palindrome(n)
armstrong(n)
perfect(n)
Output-
enter number:8
8 -The number is a palindrome.
8 is not an Armstrong no
8 The no is not a perfect no.

6) Input a number and check if the number is a prime or composite number.


n=int(input("Enter number:"))
fc=0
for i in range(1,n+1):
if n%i==0:
fc+=1
if fc>2:
print("It is a composite no")
else:
print("It is a prime no")
Output-
Enter number:4
It is a composite no
>>>
Enter number:3
It is a prime no

7) Display the terms of a Fibonacci series.


n=int(input("How many terms?"))
n1,n2=0,1
count=0
if n<=0:
print("Please enter a positive integer-")
elif n==1:
print("Fibonacci sequence upto",n,":")
print(n1)
else:
print("Fibonacci sequence:")
while count<n:
print(n1)
nth=n1+n2
n1=n2
n2=nth
count+=1
Output-
How many terms?4
Fibonacci sequence:
0
1
1
2
>>>
How many terms?0
Please enter a positive integer-
>>>
How many terms?1
Fibonacci sequence upto 1:
0
8) Compute the greatest common divisor and least common multiple of two integers.
def find_gcd(x,t):
gcd = 1
for i in range(1,x+1):
if x%i==0 and y%i==0:
gcd = i
return gcd
def compute_gcd(x,y):
while(y):
x,y=y,x%y
return x
def compute_lcm(x,y):
lcm=(x*y)//compute_gcd(x,y)
return lcm
x=int(input("Enter 1st no."))
y=int(input("enter 2nd no."))
print("G.C.D. of given no is", find_gcd(x,y))
print("The L.C.M. is", compute_lcm(x,y))
Output-
Enter 1st no.5
enter 2nd no.10
G.C.D. of given no is 5
The L.C.M. is 10

9) Count and display the number of vowels in a string.


word=input("Enter a string-")
count=0
for letter in word:
if letter in("i","u","a","o","e"):
count=count+1
print("No of vowels:",count)
Output-
Enter a stringpineapple
4
10) Input a string and determine whether it is a palindrome or not; convert the case of characters
in a string.
def isPalindrome(s)
for i in range(0, int(len(s)/2)):
if s[i] != s[len(s)-i-1]:
return False
return True

s=input("Enter a palindrome-")
ans = isPalindrome(s)

if (ans):
print("Yes")
else:
print("No")
print("Palindrome in uppercase-",s.swapcase())
Output-
Enter a palindrome-wew
Yes
Palindrome in uppercase- WEW

11) Given a list with repeated values, define a function (Arr,n) for finding the no. of duplicated
items in the list.
def Execute(Arr,n):
for i in Arr:
if i not in nonduplicate:
nonduplicate.append(i)
elif i not in duplicate:
duplicate.append(i)
else:
moreduplicate.append(i)
return len(duplicate)
n=int(input("Enter a limit"))
nonduplicate=[]
duplicate=[]
moreduplicate=[]
Arr=[]
for i in range(n):
a=int(input("Enter the numbers"))
Arr.append(a)
print(Execute(Arr,n))
Output-
Enter a limit2
Enter the numbers33
Enter the numbers44
0
>>>
Enter a limit5
Enter the numbers55
Enter the numbers66
Enter the numbers55
Enter the numbers77
Enter the numbers88
1

12) Display whether the numbers are even or odd.


num = int(input("Enter any number to test whether it is odd or even:"))
if(num%2)==0:
print("The number is even")
else:
print("The provided number is odd")
Output-
Enter any number to test whether it is odd or even:4
The number is even
Enter any number to test whether it is odd or even:5
The provided number is odd

13) Take 10 integers from user using while loop and print their average value on the screen.
num = int(input('How many numbers: '))
total_sum = 0
for n in range(num):
numbers = float(input('Enter number : '))
total_sum += numbers
avg = total_sum/num
print('Average of ', num, ' numbers is :', avg)
Output-
How many numbers: 4
Enter number : 3
Enter number : 4
Enter number : 5
Enter number : 6
Average of 4 numbers is : 4.5

14) Take 2 number from user and print the sum of all even numbers between them.
m=int(input("Enter the starting no:"))
n=int(input("Enter the ending no:"))
total=0
for num in range(m,n+1):
if(num%2==0):
print(num)
total+=num
print("the sum of even no is",total)
Output-
Enter the starting no:3
Enter the ending no:12
4
6
8
10
12
the sum of even no is 40

15) Write a program that asks the user to enter their name and age. Print a message addressed to
the user that tells the user the year in which they will turn 100 years old.
name = input("Enter your name: ")
current_age = int(input("Enter your age: "))
hundredth_year = 2020 + (100 - current_age)
print(name,"will become 100 years old in the year", hundredth_year)
Output-
Enter your name: NC
Enter your age: 16
NC will become 100 years old in the year 2104

16) Write a program that uses a user defined function that accepts name and gender (as M for
Male, for Female) and prefixes Mr/Ms on the basis of the gender.
def Execute(name, gender):
if gender=='M':
name="Mr"+" "+name
elif gender=="F":
name="Ms"+" "+name
print("Your Name -> ", name)
name=input("Enter Your Name..")
gender=input("Enter Gender..")
Execute(name,gender)
Output-
Enter Your Name..nc
Enter Gender..F
Your Name -> Ms nc

17) Write a program to check the divisibility of a number by that is passed as a parameter to the
user defined function.
def Execute(num):
if num%7==0:
print(num, " is divisible by 7")
else:
print(num," is not divisible by 7")
num=int(input("Enter a number"))
Execute(num)
Output-
Enter a number21
21 is divisible by 7
>>>
Enter a number15
15 is not divisible by 7

18) Write a program that reads a line, then count words and displays how many words are there
in the line.
line=input("Enter line:")
x=line.split()
cnt=0
for i in x:
cnt=cnt+1
print(cnt)
Output-
Enter line:Hi!! I am learning Python.
5
19) Write a program to input a string having some digits and return the sum of digits present in
this string.
a=input("Enter a string with digit:")
c=0
for i in a:
if i.isdigit():
c+=int(i)
print(c)
Output-
Enter a string with digit:I have 2 apples, 3 mangoes
5
20) WAP to find whether the given year is a leap year or not.
year=int(input("Enter 4-digit year"))
if year%100==0:
if(year%400==0):
print("It's a leap year.")
elif(year%4==0):
print("It's a leap year.")
else:
print("It is not a leap year")
Output-
Enter 4-digit year2014
It is not a leap year
>>>
Enter 4-digit year2016
It's a leap year.

21) WAP to convert temperature from Celsius to Fahrenheit.


Celsius=float(input("Enter temperature in Celsius:"))
Fahrenheit=(Celsius*1.8)+32
print(Celsius,"Celsius",Fahrenheit,"Fahrenheit")
Output-
Enter temperature in Celsius:22
22.0 Celsius 71.6 Fahrenheit

22) WAP to accept a number from the user and print the table of that number.
x=int(input("Enter no for which table is required"))
i=1
while i<=10:
print(x,"*",i,"=",x*i)
i+=1
Output-
Enter no for which table is required5
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

23) WAP to accept a decimal number and display its binary number.
n=int(input("Enter no....."))
a=0
m=0
c=0
while n>0:
a=n%2
m=m+(a*c)
c=c*10
n=int(n/2)
print(m)
Output-
Enter no.....56
0
0
0
0
0
0

24) WAP to accept a character and display if it is an uppercase character, lowercase character, digit or
special character.
ch=input("Enter character")
if ch.isupper():
print("Uppercase character")
elif ch.islower():
print("Lowercase character")
elif ch.isdigit():
print("Digit")
else:
print("Special Character")
Output-
Enter characterpythonA33
Special Character
25) WAP to accept name and password from the user and display “You are admin” if name= “admin”
and password= “root”, and display “You are user” and password= “root”. Display “You are Guest” if
name is “guest”, otherwise display “Not a valid user”.
name=input("enter username")
password=input("enter password")
if name=="admin" and password=="root":
print("you are admin")
elif name=="user" and password=="root":
print("you are user")
elif name=="guest":
print("you are guest")
else:
print("not a valid user")
Output-
enter usernameadmin
enter passworddlalda
not a valid user

26) WAP that reads a string and displays the longest substring of the given string.
str1=input("Enter a string")
word=str1.split()
maxlength=0
maxword=" "
for i in word:
x=len(i)
if x>maxlength and i.isalpha()==True:
print(i)
maxlength=x
maxword=i
print("Substring with maximum length is:",maxword)
Output-
Enter a stringThis is a book
This
Substring with maximum length is: This

27) A user defined function trafficLight( ) that accepts input from the user, displays an error
message if the user enters anything other than RED, YELLOW, and GREEN. 
def trafficLight(n):
if n=="RED":
print("STOP, your life is precious.")
elif n=="YELLOW":
print("Please WAIT, till the light is Green")
elif n=="GREEN":
print("GO! Thank you for being patient")
else:
print("INVALID INPUT")
n=input("Enter a value as RED,YELLOW or GREEN")
trafficLight(n)
Output-
Enter a value as RED,YELLOW or GREENGREEN
GO! Thank you for being patient

28) Write a program to read a list of flower names. The program will display the list in descending
order.
Ans. a=int(input(“Enter the limits of no.of flowers:”))
l=[]
for i in range(a):
x=input(“Enter a flower name:”)
l.append(x)
print(l)
l.sort(reverse=True)
print(“List in descending order”, l)
OUTPUT-
Enter the limits of no.of flowers:2
Enter a flower name:Rose
Enter a flower name:Lavender
[‘Rose’, ‘Lavender’]
List in descending order [‘Rose’, ‘Lavender’]

29) Write a Python program that prints all the numbers from 0 to 6 except 3 and 6. Write a Python
program which iterates the integers from 1 to 50. For multiples of three print(“Fizz”) instead of the
number and for the multiples of five print(“Buzz”). For numbers which are multiples of both three and
five print(“FizzBuzz”).
for i in range(51):
if i%3==0:
print(“Fizz”)
elif i%5==0:
print(“Buzz”)
elif i%5==0 and i%3==0:
print(“FizzBuzz”)
Output-
Fizz
Fizz
Buzz
Fizz
Fizz
Buzz
Fizz
Fizz
Fizz
Buzz
Fizz
Fizz
Buzz
Fizz
Fizz
Fizz
Buzz
Fizz
Fizz
Buzz
Fizz
Fizz
Fizz
Buzz

30) Print ‘@’ with number of rows and column to be 5 using nested loop.
for i in range(1,6,1):
for j in range (1,i+1,1):
print(“@”, end= “ ”)
print()
OUTPUT:
@
@@
@@@
@@@@
@@@@@

Dictionary
Q1. Write the code to input any 5 years and the population of any city and print it on the
screen.
def execute():
city=dict()
n=5
i=1
while i<=n:
a=input("enter city name-")
b=input("enter population-")
city[a]=b
i=i+1
print(city)
execute()
Output-
enter city name-Chennai
enter population-7900000
enter city name-Mumbai
enter population-90000000
enter city name-Hyderabad
enter population-8990000
enter city name-Delhi
enter population-12000000
enter city name-Patna
enter population-7899990
{'Chennai': '7900000', 'Mumbai': '90000000', 'Hyderabad': '8990000', 'Delhi': '12000000',
'Patna': '7899990'}
>>>
Q2. WAP to input ‘n’ names and phone numbers to store it in a dictionary and print the
phone number of a particular name.
def store():
phone=dict()
i=1
n=int(input("Enter number of enteries:"))
while i<=n:
a=input("Enter name..")
b=input("Enter phone no...")
phone[a]=b
i+=1
l=phone.keys()
m=input("enter the name to be searched:")
for i in l:
if i==m:
print(m,":phone no is:",phone[i])
break
else:
print(m,"does not exist")
store()
Output-
>>>
=================== RESTART: E:/python file handling/rhgd.py ===================
Enter number of enteries:3
Enter name..ram
Enter phone no...09090898
Enter name..shyam
Enter phone no...76879809
Enter name..jaya
Enter phone no...97800000
enter the name to be searched:jaya
jaya :phone no is: 97800000
Q3. WAP to convert a number entered by the user into its corresponding number in words.
For example, if the input is 985, then the output should be ‘Nine Eight Five’.
def number():
n={0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine'}
num=input("entery any number:")
result=''
for ch in num:
key=int(ch)
value=n[key]
result=result+''+value
print("The number is:", num)
print("The numbername is:",result)
number()
Output-
>>>
=================== RESTART: E:/python file handling/rhgd.py ===================
entery any number:988
The number is: 988
The numbername is: NineEightEight
>>>
Q4. WAP to store students’ info like admission number, roll number, name and marks in a
dictionary and display info on the basis of admission number.
def display():
a=dict()
i=1
b=0
n=int(input("Enter the number of enteries.."))
while i<=n:
adm=input("Enter admission no of a student:")
nm=input("Enter name of the student:")
sec=input("Enter class and section:")
per=float(input("Enter percentage in a student:"))
l=(nm,sec,per)
a[adm]=l
i+=1
f=a.keys()
for i in f:
print("\nAdmno-",i,":")
c=a[i]
print("Name\t","class\t","per\t")
for j in c:
print(j, end="\t")
display()
Output-
=================== RESTART: E:/python file handling/rhgd.py ===================
Enter the number of enteries..2
Enter admission no of a student:3374
Enter name of the student:Ashwini
Enter class and section:7 C
Enter percentage in a student:88
Enter admission no of a student:3375
Enter name of the student:Ancey
Enter class and section:11 A2
Enter percentage in a student:99
Admno- 3374 :
Name class per
Ashwini 7C 88.0
Admno- 3375 :
Name class per
Ancey 11 A2 99.0
Q5. Write a code to create customer’s list with their number & name and delete any
particular customer using his /her number.
def info():
customer=dict()
n=int(input("Enter total number of customers:"))
i=1
while i<=n:
a=input("enter customer name-")
b=input("enter customer number-")
customer[a]=b
i+=1
name=input("Enter customer name to delete:")
del customer[name]
l=customer.keys()
print("Customer Information")
print("Name\t","Number\t")
for i in l:
print(i,'\t',customer[i])
info()
Output-
>>>
=================== RESTART: E:/python file handling/rhgd.py ===================
Enter total number of customers:2
enter customer name-Uri
enter customer number-78
enter customer name-Raju
enter customer number-98
Enter customer name to delete:Uri
Customer Information
Name Number
Raju 98
Tuple
Q1.WAP to store ‘n’ number of subjects in a tuple.
def sub():
t=tuple()
n=int(input("how many subjects you want to add:"))
print("enter all subjects one after another")
for i in range(n):
a=input("Enter the subject")
t+=(a,)
print("output is")
print(t)
sub()
Output-
>>>
=================== RESTART: E:/python file handling/rhgd.py ===================
how many subjects you want to add:2
enter all subjects one after another
Enter the subjectMaths
Enter the subjectScience
output is
('Maths', 'Science')
>>>
Q2. WAP to create a nested tuple to store roll number, name and marks of students.
def nest():
st=((775,'Akshat',56),(324,'Ancey',99),(422,'Yam',87),(300,'Yoshi',90))
print("S_nO","Roll no","name","marks")
for i in range(0,len(st)):
print((i+1),'\t',st[i][0],'\t',st[i][2])
nest()
Output-
>>>
=================== RESTART: E:/python file handling/rhgd.py ===================
S_no Roll no name marks
1 775 56
2 324 99
3 422 87
4 300 90
Q3. WAP to input n numbers form the user, tore these numbers in a tuple and print the
maximum, minimum number along with the sum and mean of all the elements form this
tuple.
def find():
num=tuple()
n=int(input("how many number you want ot enter?"))
for i in range(0,n):
a=int(input("Enter number"))
num+=(a,)
print("\nThe numbers in the tuple are:",num)
print("\nThe maximum number is:",max(num))
print("\nThe minimum number is:",min(num))
print("\nSum of numbers is:",sum(num))
mean=sum(num)/len(num)
print("\nMean of values in the tuple is:",mean)
find()
Output-
how many number you want ot enter?3
Enter number56
Enter number78
Enter number90
The numbers in the tuple are: (56, 78, 90)
The maximum number is: 90
The minimum number is: 56
Sum of numbers is: 224
Mean of values in the tuple is: 74.66666666666667
>>>
Q4. Program to perform linear search on a tuple of numbers.
def perform():
Tuple=(1,2,3,4,5,6)
n=int(input("Enter the element to be searched:"))
flag=False
for i in range(len(Tuple)):
if Tuple[i]==n:
print("Element Found at index",i)
flag=True
if flag==True:
print("Successful Search")
else:
print("Not found")
perform()
Output-
=================== RESTART: E:/python file handling/rhgd.py ===================
Enter the element to be searched:6
Element Found at index 5
Successful Search
>>>
Q5. WAP to input any two tuples and swap their values.
def swap():
t1=tuple()
n=int(input("Total no of values in first tuple:"))
for i in range(n):
a=input("Enter elements")
t1+=(a,)
t2=tuple()
m=int(input("Total no of values in second tuple:"))
for i in range(m):
a=input("Enter elements")
t2+=(a,)
print("First tuple:")
print(t1)
print("Second tuple:")
print(t2)
t1,t2=t2,t1
print("after swapping:")
print("First tuple:")
print(t1)
print("second tuple:")
print(t2)
swap()
Output-
Total no of values in first tuple:5
Enter elements7
Enter elements8
Enter elements4
Enter elements2
Enter elements6
Total no of values in second tuple:3
Enter elements7
Enter elements4
Enter elements1
First tuple:
('7', '8', '4', '2', '6')
Second tuple:
('7', '4', '1')
after swapping:
First tuple:
('7', '4', '1')
second tuple:
('7', '8', '4', '2', '6')

Structured Query Language for One Table


1.

(i) select * from Students;

(ii) select * from Students where Adno=935;

(iii) select count(*) as total_record from Students;


(iv) select count(Adno) as total_record from Students group by Gender;

(v) select * from Students order by Name asc;

2.
1)
1) insert into furniture values(1,'White lotus','Double Bed',23/02/2002,30000,25);
2) select ITEMNAME,DISCOUNT from furniture where PRICE between 5000 and 8000;

3) select ITEMNAME,PRICE+5 from furniture where TYPE='Double Bed' or 'Baby cot';

4) delete from furniture where ITEMNAME like '%e';


5) select * from furniture order by DATEOFSTOCK desc;

3. First Create this table in MySQL.

a. Insert the last record in the table.


insert into employee values(5,'Ben',45,4500,15/03/2015,NULL);
b. Display the records of 30 aged employee whose salary is increasing.
select * from employee where emg_age=30 order by emp_salary asc;
c. You need to delete the last column of the table ‘phone’ containing NULL’s.
alter table employee
drop column phone;

d. Delete the record of Mike and Michale together from the table.
delete from employee where emp_name like'M%e';

e.

Shaun’s age is 3 years more than his original age. Write the code to update that value.
update employee
set emg_age=33
where emp_salary=3500;
CSV File Handling
Q1) Read csv file “COVID” and take 5 records from the user to write in the file.
def create():
import csv
f=open("COVID.csv","a")
k=csv.writer(f,lineterminator='\n')
for i in range(5):
variant=input("Enter COVID variant name")
origin=input("Enter Country from it is originated")
k.writerow([variant,origin])
f.close()
create()
Output-

Q2) Read any file and append the rows by taking values from the user.
def EXECUTE():
import csv
f=open("Book info.csv","a")
a=csv.writer(f)
while True:
     c=input("author name..") 
     b=int(input("price..."))
     a.writerow([c,b])
     n=input("do you want to continue?")
      if n.upper()=='N':
         break
f.close()
EXECUTE()
Output-

Q3) Display the data present in above file.


def EXECUTE():
import csv
f=open("Book info.csv","r")
a=csv.reader(f)
for i in a:
print(i)
f.close()
EXECUTE()
Output-
>>>
['Kushwant', '560']
[]
['Champak', '700']
[]
['Ruskin Bond', '900']
[]
Q4) Read the previous file and display author name whose book’s prices is greater than 600.
def EXECUTE():
import csv
f=open("Book info.csv","r")
k=csv.reader(f)
print("Author","Price")
for i in k:
if i[1]>'600':
print("The author name are=",i[0])
f.close()
EXECUTE()
Output-

Binary File Handling


Q1) Given a binary file “STUDENT.DAT”, containing records of the following type:
[S_Admno, S_Name, Percentage]
Where these three values are:
S_Admno – Admission Number of student (string)
S_Name – Name of student (string)
Percentage – Marks percentage of student (float)
Write a function in PYTHON that would read contents of the file “STUDENT.DAT” and display
the details of those students whose percentage is above 75.
def CREATE():
import pickle
f=open("STUDENT.DAT","ab")
for data in range(3):
S_Admno=input("Admission Number of student-")
S_Name=input("Name of student-")
Percentage=float(input("Marks percentage of student-"))
L=[S_Admno,S_Name,Percentage]
pickle.dump(L,f)
f.close()

def DISPLAY():
import pickle
g=open("STUDENT.DAT","rb")
while True:
try:
a=pickle.load(g)
print(a)
except:
break
g.close()

def EXECUTE():
import pickle
h=open("STUDENT.DAT","rb")
while True:
try:
b=pickle.load(h)
if float(b[2])>75.0:
print("The details of the students whose percent is above 75-")
print("Adm no=",b[0],"Name",b[1],"percentage",b[2])
except:
break
h.close()

print("1.CREATE\ 2.Display\ 3.EXECUTE")


ans=int(input("Enter choice"))
if ans==1:
CREATE()
elif ans==2:
DISPLAY()
elif ans==3:
EXECUTE()
else:
print("No such")
Output-
>>> ==================== RESTART: E:/python file handling/uio.py =============
1.CREATE\ 2.Display\ 3.EXECUTE
Enter choice1
Admission Number of student-3374
Name of student-ABC
Marks percentage of student-56
Admission Number of student-9973
Name of student-XYZ
Marks percentage of student-98
Admission Number of student-8653
Name of student-PQR
Marks percentage of student-89
>>> ==================== RESTART: E:/python file handling/uio.py ============
1.CREATE\ 2.Display\ 3.EXECUTE
Enter choice2
['3374', 'ABC', 56.0]
['9973', 'XYZ', 98.0]
['8653', 'PQR', 89.0]
>>> ==================== RESTART: E:/python file handling/uio.py =============
1.CREATE\ 2.Display\ 3.EXECUTE
Enter choice3
The details of the students whose percent is above 75-
Adm no= 9973 Name XYZ percentage 98.0
The details of the students whose percent is above 75-
Adm no= 8653 Name PQR percentage 89.0
Q2. Assuming the tuple Vehicle as follows:( vehicletype, no_of_wheels)
Where vehicletype is a string and no_of_wheels is an integer.
Write a function showfile() to read all the records present in an already existing binary file
SPEED.DAT and display them on the screen, also count the number of records present in the
file.
def CREATE():
import pickle
f=open("SPEED.DAT","ab")
for data in range(3):
a=input("Vehicel type-")
b=int(input("No of wheels-"))
L=[a,b]
pickle.dump(L,f)
f.close()

def showfile():
import pickle
g=open("SPEED.DAT","rb")
while True:
try:
a=pickle.load(g)
print(a)
line_count=0
if a != "\n":
line_count+=1
print(line_count,"are the no of records")
except:
break
g.close()

print("1.CREATE\ 2.showfile")
ans=int(input("Enter choice"))
if ans==1:
CREATE()
elif ans==2:
showfile()
else:
print("No such")
Output-
>>> ==================== RESTART: E:/python file handling/uio.py ============
1.CREATE\ 2.showfile
Enter choice1
Vehicel type-car
No of wheels-4
Vehicel type-bike
No of wheels-2
Vehicel type-scooter
No of wheels-3
>>> ==================== RESTART: E:/python file handling/uio.py===========
1.CREATE\ 2.showfile
Enter choice2
['car', 4]
['bike', 2]
['scooter', 3]
Q3. Assuming that a binary file VINTAGE.DAT contains records of the following type, write a
function in PYTHON to read the data VINTAGE.DAT and display those vintage vehicles, which
are priced between 200000 and 250000.                                                 
[VNO, VDesc, price]
def CREATE():
import pickle
f=open("VINTAGE.DAT","ab")
for data in range(3):
vno=int(input("vehicle no-"))
vdesc=input("vehicle name-")
price=float(input("Price-"))
L=[vno,vdesc,price]
pickle.dump(L,f)
f.close()

def DISPLAY():
import pickle
g=open("VINTAGE.DAT","rb")
while True:
try:
a=pickle.load(g)
print(a)
except:
break
g.close()

def EXECUTE():
import pickle
h=open("VINTAGE.DAT","rb")
while True:
try:
b=pickle.load(h)
if 200000.0<float(b[2])<250000.0:
print("The details of vintage cars-")
print("Vehicle no=",b[0],"Vehicle Name",b[1],"Price",b[2])
except:
break
h.close()

print("1.CREATE\ 2.Display\ 3.EXECUTE")


ans=int(input("Enter choice"))
if ans==1:
CREATE()
elif ans==2:
DISPLAY()
elif ans==3:
EXECUTE()
else:
print("No such")
Output-
>>> ==================== RESTART: E:/python file handling/uio.py =============
1.CREATE\ 2.Display\ 3.EXECUTE
Enter choice1
vehicle no-3455
vehicle name-Suzu
Price-670000
vehicle no-5699
vehicle name-Hutu
Price-240000
vehicle no-67888
vehicle name-uisi
Price-210000
>>> ==================== RESTART: E:/python file handling/uio.py ============
1.CREATE\ 2.Display\ 3.EXECUTE
Enter choice2
[3455, 'Suzu', 670000.0]
[5699, 'Hutu', 240000.0]
[67888, 'uisi', 210000.0]
>>>==================== RESTART: E:/python file handling/uio.py =============
1.CREATE\ 2.Display\ 3.EXECUTE
Enter choice3
The details of vintage cars-
Vehicle no= 5699 Vehicle Name= Hutu Price= 240000.0
The details of vintage cars-
Vehicle no= 67888 Vehicle Name= uisi Price= 210000.0
Q4. Write a function in PYTHON to search for a laptop from a binary file “LAPTOP.DAT”
containing the records of following type. The user should enter the model number and the
function should display the details of the laptop.                                           
[ModelNo, RAM, HDD, Details]
where ModelNo, RAM, HDD are integers, and Details is a string.
def CREATE():
import pickle
f=open("LAPTOP.DAT","ab")
for data in range(3):
modelno=int(input("model no-"))
RAM=int(input("RAM in GB-"))
HDD=int(input("HDD in GB-"))
details=input("Describe-")
L=[modelno,RAM,HDD,details]
pickle.dump(L,f)
f.close()

def DISPLAY():
import pickle
g=open("LAPTOP.DAT","rb")
while True:
try:
a=pickle.load(g)
print(a)
except:
break
g.close()

def EXECUTE():
import pickle
h=open("LAPTOP.DAT","rb")
try:
while True:
k=pickle.load(h)
a=int(input("enter the model no. you want to search for:"))
if k[0]==a:
print("model no-",k[0],"\nRAM-",k[1],"\nHDD-",k[2],"\ndetails-",k[3])
break
else:
print("Underflow!!,no such entry")
except:
h.close()

print("1.CREATE\ 2.Display\ 3.EXECUTE")


ans=int(input("Enter choice"))
if ans==1:
CREATE()
elif ans==2:
DISPLAY()
elif ans==3:
EXECUTE()
else:
print("No such")
Output-
1.CREATE\ 2.Display\ 3.EXECUTE
Enter choice1
model no-566
RAM in GB-3
HDD in GB-12
Describe-slow
model no-344
RAM in GB-5
HDD in GB-15
Describe-fast
model no-233
RAM in GB-4
HDD in GB-16
Describe-ok ok
>>> ==================== RESTART: E:/python file handling/uio.py ============
1.CREATE\ 2.Display\ 3.EXECUTE
Enter choice2
[566, 3, 12, 'slow']
[344, 5, 15, 'fast']
[233, 4, 16, 'ok ok']
>>>==================== RESTART: E:/python file handling/uio.py =============
1.CREATE\ 2.Display\ 3.EXECUTE
Enter choice3
enter the model no. you want to search for:566
model no- 566
RAM- 3
HDD- 12
details- slow

Text File Handling


Q1) Read a file of your name and edit the file using codes. 
def Create():
f=open("NC.txt", "a")
a=input("Enter a line ")
f.write(a)
f.close()
Create()
Output-

Q2) Read a file of your name and append some flower names to the file. 
def APPEND():
with open("NC,,.txt", "a") as f:
     a=input("Enter some flower names")
     f.write(a)
APPEND()
Output-
Q3) Read a file and display how many lines are there.
def Display():
f=open("Stud.txt")
a=f.readlines()
c=len(a)
print("Total no of lines in FILE -> ", c)
f.close()
Display()
Output-

Q4) Read a file "Damm.txt" and display those lines starting with the letter 'a'.  
def Show():
f=open("Damm.txt","r")
for i in f.readlines():
     if i[0]=='a':
         print(i)
f.close()
Show()
Output-
Q5) Read a file “Damm.txt” and display the total number of lines in the file.
def execute():
f=open("Damm.txt","r")
print("Total no of lines is....", len(f.readlines()))
f.close()
execute()
Output-

Q6) Read a file "Damm.txt" and display those lines starting with the letter 'e'.
def Show():
f=open("Damm.txt","r")
for i in f.readlines():
if i[0]=='e':
print(i)
f.close()
Show()
Output-

Q7) Read a file of your name and display total no of words in file. 
def DISPLAY():
f=open("NC.txt")
a=f.read()
b=a.split()
c=len(b)
print("Total no of words in FILE -> ", c)
f.close()
DISPLAY()
*(One line CODE)
def DISPLAY():
f=open("NC.txt")
f.seek(0)
print("Total no of words in FILE -> ", len(f.read().split()))
f.close()
DISPLAY()
Output-
Content in file- “Hi, this is Ancey Verma, nice to meet you”.
>>> ==================== RESTART: E:/python file handling/jj.py ==============
Total no of words in FILE -> 9
Q8) Read a file “Damm.txt” and display the no. of times “the” is present in the file.
def COUNT():
with open ("Damm.txt") as f:
print("no of times -the- there....", f.read().split().count("the"))
COUNT()
Output-

Python SQL Connectivity


Q1) Write A Program to Find the Names of the student with repeated roll no.s with the
following table “Student” and database “Records”:
RNo Sname Adm_no
1 Marlo 6577
2 Rambo 5655
3 Hikari 2467
4 Utsu 9403
def T2():
import mysql.connector as m
a=m.connect(host="localhost",user="root",passwd="admin",database="Records")
b=a.cursor()
b.execute("select* from Student")
roll_no=[]
o=[]
t=[]
for i in b:
if i[0] not in roll_no:
roll_no.append(i[0])
o.append(i)
elif i[0] in roll_no:
t.append(i)
for j in o:
if j[0]==i[0]:
t.append(j)
print(t)
T2()
Output:
Q2) Write a Program using Python Sql connectivity to retrieve only those items from Item
whose Name starts with E and print only three of those records by using fetch() function.
def AV():
import mysql.connector as m
x=m.connect(host="localhost",user="root",passwd="admin",database="Records")
y=x.cursor()
y.execute("select* from Item where Item like 'E%'")
y.fetchmany(3)
AV()
Output-
Q3) Write a Python SQL Connectivity program to display those records where name starts
with letter “V” and house is not blank considering table name as ‘School’, database name as
‘Teresa’.
AdmissionNo Name House
0789 Shinzu Null
7754 Muko Niti Khand 1
2245 Hinato Null
import mysql.connector as m
x=m.connect(host="localhost",user="root",passwd="admin",database="Teresa")
y=x.cursor()
y.execute("select * from school where name like 'V%' and house is not NULL")
for i in y:
print(i)
x.close()
Output-
Q4) Write a program to delete the record of the student on the basis of name fetched from
the user at run-time.
RNo Sname Adm_no
1 Marlo 6577
2 Rambo 5655
3 Hikari 2467
4 Utsu 9403
import mysql.connector as m
a=m.connect(host="localhost",user="root",passwd="admin",database="Records")
b=a.cursor()
nm=input("Enter name of the student whose record to be deleted-")
b.execute("delete from Student where name='nm'")
print(b.rowcount,"records")
a.close()
Output-
Q5) Consider a database “Records” that has a table “Emp” that stores IDs of employees. Write
a MySQL-Python connectivity to retrieve data, one record at a time, for employees with IDs
less than 10.

ID Name Salary

23 Karishma 900000

12 Chand Bibi 560000

03 Jayshankar 220000

import mysql.connector as m
a=m.connect(host="localhost",user="root",passwd="admin",database="Records")
b=a.cursor()
b.execute("select * from Emp where ID<10")
print(b.fetchone())
a.close()
Output-
Q6) Write code to connect database Record and then fetch all records from table Student
where grade is “A”.
Roll_no Name Grade
2 Shinshau B
5 Limo A
7 Guzu A
import mysql.connector as m
a=m.connect(host="localhost",user="root",passwd="admin",database="Records")
b=a.cursor()
b.execute("select * from Student where grade='A'")
c=b.fetchall()
for i in c:
print(i)
a.close()
Output-
Q7) St. Teresa School is managing student data in “Student” table in “Records” database.
Write a python code that connects to database record and retrieves all records and displays
total number of students.
import mysql.connector as m
a=m.connect(host="localhost",user="root",passwd="admin",database="Records")
b=a.cursor()
b.execute("select * from Student")
c=b.fetchall()
count=0
for i in c:
count+=1
print(i)
print("total no of records-",count)
a.close()
Output-
Q8) Write a Program for the table Detail and Database to input a new record as specified by
the user.
def goat():
import mysql.connector as m
a=m.connect(host='localhost',user='root',passwd='admin',database='Records')
b=a.cursor()
x=input("Enter Id")
y=input("EPrice")
z=input("Tax")
s=input("Eplace")
b.execute(“insert into Export values ('+x+","+y+","+z+","+"'"+s+"'"+")")
for i in b:
print(i)
goat()

Output-
Structured Query Language of Two Tables
Q1) Consider the following tables Product and Client. Write SQL commands for the
statements and give outputs:-
Table: Product
P_ID Productname Manufacturer Price
TP01 Talcum Powder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95
Table: Client
C_ID Clientname City P_ID
01 Cosmetic Shop Delhi TP01
06 Total Health Mumbai FW05
12 Live Life Delhi BS01
15 Pretty Woman Delhi SH06
16 Dreams Bengaluru FW12

i) To display the details of those Clients whose city is Delhi?


select * from Client where City=’Delhi’;

ii) To display the details of products whose price is in the range of 50 to 100( both
values included)
select * from Product where Price between 50 and 100;

iii) To display the details of those products whose name ends with “wash”.
select * from Product where Productname like ‘%wash’;

iv) To display Manufacturer, maximum price and minimum price and count the
records of each manufacturer.
select Manufacturer, max(Price), min(Price), count(*) from Product group by
Manufacturer;

v) Display product name and four times of price of product.


select Productname, Price*4 from Product;

Q2) Consider the following tables Teacher and Posting given below:-
Table: Teacher
T_ID Name Age Department Date_of_join Salary Gender
1 Jugal 34 Computer Sc 2017-01-10 12000 M
2 Sharmilla 31 History 2008-03-24 20000 F
3 Sandeep 32 Mathematics 2016-12-12 30000 M
4 Sangeeta 35 History 2015-07-01 40000 F
5 Rakesh 42 Mathematics 2007-09-05 25000 M
Table: Posting
P_ID Department Place
1 History Agra
2 Mathematics Raipur
3 Computer Science Delhi

i) To show all information about the teachers of History department.


select * from Teacher where Department=’History’;
ii) To list the names of female teachers with their date of joining in ascending order.
select Name from Teacher where Department=’Mathematics’ and Gender=’M’;

iii) To list the names of all teachers with their date of joining in ascending order.
select Name from Teacher order by Date_of_join;

iv) To display teacher’s name, salary, age for male teachers only;
select Name, Salary, Age from Teacher where Gender=’M’;

v) To display name, bonus for each teacher where bonus is 10% of salary;
select Name, Salary*0.1 as Bonus from Teacher;

Q3) Consider the following tables- Company and Model:-


Table: Company
Comp_ID CompName CompHO Contactperson
1 Titan Okhla C.B. Ajit
2 Ajanta Najafgarh R. Mehta
3 Maxima Shahdara B. Kholi
Table: Model
Model_ID Comp_ID Cost DateofManufacture
T020 1 2000 2010-05-12
M032 2 7000 2009-04-15
M059 3 800 2009-09-23

i) To display details of all models in the Model table in ascending order of


DateofManufacture.
select * from Model order by DateofManufacture;

ii) To display details of those models manufactured in 2011 and whose cost is below
2000.
select * from Model where year(DateofManufacture)=2011 and Cost<2000;

iii) To dispaly the Model_ID, Comp_ID, Cost from the table Model, CompName, and
ContactPerson from Company table, with their corresponding Comp_ID.
select Model_ID, Comp_ID,Cost,CompName,ContactPerson from Model, Company where
Model.Comp_ID=Company.Comp_ID;

iv) To decrease the cost of all the models in Model table by 15%
update Model set Cost=Cost-0.15*Cost;

v) To display Company Name, and add Mr. before Contact person where company
name ends with letter a.
select Compname, ‘Mr.’, ContactPerson from Company where CompName like ‘%a’;

Q4) Consider the following Tables: Stationery and Consumer:-


Table: Stationery
S_ID StationeryName Company Price Stockdate
DP01 Dot Pen ABC 10 2011-03-31
PL02 Pencil XYZ 6 2010-01-01
ER05 Eraser XYZ 7 2010-02-14
PL01 Pencil CAM 5 2009-01-09
GP02 Gel Pen ABC 15 2009-03-19
Table: Consumer
C_ID ConsumerName Address S_ID
01 Good Learner Delhi PL01
06 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02
16 Motivation Bengaluru PL01

i) To display details of all the stationery items in the stationery table in descending
order of StockDate.
select * from Stationery order by StockDate desc;

ii) To dispay details of that stationery item whose Company is XYZ and price is below
10.
select * from Stationery where Company=’XYZ’ and price<10;

iii) To display consumer name, address from the table consumer and company and
price from stationery table with their corresponding S_ID.
select ConsumerName,Address,Company,Price from Consumer,Stationery where
Consumer.P_ID=Stationery.S_ID;

iv) To increase the price of all the stationery items in stationery table by 2 Rs.
update Stationery set Price=Price+2;
v) Count the consumers who have distinct addresses.
select count(distinct Address) from Consumer;

Q5) Consider the following tables: Stock and Dealer:-


Table: Stock
ItemNo Item Dcode Qty UnitPrice StockDate
5005 Ball Pen 0.5 102 100 16 2011-03-31
5003 Ball Pen 0.25 102 150 20 2010-01-01
5002 Gel Pen Premium 101 125 14 2010-02-14
5006 Gel Pen Classic 101 200 22 2009-01-09
5001 Eraser Small 102 210 5 2009-03-19
Table: Dealer
Dcode Dname
101 Reliable Stationers
103 Class Plastics
104 Fair Deals
102 Clear Deals

i) To display details of all the items in the Stock table in ascending order of
StockDate.
select * from Stock order by StockDate;

ii) To display details of those items in Stock table whose Dealer Code (Dcode) is 102
or quantity in Stock(Qty) is more than 100.
select * from Stock where Dcode=102 pr Qty>100;
iii) To insert a record in the Stock table with the values.
insert into Stock values(5010, ‘Pencil HB’, 102, 500, 10, ‘2010-01-26’);

iv) To display Dcode, Dname from Dealer table and Item, UnitPrice from Stock table
of all the Dealers.
select Dealer.Dcode, Dname, Item, UnitPrice from Dealer left join Stock on
Dealer.Dcode=Stock.Dcode;

v) Display result of quantity and unit price by multiplying them for item no 5006.
select Qty*UnitPrice from Stock where ItemNo=5006;

Stack
Q1) Alam has a list containing 10 integers. You need to help him create a program with
separate user defined to perform the following operations based on this list:
N=[12,13,34,56,21,79,98,22,35,38]
Sample output-
[38,22,98,56,34,12]
i) Transverse the content of the list and push the even numbers into a stack.
ii) Pop and display content of stack.
def Push(stack,i):
stack.append(i)
def Pop(stack):
if stack!=[]:
print(stack.pop(),end=" ")
N=[12,13,34,56,21,79,98,22,35,38]
stack=[]
for i in N:
if i%2==0:
Push(stack,i)
while True:
if stack!=[]:
Pop(stack)
else:
break
Output-
38 22 98 56 34 12
Q2) Debojit has created a dictionary containing names and marks as key value pair. Write a
program with separate user defined function to perform the following operation:
i) Push the keys(Name of the student) of a dictionary into a stack where the
corresponding values(marks) is greater than 75.
ii) Pop and display the content of the stack. For example, sample content of the
dictionary is as follows are equal to
{"om":76,"jay":45,"bob":89,"ali":65,"anu":65,"tom":82}.
def push(L,m):
L.append(m)
def Pop(L):
if L!=[]:
print(L.pop(), end=" ")
else:
return None
R={"om":76,"jay":45,"bob":89,"ali":65,"anu":90,"tom":82}
L=[]
for i in R:
if R[i]>75:
push(L,i)
while True:
if L!=[]:
Pop(L)
else:
break
Output-
tom anu bob om
Q3) Write a program to display unique vowels present in the given word using Stack.
vowels=['a','e','i','o','u']
word=input("enter a word")
stack=[]
for letter in word:
if letter in vowels:
if letter not in stack:
stack.append(letter)
print(stack)
print("the number of different vowels present in",word,"is",len(stack))
Output-
enter a wordancey
['a', 'e']
the number of different vowels present in ancey is 2
Q4) Write a function in Python Push(Arr), where Arr is a list of numbers. From this list, push
all the numbers divisible by 5 into a stack implemented by using a list. Display the stack if it
has at least one element, otherwise display appropriate error message.
def Push(Arr):
s=[]
for x in range(0,len(Arr)):
if Arr[x]%5==0:
s.append(Arr[x])
if len(s)==0:
print("Empty Stack")
else:
print(s)
Arr=[25,67,89,10,54,55,55]
Push(Arr)
Output-
[25]
[25, 10]
[25, 10, 55]
[25, 10, 55, 55]
Q5) 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.
def POP(Arr):
if len(Arr)==0:
print("Underflow")
else:
L=len(Arr)
val=Arr.pop(L-1)
print(val)
Arr=[1,2,3,4,5,6,7,8,9]
POP(Arr)
Output-
9

You might also like