# Python Programming Exam Questions and Answers
## Q1(a) Dictionary Operations
**Question:** Create a dictionary containing any 5 elements in the form
of key, value pair, and write python code to perform the following operations on
it.
i) To display all the keys
ii) To add new key value pair
iii) To delete specific element from the dictionary
iv) To modify value of a particular key
**Answer:**
A dictionary stores data in key–value pairs. The following program
performs all required dictionary operations.
d = {1:"Ajay",2:"Vijay",3:"Ganesh",4:"Paresh",5:"Mahesh"} # dictionary
creation
print([Link]()) # display all keys
d[6] = "Ramesh" # add new key-value pair
print(d)
del d[3] # delete specific element
print(d)
d[2] = "Sanjay" # modify value of a key
print(d)
## Q1(b) Swap Odd-Even Position Characters
**Question:** Write a program which swap every odd-even position
character in the string (e.g. Input: 'abcdef' Output: 'badcfe').
**Answer:**
The program swaps characters at odd and even positions in a string.
s = "abcdef" # input string
r = "" # empty result string
for i in range(0,len(s),2): # loop with step 2
if i+1 < len(s):
r = r + s[i+1] + s[i]
else:
r = r + s[i]
print(r) # display result
## Q1(c) First Letter Extraction Using List Comprehension
**Question:** Write a program to create the separate list by taking the
first letter of each word from the original string using list comprehension.
Input list : ['Ajay', 'Vijay', 'Ganesh', 'Paresh', 'Mahesh']
Output list : ['A', 'V', 'G', 'P', 'M']
**Answer:**
List comprehension is used to extract the first character of each word.
lst = ['Ajay','Vijay','Ganesh','Paresh','Mahesh'] # input list
res = [x[0] for x in lst] # list comprehension
## Q1(d) Set Operations
**Question:** Write a program to create a set by accepting n elements
(0-9 or A-Z or a-z) input from the user.
i) Display the set elements
ii) Length of set
iii) Count number of digits, lowercase letters, upper case letters in a set
**Answer:**
A set stores unique elements. The following program performs all required
operations.
n = int(input()) # number of elements
s = set() # empty set
for i in range(n):
[Link](input()) # add elements to set
print(s) # display set
print(len(s)) # length of set
d=l=u=0
for ch in s:
if [Link]():
d += 1
elif [Link]():
l += 1
elif [Link]():
u += 1
print(d,l,u) # display counts
## Q2(a) Reverse Each Word in String
**Question:** Write a function to accept string from user and it will
return reverse each word of string.
**Answer:**
Each word of the string is reversed individually.
s = input() # accept string
w = [Link]() # split into words
r = [x[::-1] for x in w] # reverse each word
print(" ".join(r)) # display result
## Q2(b) Generator Function
**Question:** Write a generator function my-range(start, stop, step)
which will accept three arguments as start, stop, and step and generate a given
range.
**Answer:**
A generator function generates values using the yield keyword.
def my_range(start,stop,step):
while start < stop:
yield start # return value one by one
start += step
for i in my_range(1,10,2):
print(i)
## Q2(c) User-Defined Exception for Factorial
**Question:** Write user defined exception program in python which will find
the
factorial of a number. If number is less than zero it should raise the exception as
"Invalid Input".
**Answer:**
User-defined exception is raised for negative numbers.
class InvalidInput(Exception): # custom exception
pass
def fact(n):
if n < 0:
raise InvalidInput("Invalid Input")
f=1
for i in range(1,n+1):
f *= i
return f
try:
n = int(input())
print(fact(n))
except InvalidInput as e:
print(e)
## Q2(d) Random Module Functions
**Question:** Explain the use of any five functions from the random module
with suitable example.
**Answer:**
- **random()** generates a float between 0 and 1
- **randint()** returns random integer
- **choice()** selects random element
- **shuffle()** shuffles list
- **uniform()** generates float between two values
import random
print([Link]()) # random float
print([Link](1,10)) # random integer
print([Link]([10,20,30])) # random element
a = [1,2,3,4]
[Link](a) # shuffle list
print(a)
print([Link](1,5)) # random float range
## Q3(a) Student Class
**Question:** Create a class student having attributes 'First Name', 'Last Name',
'Qualification'
and methods 'update Qualification', 'Display details', and a constructor to
initialize the values.
Write main program to demonstrate the use of student class.
**Answer:**
A class is a blueprint for creating objects. The following program
demonstrates class creation, constructor, methods, and object usage.
class Student:
def __init__(self, fname, lname, qual): # constructor
[Link] = fname
[Link] = lname
[Link] = qual
def updateQualification(self, qual): # update qualification
[Link] = qual
def display(self): # display details
print([Link], [Link], [Link])
s = Student("Ajay", "Patil", "BSc") # object creation
[Link]()
[Link]("MCA")
[Link]()
## Q3(b) Delegation and Containership
**Question:** Describe the concept of Delegation and Containership with
suitable example.
**Answer:**
**Containership** means one class contains an object of another class.
**Delegation** means a class delegates responsibility to another class.
class Engine:
def start(self):
print("Engine Started")
class Car:
def __init__(self):
[Link] = Engine() # containership
def start(self):
[Link]() # delegation
c = Car()
[Link]()
## Q3(c) Email Validation Using Regular Expression
**Question:** Write a program to validate email address using regular
expression.
**Answer:**
Regular expressions are used to match patterns in strings.
import re
email = input()
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
if [Link](pattern, email):
print("Valid Email")
else:
print("Invalid Email")
## Q3(d) Multithreading with Synchronization
**Question:** Write a multithreaded program, where one thread prints square
of a number and another thread prints cube of numbers. Make use of thread
synchronization.
**Answer:**
Thread synchronization is achieved using a Lock to avoid conflict.
import threading
lock = [Link]()
def square(n):
[Link]()
print("Square:", n*n)
[Link]()
def cube(n):
[Link]()
print("Cube:", n*n*n)
[Link]()
t1 = [Link](target=square, args=(5,))
t2 = [Link](target=cube, args=(5,))
[Link]()
[Link]()
[Link]()
[Link]()
## Q4(a) MongoDB Books Collection Operations
**Question:** Write a MongoDB program to create a "Books" collection having
fields:
Title, Author, Publisher, Price. Write a code to perform the following operations.
i) Insert 5 documents into Books collection
ii) Retrieve books whose publisher is 'pearson'
iii) Retrieve books whose price is between 400 to 600
iv) Retrieve books in the descending order of price
v) Update the price of book by 10% whose title is 'Python'
vi) Update the title of a book whose author is 'Guido' and publisher is 'BPB'
vii) Delete books whose price is greater than 500
**Answer:**
The following program performs all MongoDB operations using PyMongo.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = [Link]
books = [Link]
books.insert_many([
{"Title":"Python","Author":"Guido","Publisher":"BPB","Price":500},
{"Title":"Java","Author":"James","Publisher":"Pearson","Price":450},
{"Title":"C","Author":"Dennis","Publisher":"Pearson","Price":550},
{"Title":"DBMS","Author":"Navathe","Publisher":"McGraw","Price":600},
{"Title":"AI","Author":"Russell","Publisher":"Pearson","Price":400}
])
print(list([Link]({"Publisher":"Pearson"})))
print(list([Link]({"Price":{"$gte":400,"$lte":600}})))
print(list([Link]().sort("Price",-1)))
books.update_one({"Title":"Python"},{"$mul":{"Price":1.1}})
books.update_one({"Author":"Guido","Publisher":"BPB"},{"$set":{"Title":"Advan
ced Python"}})
books.delete_many({"Price":{"$gt":500}})
## Q4(b) MongoDB Student Collection Operations
**Question:** Write a MongoDB program to create a Student collection having
fields:
Roll No, Name, Course, Marks, Grade Point. Write code to perform the following
operations:
i) Insert 5 documents into Student collection
ii) Find students having marks between 80 to 90
iii) Update name of a student whose roll no. is 5
iv) Display top 3 students according to their grade points
v) Display students having highest grade points
vi) Find all students having course 'MCA'
vii) Display all students in the descending order of marks
**Answer:**
The following MongoDB program uses PyMongo to create and perform
operations on the Student collection.
python
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = [Link]
students = [Link]
students.insert_many([
{"RollNo":1,"Name":"Ajay","Course":"MCA","Marks":85,"GradePoint":8.5},
{"RollNo":2,"Name":"Vijay","Course":"MBA","Marks":78,"GradePoint":7.8},
{"RollNo":3,"Name":"Ganesh","Course":"MCA","Marks":92,"GradePoint":9.2},
{"RollNo":4,"Name":"Paresh","Course":"MCA","Marks":88,"GradePoint":8.8},
{"RollNo":5,"Name":"Mahesh","Course":"MSC","Marks":81,"GradePoint":8.1}
])
print(list([Link]({"Marks":{"$gte":80,"$lte":90}})))
students.update_one(
{"RollNo":5},
{"$set":{"Name":"Ramesh"}}
)
print(list([Link]().sort("GradePoint",-1).limit(3)))
max_gp = students.find_one(sort=[("GradePoint",-1)])["GradePoint"]
print(list([Link]({"GradePoint":max_gp})))
print(list([Link]({"Course":"MCA"})))
print(list([Link]().sort("Marks",-1)))
## Q5(a) Django Student Registration Page
**[Link]**
from [Link] import models
class Student([Link]):
name = [Link](max_length=100)
course = [Link](max_length=50)
**[Link]**
from [Link] import render
from .models import Student
def register(request):
if [Link] == "POST":
name = [Link]['name']
course = [Link]['course']
[Link](name=name, course=course)
return render(request, '[Link]')
**template ([Link])**
html
<form method="post">
{% csrf_token %}
Name: <input type="text" name="name"><br>
Course: <input type="text" name="course"><br>
<input type="submit">
</form>
## Q5(b) Send Date and Time from View to Template
**[Link]**
from [Link] import render
from datetime import datetime
def show_datetime(request):
now = [Link]()
return render(request, '[Link]', {'current_time': now})
**template ([Link])**
html
<h3>Current Date and Time: {{ current_time }}</h3>
## Q5(c) Django REST Framework (DRF)
**Short Note:**
Django REST Framework (DRF) is a powerful toolkit for building Web APIs in
Django. It supports serialization, authentication,
permissions, and viewsets. DRF uses JSON as the default response format and
simplifies RESTful service development.
## Q5(d) Mapping View to URL in Django
**[Link]**
from [Link] import path
from . import views
urlpatterns = [
path('register/', [Link], name='register'),
]