0% found this document useful (0 votes)
5 views24 pages

Python Solved Paper

The document is a solved question paper for a Python Programming course, covering topics from six units. It includes detailed explanations of Python objects, expressions, numerical types, functions like range() and input(), data structures such as tuples and dictionaries, mutability, lambda functions, exception handling, file handling, and built-in exceptions. Each section provides examples and syntax to illustrate the concepts effectively.

Uploaded by

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

Python Solved Paper

The document is a solved question paper for a Python Programming course, covering topics from six units. It includes detailed explanations of Python objects, expressions, numerical types, functions like range() and input(), data structures such as tuples and dictionaries, mutability, lambda functions, exception handling, file handling, and built-in exceptions. Each section provides examples and syntax to illustrate the concepts effectively.

Uploaded by

dushyantbhatu123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SOLVED QUESTION PAPER

Subject: Python Programming


Complete Solution – All Units (1 to 6)

UNIT 1

Q-1. Explain Python Objects, Expressions, and Numerical Types.


Ans.
Python is an object-oriented language where everything — numbers, strings, functions, and even
classes — is an object. Each object has an identity (id), a type (type()), and a value.
1. Python Objects
• An object is an instance of a data type or class.
• Objects have: Identity (memory address), Type (int, float, str, etc.), Value (stored data)
Example:
x = 10 # x is an object of type int
print(id(x)) # prints memory address
print(type(x)) # <class 'int'>
print(x) # 10

2. Python Expressions
An expression is a combination of values, variables, and operators that evaluates to a result.
Types of Expressions:
• Arithmetic Expressions: 3 + 5 * 2 evaluates to 13
• Relational Expressions: 5 > 3 evaluates to True
• Logical Expressions: True and False evaluates to False
• Assignment Expressions: x = 10 assigns 10 to x
a = 10; b = 3
print(a + b) # 13
print(a % b) # 1
print(a // b) # 3

3. Numerical Types
• int: Whole numbers (positive or negative). Example: x = 100
• float: Decimal numbers. Example: y = 3.14
• complex: Numbers with real and imaginary parts. Example: z = 2 + 3j
x = 100 # int
y = 3.14 # float
z = 2 + 3j # complex
print(type(x)) # <class 'int'>
print(type(y)) # <class 'float'>
print(type(z)) # <class 'complex'>
print([Link]) # 2.0
print([Link]) # 3.0

Python Programming – Solved Paper | Page 1


Q-2. Explain the range() function in detail with example.
Ans.
The range() function generates a sequence of numbers. It is widely used in loops and list generation.
Syntax:
range(stop)
range(start, stop)
range(start, stop, step)
Parameters:
• start – Starting value (default is 0)
• stop – Ending value (not included)
• step – Increment between each number (default is 1)

Examples:
# Example 1: range(stop)
for i in range(5):
print(i, end=' ') # 0 1 2 3 4

# Example 2: range(start, stop)


for i in range(2, 7):
print(i, end=' ') # 2 3 4 5 6

# Example 3: range(start, stop, step)


for i in range(0, 10, 2):
print(i, end=' ') # 0 2 4 6 8

# Example 4: Reverse range


for i in range(10, 0, -2):
print(i, end=' ') # 10 8 6 4 2

# Convert to list
print(list(range(1, 6))) # [1, 2, 3, 4, 5]
Note: range() returns a range object, not a list. Use list() to convert if needed.

Q-3. Explain Branching and Iteration Statements in Python.


Ans.
A. Branching Statements (Conditional Statements)
Branching allows the program to take different paths based on conditions.
1. if Statement:
x = 10
if x > 5:
print('x is greater than 5')
2. if-else Statement:
x = 3
if x % 2 == 0:
print('Even')
else:
print('Odd')

Python Programming – Solved Paper | Page 2


3. if-elif-else Statement:
marks = 75
if marks >= 90:
print('Grade A')
elif marks >= 75:
print('Grade B')
elif marks >= 60:
print('Grade C')
else:
print('Fail')

B. Iteration Statements (Loops)


1. for Loop – used to iterate over sequences:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
2. while Loop – executes as long as the condition is True:
n = 1
while n <= 5:
print(n)
n += 1
3. Loop Control Statements:
• break – exits the loop immediately
• continue – skips the current iteration
• pass – placeholder, does nothing
for i in range(10):
if i == 5:
break # stop at 5
if i % 2 == 0:
continue # skip even
print(i) # prints 1 3

Q-4. Explain the input() function in Python.


Ans.
The input() function is used to accept user input from the keyboard during runtime.
Syntax: variable = input(prompt)
• prompt – An optional string message displayed to the user.
• The function always returns a string, regardless of what the user types.
• Use int(), float() etc. to convert the input to required type.

Examples:
# Basic input
name = input('Enter your name: ')
print('Hello,', name)

# Integer input
age = int(input('Enter your age: '))
print('Your age is:', age)

Python Programming – Solved Paper | Page 3


# Float input
price = float(input('Enter price: '))
print('Price with GST:', price * 1.18)

# Multiple values in one line


a, b = input('Enter two numbers: ').split()
print(int(a) + int(b))
Note: If the user enters non-numeric data and you try to convert it, Python raises a ValueError.

Q-5. Explain Tuples and Dictionaries with suitable examples.


Ans.
A. Tuples
A tuple is an ordered, immutable (unchangeable) collection of items. Items are enclosed in
parentheses ().
# Creating a tuple
t = (10, 20, 30, 'Python', 3.14)
print(t[0]) # 10
print(t[-1]) # 3.14
print(t[1:3]) # (20, 30)

# Tuple functions
print(len(t)) # 5
print([Link](10))# 1
print([Link](20))# 1

# Tuple packing and unpacking


a, b, c = (1, 2, 3)
print(a, b, c) # 1 2 3

B. Dictionaries
A dictionary is an unordered, mutable collection of key-value pairs. Keys must be unique and
immutable.
# Creating a dictionary
student = {'name': 'Raj', 'age': 20, 'marks': 85}

# Accessing values
print(student['name']) # Raj
print([Link]('age')) # 20

# Adding / Updating
student['city'] = 'Ahmedabad'
student['marks'] = 90

# Deleting
del student['city']

# Iteration
for key, value in [Link]():
print(key, ':', value)

Python Programming – Solved Paper | Page 4


# Dictionary methods
print([Link]()) # dict_keys(['name', 'age', 'marks'])
print([Link]()) # dict_values(['Raj', 20, 90])

Q-6. Explain Mutability and Cloning in Python.


Ans.
A. Mutability
• Mutable objects can be changed after creation: list, dict, set
• Immutable objects cannot be changed after creation: int, float, str, tuple
# Mutable example
lst = [1, 2, 3]
lst[0] = 100
print(lst) # [100, 2, 3]

# Immutable example
t = (1, 2, 3)
# t[0] = 100 # TypeError: tuple does not support assignment

B. Cloning
Cloning means creating an independent copy of an object. Without cloning, both variables point to the
same object.
Shallow Copy – copies the outer object only:
import copy
lst1 = [1, 2, 3]
lst2 = lst1[:] # slice clone
lst3 = [Link](lst1) # shallow copy
[Link](99)
print(lst1) # [1, 2, 3] -- unaffected
print(lst2) # [1, 2, 3, 99]
Deep Copy – copies nested objects as well:
import copy
lst1 = [[1, 2], [3, 4]]
lst2 = [Link](lst1)
lst2[0][0] = 99
print(lst1) # [[1, 2], [3, 4]] -- unaffected
print(lst2) # [[99, 2], [3, 4]]

UNIT 2

Q-1. Explain Lambda Functions and their use with filter(), map(), and reduce().
Ans.
A lambda function is an anonymous (nameless), inline function defined using the lambda keyword.
Syntax: lambda arguments: expression
# Regular function
def square(x): return x * x

Python Programming – Solved Paper | Page 5


# Equivalent lambda
sq = lambda x: x * x
print(sq(5)) # 25

1. filter() – filters elements for which the function returns True:


nums = [1, 2, 3, 4, 5, 6, 7, 8]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4, 6, 8]
2. map() – applies function to every element:
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, nums))
print(squares) # [1, 4, 9, 16, 25]
3. reduce() – reduces sequence to a single value (from functools):
from functools import reduce
nums = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, nums)
print(product) # 120

Q-2. Explain different types of arguments in Python with examples.


Ans.
Python supports 5 types of function arguments:

1. Positional Arguments – passed in order:


def add(a, b): return a + b
print(add(3, 5)) # 8
2. Keyword Arguments – passed with parameter names:
def greet(name, age):
print(f'Name: {name}, Age: {age}')
greet(age=20, name='Raj')
3. Default Arguments – have a default value:
def greet(name, msg='Hello'):
print(msg, name)
greet('Raj') # Hello Raj
greet('Raj', 'Hi') # Hi Raj
4. Variable-Length Positional (*args):
def total(*nums):
return sum(nums)
print(total(1, 2, 3, 4)) # 10
5. Variable-Length Keyword (**kwargs):
def info(**data):
for k, v in [Link]():
print(k, ':', v)
info(name='Raj', city='Ahmedabad')

Python Programming – Solved Paper | Page 6


Q-3. Discuss Exception Handling in Python. Explain try, except, finally, assert, and
user-defined exceptions.
Ans.
Exception handling prevents program crashes due to runtime errors.

1. try – except Block:


try:
x = int(input('Enter number: '))
result = 10 / x
print(result)
except ZeroDivisionError:
print('Cannot divide by zero!')
except ValueError:
print('Please enter a valid integer!')
2. finally Block – always executes (cleanup):
try:
f = open('[Link]', 'r')
data = [Link]()
except FileNotFoundError:
print('File not found!')
finally:
print('Execution complete.')
3. assert Statement – raises AssertionError if condition is False:
def divide(a, b):
assert b != 0, 'Divisor cannot be zero'
return a / b
print(divide(10, 2)) # 5.0
# divide(10, 0) → AssertionError: Divisor cannot be zero
4. else Clause – runs only if no exception occurred:
try:
result = 10 / 2
except ZeroDivisionError:
print('Error')
else:
print('Result:', result) # Result: 5.0
5. User-Defined (Custom) Exceptions:
class AgeError(Exception):
def __init__(self, msg='Age must be between 1 and 120'):
super().__init__(msg)

def validate_age(age):
if age < 1 or age > 120:
raise AgeError()
print('Valid age:', age)

try:
validate_age(200)
except AgeError as e:
print('Exception:', e)

Python Programming – Solved Paper | Page 7


Q-4. Explain File Handling in Python. Discuss text files, binary files, seek(), tell(), and
with statement.
Ans.
File handling allows reading and writing data to files persistently.

1. Text Files – store human-readable characters:


# Writing to text file
f = open('[Link]', 'w')
[Link]('Hello, Python!\n')
[Link]('File Handling')
[Link]()

# Reading from text file


f = open('[Link]', 'r')
print([Link]())
[Link]()
2. Binary Files – store data in binary format:
# Write binary
f = open('[Link]', 'wb')
[Link](bytes([10, 20, 30, 40]))
[Link]()

# Read binary
f = open('[Link]', 'rb')
print([Link]()) # b'\n\x14\x1e('
[Link]()
3. seek() and tell():
f = open('[Link]', 'r')
print([Link](5)) # reads 5 chars
print([Link]()) # current position = 5
[Link](0) # go back to beginning
print([Link]()) # reads entire file
[Link]()
4. with Statement – auto-closes file:
with open('[Link]', 'r') as f:
content = [Link]()
print(content)
# File is automatically closed after the block

Q-5. Explain different types of built-in exceptions (errors) in Python.


Ans.
Python provides several built-in exceptions. All exceptions are derived from the BaseException class.

Common Built-in Exceptions:


Exception Cause Example
SyntaxError Invalid Python syntax if x == 10 (missing
colon)

Python Programming – Solved Paper | Page 8


IndentationError Wrong indentation def f():\nprint() (no
indent)
NameError Variable not defined print(xyz) before
assignment
TypeError Wrong data type operation 'abc' + 5
ValueError Correct type, wrong value int('abc')
ZeroDivisionError Division by zero 10 / 0
IndexError Index out of range lst[10] on list of 3
KeyError Key not found in dict d['missing']
AttributeError Object lacks attribute [Link]()
FileNotFoundError File does not exist open('[Link]','r')
ImportError Module not found import xyz
OverflowError Number too large for float import math;
[Link](1000)

Q-6. Discuss opening, closing, and different file modes with suitable examples.
Ans.
1. Opening a File – using open():
file_object = open('filename', 'mode')
2. File Modes:
Mode Description
'r' Read only (default). File must exist.
'w' Write only. Creates new or overwrites existing.
'a' Append. Adds to end of existing file.
'x' Exclusive create. Fails if file exists.
'r+' Read and Write. File must exist.
'w+' Read and Write. Overwrites existing.
'rb' Read in binary mode.
'wb' Write in binary mode.

3. Examples:
# Write mode
f = open('[Link]', 'w')
[Link]('Line 1\n')
[Link]()

# Append mode
f = open('[Link]', 'a')
[Link]('Line 2\n')
[Link]()

Python Programming – Solved Paper | Page 9


# Read mode
f = open('[Link]', 'r')
print([Link]())
[Link]()
4. Closing a File – always close files to free resources:
f = open('[Link]', 'r')
# ... do operations ...
[Link]() # frees OS resource

UNIT 3

Q-1. Explain Abstract Data Types (ADT) and Classes in Python.


Ans.
1. Abstract Data Type (ADT)
An ADT defines what operations can be performed on a data structure, but not how they are
implemented. It separates interface from implementation. Examples: Stack, Queue, List.
• ADT specifies: data stored, operations on data, error conditions.
• Users interact with the ADT through its interface, not its implementation.

2. Classes in Python
A class is a blueprint for creating objects. It encapsulates data (attributes) and behavior (methods).
class Student:
# Class attribute
school = 'DY Patil'

# Constructor (initializer)
def __init__(self, name, roll, marks):
[Link] = name
[Link] = roll
[Link] = marks

# Instance method
def display(self):
print(f'Roll: {[Link]}, Name: {[Link]}, Marks:
{[Link]}')

# Static method
@staticmethod
def college():
return [Link]

# Creating objects
s1 = Student('Raj', 101, 85)
s2 = Student('Priya', 102, 90)
[Link]()
[Link]()
print([Link]())

Python Programming – Solved Paper | Page 10


Q-2. Explain Inheritance in Python with suitable examples.
Ans.
Inheritance is a mechanism where a child class acquires properties and methods of a parent class. This
promotes code reuse.

1. Single Inheritance:
class Animal:
def speak(self): print('Animal speaks')

class Dog(Animal):
def bark(self): print('Dog barks')

d = Dog()
[Link]() # inherited
[Link]() # own method
2. Multilevel Inheritance:
class A:
def m1(self): print('A')
class B(A):
def m2(self): print('B')
class C(B):
def m3(self): print('C')
c = C()
c.m1(); c.m2(); c.m3()
3. Multiple Inheritance:
class Father:
def coding(self): print('Father codes')
class Mother:
def cooking(self): print('Mother cooks')
class Child(Father, Mother):
pass
c = Child()
[Link](); [Link]()
4. Hierarchical Inheritance (one parent, many children):
class Shape:
def area(self): pass
class Circle(Shape):
def area(self): print('Circle area')
class Square(Shape):
def area(self): print('Square area')

Q-3. Design a Banking Application using OOP concepts.


Ans.
class BankAccount:
def __init__(self, account_no, name, balance=0):
self.__account_no = account_no # private
self.__name = name
self.__balance = balance

Python Programming – Solved Paper | Page 11


def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f'Deposited Rs.{amount}. Balance: Rs.
{self.__balance}')
else:
print('Invalid deposit amount.')

def withdraw(self, amount):


if 0 < amount <= self.__balance:
self.__balance -= amount
print(f'Withdrawn Rs.{amount}. Balance: Rs.
{self.__balance}')
else:
print('Insufficient funds or invalid amount.')

def get_balance(self):
return self.__balance

def display(self):
print(f'Account: {self.__account_no} | Holder: {self.__name}
| Balance: Rs.{self.__balance}')

class SavingsAccount(BankAccount):
INTEREST_RATE = 0.04 # 4%

def add_interest(self):
interest = self.get_balance() * self.INTEREST_RATE
[Link](interest)
print(f'Interest of Rs.{interest:.2f} added.')

# Main program
acc = SavingsAccount('SB001', 'Raj Patel', 10000)
[Link]()
[Link](5000)
[Link](3000)
acc.add_interest()
[Link]()

Q-4. Explain Method Resolution Order (MRO) in Python in detail.


Ans.
MRO defines the order in which Python searches for methods in a class hierarchy, especially in
multiple inheritance.
Python uses the C3 Linearization algorithm to determine MRO.
MRO Rule: Left-to-right (same level), bottom-to-top (hierarchy).

class A:
def greet(self): print('Hello from A')

class B(A):
def greet(self): print('Hello from B')

Python Programming – Solved Paper | Page 12


class C(A):
def greet(self): print('Hello from C')

class D(B, C):


pass

d = D()
[Link]() # Hello from B (MRO: D -> B -> C -> A)

print(D.__mro__)
# (<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, <class
'object'>)

# Use mro() method


print([Link]())
MRO for D: D → B → C → A → object
Python checks class D first, then B (left), then C (right), then A, and finally object.
• Use help(ClassName) to see the MRO.
• Use ClassName.__mro__ or [Link]() to view it programmatically.

Q-5. Explain Constructor, Object Creation, and Class Members with examples.
Ans.
1. Constructor – __init__() method:
Constructor is automatically called when an object is created. It initializes instance variables.
class Person:
def __init__(self, name, age):
[Link] = name # instance variable
[Link] = age
def display(self):
print(f'{[Link]} is {[Link]} years old')

p1 = Person('Raj', 22) # object creation


[Link]()

2. Object Creation:
• object_name = ClassName(arguments) calls __init__ and creates the object in memory.
p2 = Person('Priya', 20)
print(type(p2)) # <class '__main__.Person'>
3. Class Members:
• Instance Variables: Specific to each object ([Link])
• Class Variables: Shared across all objects (defined outside __init__)
• Instance Methods: Use self, operate on instance data
• Class Methods: Use @classmethod and cls parameter
• Static Methods: Use @staticmethod, no self or cls
class Counter:
count = 0 # class variable

def __init__(self):

Python Programming – Solved Paper | Page 13


[Link] += 1

@classmethod
def get_count(cls):
return [Link]

c1 = Counter(); c2 = Counter(); c3 = Counter()


print(Counter.get_count()) # 3

Q-6. What is method overriding? Explain the use of super() function with example.
Ans.
Method Overriding occurs when a child class provides its own implementation of a method already
defined in the parent class.
class Animal:
def sound(self):
print('Some animal sound')

class Dog(Animal):
def sound(self): # overrides parent method
print('Dog barks')

class Cat(Animal):
def sound(self): # overrides parent method
print('Cat meows')

a = Animal(); [Link]() # Some animal sound


d = Dog(); [Link]() # Dog barks
c = Cat(); [Link]() # Cat meows

super() Function:
super() allows a child class to call a method from its parent class. It is especially useful in constructors
to avoid rewriting parent initialization code.
class Vehicle:
def __init__(self, brand, speed):
[Link] = brand
[Link] = speed

def display(self):
print(f'Brand: {[Link]}, Speed: {[Link]} km/h')

class Car(Vehicle):
def __init__(self, brand, speed, fuel_type):
super().__init__(brand, speed) # calls Vehicle.__init__
self.fuel_type = fuel_type

def display(self):
super().display() # calls [Link]
print(f'Fuel: {self.fuel_type}')

c = Car('Toyota', 180, 'Petrol')

Python Programming – Solved Paper | Page 14


[Link]()
# Brand: Toyota, Speed: 180 km/h
# Fuel: Petrol

UNIT 4

Q-1. Explain DataFrame creation using CSV files, Dictionary, and List of Tuples.
Ans.
A DataFrame is a 2D labeled data structure in Pandas — like a spreadsheet or SQL table.

1. Creating DataFrame from Dictionary:


import pandas as pd

data = {
'Name': ['Raj', 'Priya', 'Sam'],
'Age': [22, 20, 25],
'Marks': [85, 90, 78]
}
df = [Link](data)
print(df)
2. Creating DataFrame from List of Tuples:
records = [('Raj', 22, 85), ('Priya', 20, 90), ('Sam', 25, 78)]
df = [Link](records, columns=['Name', 'Age', 'Marks'])
print(df)
3. Creating DataFrame from CSV File:
df = pd.read_csv('[Link]')
print([Link]()) # first 5 rows
print([Link]) # (rows, columns)
print([Link]) # column names

Q-2. Explain various operations on data frames.


Ans.
import pandas as pd
df = pd.read_csv('[Link]')

# 1. Viewing data
print([Link]()) # first 5 rows
print([Link](3)) # last 3 rows
print([Link]()) # summary
print([Link]()) # statistics

# 2. Selecting columns
print(df['Name']) # single column
print(df[['Name','Age']]) # multiple columns

# 3. Selecting rows

Python Programming – Solved Paper | Page 15


print([Link][0]) # row by index
print([Link][0]) # row by label

# 4. Filtering
print(df[df['Marks'] > 80])

# 5. Adding new column


df['Grade'] = df['Marks'].apply(lambda x: 'A' if x>=90 else 'B' if
x>=75 else 'C')

# 6. Dropping
[Link]('Age', axis=1, inplace=True)
[Link](0, axis=0, inplace=True) # drop row 0

# 7. Sorting
df.sort_values('Marks', ascending=False, inplace=True)

# 8. Groupby
print([Link]('Grade')['Marks'].mean())

# 9. Handling missing values


print([Link]().sum())
[Link](0, inplace=True)
[Link](inplace=True)

# 10. Save to CSV


df.to_csv('[Link]', index=False)

Q-3. Explain Data Visualization in Python using Matplotlib.


Ans.
Matplotlib is the most widely used Python library for creating static, animated, and interactive
visualizations.
pip install matplotlib

1. Line Plot:
import [Link] as plt
x = [1,2,3,4,5]
y = [2,4,1,6,8]
[Link](x, y, color='blue', marker='o', linestyle='--')
[Link]('Line Plot')
[Link]('X Axis')
[Link]('Y Axis')
[Link](True)
[Link]()
2. Bar Chart:
subjects = ['Math','Sci','Eng','Hist']
marks = [85, 90, 78, 88]
[Link](subjects, marks, color='orange')
[Link]('Subject Marks')
[Link]()
3. Pie Chart:

Python Programming – Solved Paper | Page 16


labels = ['Python','Java','C++','JS']
sizes = [40, 25, 20, 15]
[Link](sizes, labels=labels, autopct='%1.1f%%')
[Link]('Language Popularity')
[Link]()
4. Histogram:
marks = [55,60,65,70,75,80,85,85,90,95]
[Link](marks, bins=5, color='green', edgecolor='black')
[Link]('Marks Distribution')
[Link]()
5. Scatter Plot:
x = [5,7,8,6,9,11,10,12]
y = [60,75,80,65,85,95,88,98]
[Link](x, y, color='red')
[Link]('Hours vs Marks')
[Link]()

Q-4. Explain Plotting using PyLab with examples.


Ans.
PyLab is a procedural interface to Matplotlib's object-oriented plotting library. It combines NumPy
and [Link] into a single namespace.
from pylab import *

# Simple line plot


x = linspace(0, 2*pi, 100) # 100 points from 0 to 2π
y = sin(x)
plot(x, y, label='sin(x)')
title('Sine Wave')
xlabel('Angle (radians)')
ylabel('sin(x)')
legend()
grid(True)
show()

# Multiple plots on one figure


figure()
plot(x, sin(x), 'b-', label='sin')
plot(x, cos(x), 'r--', label='cos')
title('Sine and Cosine')
legend()
show()
PyLab makes MATLAB-style plotting easy but for production code, explicit [Link] is
preferred.

Q-5. Explain Data Analysis using Pandas DataFrames.


Ans.
import pandas as pd
import numpy as np

Python Programming – Solved Paper | Page 17


# Load data
df = pd.read_csv('[Link]')

# 1. Basic exploration
print([Link]) # dimensions
print([Link]) # data types
print([Link]()) # mean, std, min, max

# 2. Correlation analysis
print([Link]())

# 3. Group analysis
print([Link]('Region')['Sales'].sum())
print([Link]('Category').agg({'Sales':'sum', 'Profit':'mean'}))

# 4. Pivot table
pt = df.pivot_table(values='Sales', index='Region',
columns='Category', aggfunc='sum')
print(pt)

# 5. Merging DataFrames
df1 = [Link]({'ID':[1,2,3], 'Name':['A','B','C']})
df2 = [Link]({'ID':[1,2,4], 'Score':[90,85,78]})
merged = [Link](df1, df2, on='ID', how='inner')
print(merged)

# 6. Time series analysis


df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
monthly = df['Sales'].resample('M').sum()
print(monthly)

UNIT 5 & 6

Q-1. What are Regular Expressions? Explain the use of Regular Expressions for file
processing.
Ans.
A Regular Expression (regex) is a sequence of characters that defines a search pattern. Python
provides the re module for working with regex.
import re

Common re functions:
• [Link](pattern, string) – checks at beginning of string
• [Link](pattern, string) – scans entire string
• [Link](pattern, string) – returns all matches as list
• [Link](pattern, repl, string) – replaces matches
• [Link](pattern, string) – splits string by pattern

File Processing with Regex:

Python Programming – Solved Paper | Page 18


import re

# Read log file and extract IP addresses


with open('[Link]', 'r') as f:
content = [Link]()

ip_pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
ips = [Link](ip_pattern, content)
print('IP Addresses found:', ips)

# Extract email addresses from a file


email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
with open('[Link]', 'r') as f:
for line in f:
emails = [Link](email_pattern, line)
for email in emails:
print(email)

# Replace phone numbers in a file


phone_pattern = r'\b\d{10}\b'
with open('[Link]', 'r') as f:
data = [Link]()
cleaned = [Link](phone_pattern, '[REDACTED]', data)
with open('[Link]', 'w') as f:
[Link](cleaned)

Q-2. Explain Sequence Characters, Quantifiers, and Special Characters in Regex.


Ans.
A. Special Sequence Characters:
Sequence Meaning Example Match
\d Digit 0-9 7, 3, 9
\D Non-digit a, B, !
\w Word char (a-z, A-Z, 0-9, _) Python_3
\W Non-word character !, @, space
\s Whitespace space, tab, newline
\S Non-whitespace hello, 123
\b Word boundary \\bhello\\b
\A Start of string \\APython
\Z End of string end\\Z

B. Quantifiers:
Quantifier Meaning Example
* 0 or more ab* → a, ab, abb
+ 1 or more ab+ → ab, abb
? 0 or 1 colou?r → color or colour

Python Programming – Solved Paper | Page 19


{n} Exactly n \\d{4} → 2024
{n,} n or more \\d{3,} → 123, 1234
{n,m} Between n and m \\d{2,4} → 12, 123, 1234

C. Special Characters:
• . (dot) – matches any character except newline
• ^ – start of string or negation in character class
• $ – end of string
• [] – character class: [aeiou], [a-z], [^0-9]
• | – OR: cat|dog matches 'cat' or 'dog'
• () – grouping and capturing
• \ – escape special character
import re
# Validate email
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
email = 'student@[Link]'
if [Link](pattern, email):
print('Valid email')
else:
print('Invalid email')

Q-3. Explain Python Database Connectivity Architecture.


Ans.
Python uses DB-API 2.0 (PEP 249) standard to connect to databases. It provides a consistent interface
regardless of the database used.

Architecture Diagram:
┌──────────────────────────────────────────────────────────┐
│ Python Application │
└─────────────────────────┬────────────────────────────────┘
│ uses
┌─────────────────────────▼────────────────────────────────┐
│ Python DB-API 2.0 Interface │
│ (connect, cursor, execute, fetchall, commit, close) │
└─────────────────────────┬────────────────────────────────┘

┌─────────────────────────▼────────────────────────────────┐
│ Database Driver / Connector │
│ mysql-connector-python / PyMySQL / psycopg2 / sqlite3 │
└─────────────────────────┬────────────────────────────────┘

┌─────────────────────────▼────────────────────────────────┐
│ Database Server │
│ MySQL / PostgreSQL / SQLite / Oracle │
└──────────────────────────────────────────────────────────┘

Steps in DB Connectivity:
• 1. Install the connector: pip install mysql-connector-python
• 2. Import the module: import [Link]

Python Programming – Solved Paper | Page 20


• 3. Establish connection: conn = [Link](...)
• 4. Create cursor: cursor = [Link]()
• 5. Execute SQL query: [Link]('SELECT * FROM students')
• 6. Fetch results: rows = [Link]()
• 7. Commit changes: [Link]() (for INSERT/UPDATE/DELETE)
• 8. Close resources: [Link](); [Link]()

Q-4. Write a program to Insert, Update, Delete, and Retrieve records using Python and
MySQL.
Ans.
import [Link]

# Establish connection
conn = [Link](
host='localhost',
user='root',
password='password',
database='school'
)
cursor = [Link]()

# ── CREATE TABLE ──────────────────────────────────────────


[Link]('''
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT,
marks FLOAT
)
''')

# ── INSERT ────────────────────────────────────────────────
[Link]('INSERT INTO students (name, age, marks) VALUES (%s,
%s, %s)',
('Raj Patel', 21, 88.5))
[Link]('INSERT INTO students (name, age, marks) VALUES (%s,
%s, %s)',
('Priya Shah', 20, 92.0))
[Link]()
print('Records inserted.')

# ── RETRIEVE ──────────────────────────────────────────────
[Link]('SELECT * FROM students')
rows = [Link]()
print('\n-- All Records --')
for row in rows:
print(row)

# ── UPDATE ────────────────────────────────────────────────
[Link]('UPDATE students SET marks = %s WHERE name = %s',
(95.0, 'Raj Patel'))
[Link]()
print('\nRecord updated.')

Python Programming – Solved Paper | Page 21


# ── DELETE ────────────────────────────────────────────────
[Link]('DELETE FROM students WHERE age < %s', (21,))
[Link]()
print('Record(s) deleted.')

# ── RETRIEVE AGAIN ────────────────────────────────────────


[Link]('SELECT * FROM students')
rows = [Link]()
print('\n-- Records After Delete --')
for row in rows:
print(row)

# ── CLOSE ─────────────────────────────────────────────────
[Link]()
[Link]()
print('\nConnection closed.')

Q-5. Explain Creating Database Tables through Python.


Ans.
import [Link]

conn = [Link](
host='localhost',
user='root',
password='password',
database='college'
)
cursor = [Link]()

# Create DEPARTMENT table


[Link]('''
CREATE TABLE IF NOT EXISTS department (
dept_id INT PRIMARY KEY AUTO_INCREMENT,
dept_name VARCHAR(100) NOT NULL,
location VARCHAR(100)
)
''')

# Create STUDENT table with foreign key


[Link]('''
CREATE TABLE IF NOT EXISTS student (
roll_no INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE,
age INT CHECK(age >= 15 AND age <= 30),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES department(dept_id)
)
''')

[Link]()
print('Tables created successfully!')

Python Programming – Solved Paper | Page 22


# List all tables
[Link]('SHOW TABLES')
tables = [Link]()
print('Tables in database:')
for t in tables:
print(' -', t[0])

[Link]()
[Link]()

Q-6. Explain Cursor and Connection objects in Python Database Programming.


Ans.
1. Connection Object
The connection object is created using the connect() method and represents a single database session.
Key Connection Methods:
Method Description
connect() Establishes DB connection
cursor() Returns a cursor object
commit() Commits current transaction
rollback() Rolls back to last commit
close() Closes the connection

2. Cursor Object
The cursor object is used to execute SQL queries and manage results.
Method Description
execute(sql, args) Executes a single SQL query
executemany(sql, list) Executes query for a list of data
fetchone() Returns next single row
fetchall() Returns all remaining rows
fetchmany(n) Returns next n rows
rowcount Number of rows affected
description Column names of result set
close() Closes the cursor

Complete Example:
import [Link]

# Connection object
conn = [Link](
host='localhost', user='root',
password='password', database='school'
)

Python Programming – Solved Paper | Page 23


# Cursor object
cursor = [Link]()

# Execute query
[Link]('SELECT * FROM students WHERE marks > %s', (75,))

# fetchall
rows = [Link]()
print('Columns:', [desc[0] for desc in [Link]])
print('Rows affected:', [Link])
for row in rows:
print(row)

# Close resources
[Link]()
[Link]()

Python Programming – Solved Paper | Page 24

You might also like