0% found this document useful (0 votes)
2 views147 pages

Python

The document outlines key differences between syntax errors and exceptions in Python, highlighting that syntax errors occur before execution while exceptions happen during execution. It discusses the utility of docstrings, the relationship between tuples and lists, and various string formatting methods. Additionally, it covers tuple creation, negative indexing, string splitting, the range() function, and characteristics of sets and dictionaries.
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)
2 views147 pages

Python

The document outlines key differences between syntax errors and exceptions in Python, highlighting that syntax errors occur before execution while exceptions happen during execution. It discusses the utility of docstrings, the relationship between tuples and lists, and various string formatting methods. Additionally, it covers tuple creation, negative indexing, string splitting, the range() function, and characteristics of sets and dictionaries.
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

✅ 9 (b) Difference between Syntax Error and Exception

Feature Syntax Error Exception


Meaning Error in writing code Error during execution
Occurs when Python cannot understand code Code runs but something goes wrong
Example Missing colon Division by zero
Stage Before execution During execution

🔹 Example
✔ Syntax Error
if x > 5
print(x)
👉 Missing : → Syntax error

✔ Exception
x=5/0
👉 Runtime error → ZeroDivisionError

🔑 Utility of Docstrings
 Self-documentation: They explain what a function, class, or module does without needing
external notes.
 Readability: Makes code more understandable for others (or for yourself later).
 Interactive help: Tools like help() and IDEs display docstrings, so you can quickly see usage
details.
 Testing: Python’s doctest module can run examples written inside docstrings as tests.
 Standardization: Following conventions (like PEP 257 or NumPy/Google style) ensures
consistent documentation across projects.
🔹 What is Docstring?
 A docstring is a string used to describe a function, module, or class
 Written inside triple quotes (""" """)

🔹 Example
def add(a, b):
"""This function returns sum of two numbers"""
return a + b
relation Between Tuples and Lists in Python
Tuples and Lists are both sequence data types in Python. They are closely related because both are
used to store collections of elements.
Similarities Between Tuple and List
1. Both Store Multiple Values
list1 = [1, 2, 3]
tuple1 = (1, 2, 3)
2. Ordered Collection
o Elements maintain insertion order.
3. Indexing and Slicing Supported
a = [10, 20, 30]
b = (10, 20, 30)

print(a[1]) # 20
print(b[1]) # 20
4. Allow Duplicate Elements
[1, 1, 2]
(1, 1, 2)
5. Can Store Different Data Types
[1, "Python", 3.5]
(1, "Python", 3.5)
6. Iterable
o Both can be used in loops.
for x in (1,2,3):
print(x)

Difference Between Tuple and List


Feature List Tuple
Symbol [] ()
Mutability Mutable Immutable
Size Change Can add/remove items Cannot change items
Speed Slower Faster
Memory More memory Less memory
Dictionary Key Cannot be key Can be key

Conversion Between Tuple and List


List to Tuple
l = [1, 2, 3]
t = tuple(l)

print(t)
Tuple to List
t = (1, 2, 3)
l = list(t)

print(l)

Relationship in Simple Words


 A tuple is almost like a list, but it is read-only (immutable).
 Lists are used when data may change.
 Tuples are used when data should remain fixed and secure.

how will you create tupless?


Creating Tuples in Python
A tuple is created by placing elements inside parentheses () separated by commas.
1. Creating an Empty Tuple
t = ()
print(t)
Output:
()

2. Creating a Tuple with Elements


t = (1, 2, 3, 4)
print(t)
Output:
(1, 2, 3, 4)

3. Tuple with Different Data Types


t = (10, "Python", 3.5, True)
print(t)
Output:
(10, 'Python', 3.5, True)

4. Creating a Single Element Tuple


For a single element tuple, a comma is necessary.
t = (5,)
print(t)
Output:
(5,)

There is no use of + operator in python strings."- comment


The statement "There is no use of + operator in Python strings" is incorrect.
In Python, the + operator is used with strings for concatenation, which means joining two or more
strings together.
Use of + Operator in Strings
Example
str1 = "Hello"
str2 = "World"

result = str1 + " " + str2

print(result)
Output
Hello World
Here, the + operator combines the strings "Hello" and "World" into a single string.

Identify different strings formats available in python with example


Different String Formats Available in Python
Python provides several ways to format strings.
1. Old Style Formatting (% Operator)
This is the traditional method of string formatting.
Example
name = "Rahul"
age = 20

print("My name is %s and age is %d" % (name, age))


Output
My name is Rahul and age is 20
Common Format Specifiers
Specifier Meaning
%s String
%d Integer
%f Float

2. format() Method
Introduced in Python 3 for better readability.
Example
name = "Rahul"
age = 20

print("My name is {} and age is {}".format(name, age))


Output
My name is Rahul and age is 20
Indexed Formatting
print("Name: {0}, Age: {1}".format("Rahul", 20))

3. f-Strings (Formatted String Literals)


Introduced in Python 3.6. This is the easiest and fastest method.
Example
name = "Rahul"
age = 20

print(f"My name is {name} and age is {age}")


Output
My name is Rahul and age is 20
Expression Inside f-String
a = 10
b = 20

print(f"Sum = {a+b}")
Output:
Sum = 30
4. String Concatenation Using +
Strings can also be joined using the + operator.
Example
name = "Rahul"

print("Hello " + name)


Output
Hello Rahul

5. Template Strings
Python provides the Template class from the string module.
Example
from string import Template

t = Template("Hello $name")
print([Link](name="Rahul"))
Output
Hello Rahul

Briefly discuss about negative indexing in Python string.


Negative Indexing in Python String
Negative indexing is a method in Python used to access characters of a string from the end of the
string.
 Positive indexing starts from 0 from the left side.
 Negative indexing starts from -1 from the right side.

Example
s = "PYTHON"

print(s[-1])
print(s[-2])
print(s[-3])
Output
N
O
H
Uses of Negative Indexing
1. Access characters from the end easily.
2. Useful in string slicing.
3. Reduces need to calculate string length.

Example of Slicing with Negative Indexing


s = "COMPUTER"

print(s[-4:])
Output
UTER

discuss the method to split python strings. What is the function used to perform the said
operation? Give examples
Splitting Strings in Python
Splitting a string means breaking a string into smaller parts based on a separator such as space,
comma, or any other character.
Python provides the split() function to perform this operation.

Function Used
split() Function
Syntax
[Link](separator, maxsplit)
Parameters
Parameter Meaning
separator Character used to split the string
maxsplit Maximum number of splits
 Both parameters are optional.

How split() Works


 The function divides the string wherever the separator occurs.
 It returns the result as a list.

Examples
1. Splitting by Space (Default)
s = "Python is easy"

result = [Link]()

print(result)
Output
['Python', 'is', 'easy']
Explanation
 By default, split() uses space as the separator.

2. Splitting Using Comma


s = "apple,banana,mango"

result = [Link](",")

print(result)
Output
['apple', 'banana', 'mango']

3. Using maxsplit
s = "one two three four"

result = [Link](" ", 2)

print(result)
Output
['one', 'two', 'three four']
Explanation
 Only 2 splits are performed.

Advantages of split()
1. Separates words easily.
2. Useful for processing user input.
3. Converts strings into lists.
what is the purpose of range() function and how it is used in list type?
Purpose of range() Function in Python
The range() function is used to generate a sequence of numbers.
It is commonly used in loops and for creating lists of numbers.

Syntax of range()
range(start, stop, step)
Parameters
Parameter Meaning
start Starting value (default = 0)
stop Ending value (excluded)
step Difference between consecutive numbers

Purpose of range()
1. Generates a sequence of integers.
2. Used in loops (for loop).
3. Helps create lists easily.
4. Saves memory because it generates values lazily.

Using range() with List Type


The range() function itself does not create a list directly in Python 3.
To convert it into a list, we use the list() function.

Examples
1. Creating a List of Numbers
x = list(range(5))

print(x)
Output
[0, 1, 2, 3, 4]
Explanation
 Starts from 0
 Ends before 5

2. Using Start and Stop


x = list(range(2, 8))

print(x)
Output
[2, 3, 4, 5, 6, 7]

3. Using Step Value


x = list(range(1, 10, 2))

print(x)
Output
[1, 3, 5, 7, 9]
Explanation
 Numbers increase by 2.

Using range() in Loop


for i in range(5):
print(i)
Output
0
1
2
3
4

1. Tuples
Definition
A tuple is an ordered collection of elements enclosed within parentheses ( ).
 Tuples can store different data types.
 Tuples are immutable (cannot be modified after creation).
 Duplicate elements are allowed.
 Indexing and slicing are supported.
Syntax
t = (10, 20, 30)
Example
t = (10, "Python", 5.6)
print(t)
Output
(10, 'Python', 5.6)
Characteristics of Tuples
1. Ordered collection
2. Immutable
3. Allows duplicate values
4. Supports indexing and slicing
5. Can contain heterogeneous data

2. Creating Tuples
Method 1: Using Parentheses
t = (1, 2, 3)
Method 2: Without Parentheses
t = 1, 2, 3
Python automatically treats it as a tuple.

Empty Tuple
t = ()

Single Element Tuple


t = (5,)
Comma is mandatory.
Wrong:
t = (5)
This is an integer, not a tuple.

3. Basic Tuple Operations


Concatenation
Joining tuples using +.
t1 = (1,2,3)
t2 = (4,5,6)

t3 = t1 + t2

print(t3)
Output:
(1, 2, 3, 4, 5, 6)

Repetition
Using *
t = (1,2)

print(t*3)
Output:
(1, 2, 1, 2, 1, 2)

Membership
t = (10,20,30)

print(20 in t)
Output
True

Length
t = (10,20,30)

print(len(t))
Output
3

4. Indexing in Tuples
Indexing starts from 0.
t = (10,20,30,40)

print(t[0])
print(t[2])
Output
10
30

Negative Indexing
t = (10,20,30,40)

print(t[-1])
Output
40

5. Slicing in Tuples
Syntax
tuple[start:end:step]

Example
t = (10,20,30,40,50)

print(t[1:4])
Output
(20, 30, 40)
Reverse Tuple
t = (10,20,30,40)

print(t[::-1])
Output
(40, 30, 20, 10)

6. Built-in Functions on Tuples


len()
Returns number of elements.
len((1,2,3))
Output
3

max()
Returns largest value.
max((5,10,15))
Output
15

min()
Returns smallest value.
min((5,10,15))
Output
5

sum()
Returns sum of elements.
sum((1,2,3))
Output
6

sorted()
Returns sorted list.
t=(5,2,8)

print(sorted(t))
Output
[2,5,8]

7. Tuple Methods
Tuple has only two methods.

count()
Counts occurrences.
t=(1,2,3,2,2)

print([Link](2))
Output
3

index()
Returns first occurrence position.
t=(10,20,30)

print([Link](20))
Output
1

8. Relation Between Tuples and Lists


Tuple List
Immutable Mutable
() used [] used
Faster Slower
Less memory More memory
Only count(), index() Many methods

List to Tuple Conversion


L=[1,2,3]

T=tuple(L)

print(T)
Output
(1,2,3)

Tuple to List Conversion


T=(1,2,3)

L=list(T)

print(L)
Output
[1,2,3]

9. Relation Between Tuples and Dictionaries


Dictionary items can be converted to tuples.
d={
"A":1,
"B":2
}

print(tuple([Link]()))
Output
(('A',1),('B',2))

Tuples as Dictionary Keys


Since tuples are immutable, they can be dictionary keys.
d={
(1,2):"Python"
}

print(d[(1,2)])
Output
Python

10. Packing and Unpacking of Tuples


Packing
t = 10,20,30

Unpacking
a,b,c = t

print(a)
print(b)
print(c)
Output
10
20
30

11. Zip() Function


Definition
zip() combines elements from multiple iterables into tuples.
Syntax
zip(iterable1, iterable2)

Example
name = ["A","B","C"]
marks = [80,85,90]

z = list(zip(name,marks))

print(z)
Output
[('A',80),('B',85),('C',90)]

Creating Dictionary using zip()


name = ["A","B","C"]
marks = [80,85,90]

d = dict(zip(name,marks))

print(d)
Output
{'A':80,'B':85,'C':90}

12. Sets
Definition
A set is an unordered collection of unique elements.
 Written using { }
 Duplicate values are not allowed.
 Mutable.
 No indexing.

Creating Sets
s = {1,2,3,4}

Empty Set
Wrong:
s = {}
Creates dictionary.
Correct:
s = set()

Characteristics of Sets
1. Unordered
2. Mutable
3. No duplicate elements
4. No indexing
5. Mathematical set operations possible

13. Set Operations


Union
A={1,2,3}
B={3,4,5}

print(A|B)
Output
{1,2,3,4,5}

Intersection
print(A&B)
Output
{3}

Difference
print(A-B)
Output
{1,2}

Symmetric Difference
print(A^B)
Output
{1,2,4,5}

14. Set Methods


add()
s={1,2}

[Link](3)

update()
s={1,2}

[Link]([3,4])

remove()
[Link](2)
Error if element absent.

discard()
[Link](2)
No error if absent.

pop()
Removes arbitrary element.
[Link]()

clear()
[Link]()
Removes all elements.

copy()
s2=[Link]()

15. Membership in Sets


s={10,20,30}

print(20 in s)
Output
True

16. Frozen Set


Definition
A frozenset is an immutable version of a set.
Once created, elements cannot be added or removed.
Syntax
fs = frozenset([1,2,3])

Example
fs = frozenset([1,2,3])

print(fs)
Output
frozenset({1, 2, 3})

Properties of Frozenset
1. Immutable
2. Hashable
3. Can be dictionary key
4. Supports union, intersection, difference

Example
A = frozenset([1,2,3])
B = frozenset([3,4,5])

print([Link](B))
Output
frozenset({1,2,3,4,5})

Difference Between Set and Frozen Set


Set Frozen Set
Mutable Immutable
add() allowed add() not allowed
remove() allowed remove() not allowed
Cannot be dict key Can be dict key
set() frozenset()
1. Dictionary
Definition
A dictionary is an unordered collection of data stored in the form of key-value pairs.
 Keys are unique.
 Values may be duplicated.
 Dictionary is mutable (can be modified).
 Written using curly braces {}.
 Accessing elements is done using keys, not indexes.
Syntax
dictionary_name = {
key1:value1,
key2:value2,
key3:value3
}
Example
student = {
"Name":"Rahul",
"Age":20,
"Marks":85
}

print(student)
Output
{'Name': 'Rahul', 'Age': 20, 'Marks': 85}

2. Characteristics of Dictionary
1. Stores data as Key-Value pairs
student = {
"Name":"Amit",
"Age":21
}

2. Keys must be unique


d={
"A":10,
"A":20
}

print(d)
Output:
{'A':20}
The second value overwrites the first one.
3. Values may be duplicated
d={
"A":100,
"B":100
}
Valid dictionary.

4. Mutable
d = {"A":10}

d["A"] = 50
Value is modified.

5. Heterogeneous Data Allowed


d={
"Name":"Python",
"Version":3.12,
"Popular":True
}

3. Creating Dictionaries
Method 1: Using Curly Braces
d={
"A":1,
"B":2
}

Method 2: Using dict()


d = dict(A=1, B=2)

print(d)
Output
{'A':1,'B':2}

Method 3: Using List of Tuples


d = dict([
("A",1),
("B",2)
])

print(d)
Output
{'A':1,'B':2}

Method 4: Using zip()


keys = ["A","B","C"]
values = [10,20,30]

d = dict(zip(keys,values))

print(d)
Output
{'A':10,'B':20,'C':30}

Empty Dictionary
d = {}
or
d = dict()

4. Accessing Dictionary Elements


Since dictionaries do not use indexes, elements are accessed using keys.
Method 1: Using []
student = {
"Name":"Rahul",
"Age":20
}

print(student["Name"])
Output
Rahul

KeyError
print(student["Marks"])
Output
KeyError
because key does not exist.

Method 2: Using get()


student = {
"Name":"Rahul"
}

print([Link]("Name"))
Output
Rahul

Advantage of get()
print([Link]("Marks"))
Output
None
No error occurs.

Default Value
print([Link]("Marks","Not Found"))
Output
Not Found

5. Modifying Dictionary Values


Updating Existing Value
student = {
"Age":20
}

student["Age"] = 21

print(student)
Output
{'Age':21}

Adding New Key-Value Pair


student = {
"Name":"Rahul"
}

student["Marks"] = 90

print(student)
Output
{'Name':'Rahul','Marks':90}

Deleting Elements
Using del
student = {
"Name":"Rahul",
"Age":20
}

del student["Age"]

print(student)
Output
{'Name':'Rahul'}

6. Built-in Functions Used on Dictionaries


len()
Returns number of key-value pairs.
d={
"A":1,
"B":2,
"C":3
}

print(len(d))
Output
3

type()
d = {"A":1}

print(type(d))
Output
<class 'dict'>

str()
Converts dictionary to string.
d = {"A":1}

print(str(d))
Output
"{'A':1}"

dict()
Creates dictionary.
d = dict()

max()
Returns largest key.
d={
"A":10,
"B":20,
"C":30
}

print(max(d))
Output
C

min()
Returns smallest key.
print(min(d))
Output
A

sorted()
Returns sorted keys.
print(sorted(d))
Output
['A','B','C']

sum()
Works when keys are numeric.
d={
1:"A",
2:"B",
3:"C"
}

print(sum(d))
Output
6

7. Dictionary Methods
Dictionary methods are very important for CU exams.

1. keys()
Returns all keys.
d={
"A":1,
"B":2
}

print([Link]())
Output
dict_keys(['A','B'])

2. values()
Returns all values.
print([Link]())
Output
dict_values([1,2])

3. items()
Returns key-value pairs as tuples.
print([Link]())
Output
dict_items([('A',1),('B',2)])

4. get()
Returns value associated with key.
[Link]("A")
Output
1

5. update()
Updates dictionary.
d={
"A":1
}

[Link]({"B":2})

print(d)
Output
{'A':1,'B':2}

6. pop()
Removes specified key.
d={
"A":1,
"B":2
}

[Link]("A")
Output
1
Dictionary becomes
{'B':2}

7. popitem()
Removes last inserted item.
d={
"A":1,
"B":2
}

[Link]()
Output
('B',2)
8. clear()
Removes all elements.
[Link]()
Output
{}

9. copy()
Creates shallow copy.
d2 = [Link]()

10. setdefault()
Returns value if key exists; otherwise inserts key.
d={
"A":10
}

print([Link]("A"))
Output
10

If key does not exist:


print([Link]("B",20))
Output
20
Dictionary becomes:
{'A':10,'B':20}

11. fromkeys()
Creates dictionary from sequence of keys.
keys = ["A","B","C"]

d = [Link](keys,0)

print(d)
Output
{'A':0,'B':0,'C':0}

8. Traversing a Dictionary
Using for Loop
d={
"A":10,
"B":20
}
for key in d:
print(key,d[key])
Output
A 10
B 20

Using items()
for key,value in [Link]():
print(key,value)
Output
A 10
B 20

9. Dictionary Comprehension
Syntax
{key:value for item in iterable}
Example
square = {
x:x*x
for x in range(1,6)
}

print(square)
Output
{1:1,2:4,3:9,4:16,5:25}

10. Difference Between List, Tuple and Dictionary


List Tuple Dictionary
[] () {}
Ordered Ordered Key-Value Pair
Mutable Immutable Mutable
Index Access Index Access Key Access
Duplicate allowed Duplicate allowed Keys unique

Difference Between Set and Dictionary in Python


Feature Set Dictionary
A set is an unordered collection of A dictionary is an unordered collection of
Definition
unique elements. key-value pairs.
Syntax {1, 2, 3} {"A": 1, "B": 2}
Storage Stores only values. Stores key-value pairs.
Duplicate Duplicate keys not allowed, but duplicate
Not allowed.
Elements values allowed.
Cannot access elements using keys or
Access Method Elements are accessed using keys.
indexes.
Feature Set Dictionary
Mutability Mutable. Mutable.
Indexing Not supported. Not supported (uses keys instead).
Empty Structure set() {} or dict()
Membership Test Checks if an element exists in the set. Checks if a key exists in the dictionary.
Common Union, Intersection, Difference, Search, insert, update, delete key-value
Operations Symmetric Difference. pairs.

2(a) Explain the basic data types available in Python with examples. (4 Marks)
Python provides several built-in data types:
Data Type Description Example
int Integer numbers x = 10
float Decimal numbers y = 3.14
complex Complex numbers z = 2+3j
str Sequence of characters name = "Python"
list Ordered mutable collection L = [1,2,3]
tuple Ordered immutable collection T = (1,2,3)
set Unordered collection of unique elements S = {1,2,3}
dict Collection of key-value pairs D = {"A":1,"B":2}
bool Logical values flag = True
Example:
a = 10 # int
b = 3.5 # float
c = "Hello" # string
d = [1,2,3] # list
e = True # boolean

1. What is a File?
A file is a named location on a storage device used to store data permanently.
Need for Files
 Data stored in variables is temporary.
 Data is lost when the program terminates.
 Files provide permanent storage.

2. Types of Files
Python mainly supports two types of files:
A. Text Files
Stores data in human-readable form.
Examples:
[Link]
[Link]
[Link]
Contents:
Rahul
20
Kolkata
Characteristics
 Stores characters.
 Can be opened with text editors.
 Easy to read.

B. Binary Files
Stores data in binary format (0s and 1s).
Examples:
[Link]
audio.mp3
[Link]
Characteristics
 Not human readable.
 Faster than text files.
 Used for images, videos, objects, etc.

Difference Between Text and Binary Files


Text File Binary File
Human readable Not human readable
Stores characters Stores bytes
Slower Faster
Uses .txt, .csv Uses .dat, .bin
Easier to edit Difficult to edit

3. Opening a File
Python uses open().
Syntax
file_object = open(filename, mode)
Example:
f = open("[Link]", "r")

File Modes
Mode Meaning
r Read
w Write
a Append
x Create
r+ Read and Write
rb Read Binary
wb Write Binary
Mode Meaning

ab Append Binary

4. Creating and Writing Text Data


Using Write Mode
f = open("[Link]", "w")

[Link]("Rahul\n")
[Link]("Computer Science")

[Link]()
Output in file
Rahul
Computer Science

5. Reading Text Data


read()
Reads complete file.
f = open("[Link]", "r")

data = [Link]()

print(data)

[Link]()
Output:
Rahul
Computer Science

readline()
Reads one line at a time.
f = open("[Link]", "r")

print([Link]())
print([Link]())

[Link]()
Output:
Rahul
Computer Science

readlines()
Returns list of lines.
f = open("[Link]", "r")

print([Link]())

[Link]()
Output:
['Rahul\n', 'Computer Science']

6. File Methods Used for Reading and Writing


write()
Writes data.
[Link]("Hello")

writelines()
Writes multiple lines.
[Link]([
"A\n",
"B\n",
"C\n"
])

read()
Reads complete file.
[Link]()

readline()
Reads one line.
[Link]()

readlines()
Reads all lines.
[Link]()

close()
Closes file.
[Link]()

7. Append Data
Using mode a.
f = open("[Link]", "a")

[Link]("\nPython")

[Link]()
File becomes:
Rahul
Computer Science
Python

8. Using with Statement


Best way to handle files.
with open("[Link]","r") as f:
print([Link]())
Advantage
Automatically closes file.

9. Reading and Writing Binary Files


Binary files are opened using:
rb
wb
ab

Writing Binary File


f = open("[Link]","wb")

[Link](b"Python")

[Link]()

Reading Binary File


f = open("[Link]","rb")

data = [Link]()

print(data)

[Link]()
Output:
b'Python'

10. Pickle Module


Definition
The pickle module is used to store Python objects into binary files and retrieve them later.
This process is called:
Pickling
Converting Python object → Binary File
Unpickling
Binary File → Python Object

Import Pickle
import pickle

Writing Objects Using Pickle


import pickle

student = {
"Name":"Rahul",
"Age":20
}

f = open("[Link]","wb")

[Link](student,f)

[Link]()

Reading Objects Using Pickle


import pickle

f = open("[Link]","rb")

data = [Link](f)

print(data)

[Link]()
Output:
{'Name':'Rahul','Age':20}

Advantages of Pickle
1. Stores complete Python objects.
2. Faster than text files.
3. Easy retrieval of objects.

11. CSV Files


CSV = Comma Separated Values
Example:
Name,Age,City
Rahul,20,Kolkata
Amit,21,Delhi

Writing CSV File


import csv

f = open("[Link]","w",newline="")
writer = [Link](f)

[Link](["Name","Age","City"])

[Link](["Rahul",20,"Kolkata"])

[Link]()

Reading CSV File


import csv

f = open("[Link]","r")

reader = [Link](f)

for row in reader:


print(row)

[Link]()
Output:
['Name', 'Age', 'City']
['Rahul', '20', 'Kolkata']

CSV Dictionary Format


Writing
import csv

f = open("[Link]","w",newline="")

writer = [Link](
f,
fieldnames=["Name","Age"]
)

[Link]()

[Link]({
"Name":"Rahul",
"Age":20
})

[Link]()

12. Python os Module


The os module provides functions for interacting with the operating system.
Import
import os

Common os Functions
getcwd()
Current working directory.
import os

print([Link]())

mkdir()
Create directory.
[Link]("Python")

rmdir()
Remove directory.
[Link]("Python")

listdir()
List files and folders.
print([Link]())

rename()
Rename file/folder.
[Link](
"[Link]",
"[Link]"
)

remove()
Delete file.
[Link]("[Link]")

13. [Link] Module


Used for path-related operations.
Import
import [Link]

Common [Link] Functions


exists()
Checks whether file exists.
import [Link]

print(
[Link](
"[Link]"
)
)
Output:
True

isfile()
Checks whether path is a file.
[Link](
"[Link]"
)
Output:
True

isdir()
Checks whether path is directory.
[Link](
"Python"
)
Output:
True

getsize()
Returns file size.
[Link](
"[Link]"
)
Output:
25

basename()
Returns file name.
[Link](
"C:/Python/[Link]"
)
Output:
[Link]

dirname()
Returns directory path.
[Link](
"C:/Python/[Link]"
)
Output:
C:/Python

1. Discuss File Handling in Python with Suitable Examples


Definition
File handling is the process of creating, opening, reading, writing, and closing files. It allows data to
be stored permanently on secondary storage devices.
Why File Handling is Needed
 Data stored in variables is temporary.
 Data is lost when the program ends.
 Files provide permanent storage of data.

Steps in File Handling


1. Open the File
f = open("[Link]", "r")
2. Perform Operations
 Read
 Write
 Append
3. Close the File
[Link]()

Example: Writing and Reading a File


# Writing data
f = open("[Link]", "w")
[Link]("Rahul")
[Link]()

# Reading data
f = open("[Link]", "r")
print([Link]())
[Link]()
Output
Rahul

File Modes
Mode Meaning
r Read
w Write
a Append
r+ Read and Write
rb Read Binary
wb Write Binary

Conclusion
File handling enables permanent storage and retrieval of data and is essential for real-world
applications.

2. Explain Text and Binary Files and Their Operations


Text Files
A text file stores data in the form of characters.
Examples:
[Link]
[Link]
Writing to a Text File
f = open("[Link]", "w")
[Link]("Python Programming")
[Link]()
Reading a Text File
f = open("[Link]", "r")
print([Link]())
[Link]()

Binary Files
Binary files store data in the form of bytes.
Examples:
[Link]
video.mp4
[Link]
Writing Binary Data
f = open("[Link]", "wb")
[Link](b"Python")
[Link]()
Reading Binary Data
f = open("[Link]", "rb")
print([Link]())
[Link]()
Output:
b'Python'

Difference Between Text and Binary Files


Text File Binary File
Stores characters Stores bytes
Human readable Not human readable
Uses r, w, a Uses rb, wb, ab
Slower Faster

3. Explain Pickle Module with Examples


Definition
The pickle module is used to store Python objects into binary files and retrieve them later.
Pickling
Converting Python object → Binary file
Unpickling
Converting Binary file → Python object

Importing Pickle Module


import pickle

Example: Pickling
import pickle

student = {
"Name": "Rahul",
"Age": 20
}

f = open("[Link]", "wb")

[Link](student, f)

[Link]()
Explanation
 dump() writes the Python object into a binary file.

Example: Unpickling
import pickle

f = open("[Link]", "rb")

data = [Link](f)

print(data)

[Link]()
Output
{'Name': 'Rahul', 'Age': 20}

Advantages of Pickle
1. Stores complete Python objects.
2. Faster than text files.
3. Preserves object structure.

4. Discuss CSV File Handling in Python


Definition
CSV stands for Comma Separated Values.
Example CSV file:
Name,Age,City
Rahul,20,Kolkata
Amit,21,Delhi

Import CSV Module


import csv

Writing CSV File


import csv

f = open("[Link]", "w", newline="")

writer = [Link](f)

[Link](["Name", "Age", "City"])


[Link](["Rahul", 20, "Kolkata"])

[Link]()

Reading CSV File


import csv

f = open("[Link]", "r")

reader = [Link](f)

for row in reader:


print(row)

[Link]()
Output
['Name', 'Age', 'City']
['Rahul', '20', 'Kolkata']

Advantages of CSV
1. Easy data storage.
2. Compatible with Excel.
3. Efficient for tabular data.

5. Explain os and [Link] Modules with Examples


os Module
The os module provides functions to interact with the operating system.
Import
import os

Important Functions of os Module


getcwd()
Returns current working directory.
import os

print([Link]())

listdir()
Displays files and folders.
import os

print([Link]())

mkdir()
Creates a directory.
[Link]("Python")

rmdir()
Removes a directory.
[Link]("Python")

remove()
Deletes a file.
[Link]("[Link]")

[Link] Module
The [Link] module performs path-related operations.
Import
import [Link]

Important Functions of [Link]


exists()
Checks whether a file exists.
import [Link]

print([Link]("[Link]"))
Output:
True

isfile()
Checks whether path is a file.
[Link]("[Link]")
Output:
True

isdir()
Checks whether path is a directory.
[Link]("Python")
Output:
True

getsize()
Returns file size.
[Link]("[Link]")

basename()
Returns file name.
[Link]("C:/Python/[Link]")
Output:
[Link]

dirname()
Returns directory path.
[Link]("C:/Python/[Link]")
Output:
C:/Python

Lists in Python (Complete CU Honors Exam Notes)


A List is one of the most commonly used data structures in Python. It is used to store multiple items
in a single variable.

1. Creating Lists
Definition
A list is an ordered, mutable collection of elements enclosed within square brackets [ ].
Characteristics
 Ordered
 Mutable (can be modified)
 Allows duplicate values
 Supports indexing and slicing
 Can store different data types

Creating a List
L = [10, 20, 30, 40]
print(L)
Output:
[10, 20, 30, 40]

Mixed Data Type List


L = [10, "Python", 3.14, True]
print(L)
Output:
[10, 'Python', 3.14, True]

Empty List
L = []
or
L = list()

2. Basic List Operations


Concatenation (+)
L1 = [1, 2]
L2 = [3, 4]

print(L1 + L2)
Output:
[1, 2, 3, 4]

Repetition (*)
L = [1, 2]

print(L * 3)
Output:
[1, 2, 1, 2, 1, 2]

Membership Operator
L = [10, 20, 30]

print(20 in L)
Output:
True

Length
L = [1, 2, 3, 4]

print(len(L))
Output:
4

3. Indexing in Lists
Indexing starts from 0.
L = [10, 20, 30, 40]
print(L[0])
print(L[2])
Output:
10
30

Negative Indexing
L = [10, 20, 30, 40]

print(L[-1])
Output:
40

4. Slicing in Lists
Syntax
list[start:end:step]

Example
L = [10, 20, 30, 40, 50]

print(L[1:4])
Output:
[20, 30, 40]

Reverse a List
L = [10, 20, 30, 40]

print(L[::-1])
Output:
[40, 30, 20, 10]

5. Built-in Functions Used on Lists


len()
L = [1, 2, 3]

print(len(L))
Output:
3

max()
L = [5, 10, 15]

print(max(L))
Output:
15
min()
print(min(L))
Output:
5

sum()
print(sum(L))
Output:
30

sorted()
L = [5, 2, 8]

print(sorted(L))
Output:
[2, 5, 8]

6. List Methods

append()
Adds one element at the end.
L = [1, 2]

[Link](3)

print(L)
Output:
[1, 2, 3]

extend()
Adds multiple elements.
L = [1, 2]

[Link]([3, 4])

print(L)
Output:
[1, 2, 3, 4]

insert()
Inserts at specified position.
L = [1, 2, 4]

[Link](2, 3)
print(L)
Output:
[1, 2, 3, 4]

remove()
Removes specified element.
L = [10, 20, 30]

[Link](20)

print(L)
Output:
[10, 30]

pop()
Removes and returns element.
L = [10, 20, 30]

print([Link]())
Output:
30

clear()
L = [1, 2, 3]

[Link]()

print(L)
Output:
[]

index()
L = [10, 20, 30]

print([Link](20))
Output:
1

count()
L = [1, 2, 2, 3]

print([Link](2))
Output:
2
sort()
L = [5, 2, 8]

[Link]()

print(L)
Output:
[2, 5, 8]

reverse()
L = [1, 2, 3]

[Link]()

print(L)
Output:
[3, 2, 1]

copy()
L2 = [Link]()

7. del Statement
The del statement is used to delete elements or entire lists.

Delete an Element
L = [10, 20, 30]

del L[1]

print(L)
Output:
[10, 30]

Delete Multiple Elements


L = [10, 20, 30, 40, 50]

del L[1:4]

print(L)
Output:
[10, 50]

Delete Entire List


L = [10, 20, 30]

del L

Difference Between remove(), pop(), and del


remove() pop() del
Removes Deletes
Removes value
index object
Returns
No return
No return value removed
value
item
Error if Can delete
Error if value absent
index invalid entire lis

Q1. Explain Lists in Python with Characteristics, Operations, and Methods.


Answer
A list is an ordered mutable collection of elements enclosed within square
brackets [ ].
Characteristics
1. Ordered
2. Mutable
3. Allows duplicates
4. Supports indexing and slicing
Example
L = [10, 20, 30]

[Link](40)

print(L)
Output:
[10, 20, 30, 40]
Common Methods
 append()
 extend()
 insert()
 remove()
 pop()
 sort()
 reverse()

CU Exam Answer (5 Marks)


Indexing is the process of accessing an individual element of a list using its
position number. Python supports both positive and negative indexing.
Positive indexing starts from 0, while negative indexing starts from -1 from
remove() pop() del
the end of the list.
Slicing is the process of extracting a portion of a list. The syntax is
list[start:stop:step], where the start index is included and the stop index is
excluded.
Example:
L = [10,20,30,40,50]

print(L[2]) # Indexing
print(L[1:4]) # Slicing
Output:
30
[20, 30, 40]
Thus, indexing accesses a single element, whereas slicing accesses a group
of elements from a list.

Write a code snippet to sort a list containing names of all the months of a
year in descending order.

# List containing the names of all the months


months = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
]

# Sort the list in descending alphabetical order (Z to A)


[Link](reverse=True)

# Print the sorted list


print(months)
Key concept used: The .sort() method organizes the items in a list alphabetically by default. By
passing the argument reverse=True inside the method, it reverses the default sorting behavior,
arranging the strings from Z to A.
(Note: If the question meant reverse chronological order—from December down to January—you
would simply use [Link]() instead of .sort(reverse=True) assuming the list was originally
ordered from January to December).

4(a) Explain the steps involved in opening and closing a file in Python. (4 Marks)
Opening a File
Before performing any operation on a file, it must be opened using the open() function.
Syntax
file_object = open("filename", "mode")
Example:
f = open("[Link]", "r")
Here:
 "[Link]" → file name
 "r" → read mode
File Modes
Mode Meaning
r Read
w Write
a Append
rb Read Binary
wb Write Binary

Performing Operations
After opening the file, we can:
[Link]() # Read data
[Link]() # Write data

Closing a File
After completing operations, the file should be closed using close().
[Link]()
Advantages of Closing a File
1. Frees system resources.
2. Saves data properly.
3. Prevents data corruption.

Example
f = open("[Link]", "r")
data = [Link]()
print(data)
[Link]()

CU Exam Answer (2 Marks)


Method: count()
Purpose: Returns the number of occurrences of a specified element in a tuple.
Example:
t = (10, 20, 10, 30, 10)
print([Link](10))
Output:
3

1. Creating and Storing Strings


Definition
A string is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple
quotes (''' ''' or """ """).

Creating Strings
Using Single Quotes
s = 'Python'
print(s)
Output:
Python

Using Double Quotes


s = "Programming"
print(s)

Using Triple Quotes


Used for multi-line strings.
s = """Welcome
to
Python"""

print(s)
Output:
Welcome
to
Python

2. Basic String Operations


Concatenation (+)
Combines two strings.
s1 = "Hello"
s2 = "World"

print(s1 + s2)
Output:
HelloWorld

Repetition (*)
s = "Hi "

print(s * 3)
Output:
Hi Hi Hi

Membership Operators
s = "Python"

print("P" in s)
print("Z" in s)
Output:
True
False

Length of String
s = "Python"

print(len(s))
Output:
6

3. Accessing Characters in String by Index


Strings support indexing.
Example
s = "PYTHON"
Character P Y T H O N
Index 0 1 2 3 4 5
Negative Index -6 -5 -4 -3 -2 -1

Positive Indexing
s = "PYTHON"

print(s[0])
print(s[3])
Output:
P
H

Negative Indexing
s = "PYTHON"

print(s[-1])
Output:
N

4. String Slicing
Definition
Slicing extracts a part of a string.
Syntax
string[start:stop:step]

Example
s = "PYTHON"

print(s[1:4])
Output:
YTH

From Beginning
print(s[:4])
Output:
PYTH

Up To End
print(s[2:])
Output:
THON

Reverse String
print(s[::-1])
Output:
NOHTYP

5. String Joining
join() Method
Used to combine multiple strings.
Syntax
[Link](iterable)

Example
words = ["I", "Love", "Python"]

result = " ".join(words)

print(result)
Output:
I Love Python

Joining with Hyphen


words = ["2025","06","11"]

print("-".join(words))
Output:
2025-06-11

Explain String Methods in Python (5–10 Marks)


Definition
String methods are built-in functions that operate on strings and perform various tasks such as
converting case, searching, replacing, splitting, and joining strings.
Important String Methods
1. upper()
Converts all characters to uppercase.
s = "python"
print([Link]())
Output
PYTHON

2. lower()
Converts all characters to lowercase.
s = "PYTHON"
print([Link]())
Output
python

3. capitalize()
Converts the first character to uppercase.
s = "python programming"
print([Link]())
Output
Python programming

4. title()
Converts the first letter of each word to uppercase.
s = "python programming"
print([Link]())
Output
Python Programming

5. strip()
Removes spaces from both ends of a string.
s = " Python "
print([Link]())
Output
Python

6. replace()
Replaces a substring with another substring.
s = "I like Java"
print([Link]("Java", "Python"))
Output
I like Python

7. find()
Returns the index of the first occurrence of a substring.
s = "Python"
print([Link]("t"))
Output
2

8. count()
Counts occurrences of a character or substring.
s = "banana"
print([Link]("a"))
Output
3

9. startswith()
Checks whether a string starts with a specified value.
s = "Python"
print([Link]("Py"))
Output
True

10. endswith()
Checks whether a string ends with a specified value.
s = "Python"
print([Link]("on"))
Output
True

11. split()
Splits a string into a list.
s = "Python is easy"
print([Link]())
Output
['Python', 'is', 'easy']

12. join()
Joins elements of a sequence into a single string.
words = ["I", "Love", "Python"]
print(" ".join(words))
Output
I Love Python

CU Exam Answer (5 Marks)


String methods are built-in functions used to manipulate strings. Common string methods include
upper(), lower(), capitalize(), title(), strip(), replace(), find(), count(), split(), and join(). These methods
help perform various operations such as case conversion, searching, replacing, splitting, and joining
strings.
Explain String Formatting Techniques in Python (5–10 Marks)
Definition
String formatting is the process of inserting values into a string at specific positions to create
meaningful output.
Python provides three main formatting techniques.

1. Using % Operator (Old Style Formatting)


Syntax
"format string" % value
Example
name = "Rahul"
age = 20

print("My name is %s and I am %d years old." % (name, age))


Output
My name is Rahul and I am 20 years old.
Common Format Specifiers
Specifier Meaning
%s String
%d Integer
%f Float
%c Character
Example:
pi = 3.14159
print("Value = %.2f" % pi)
Output:
Value = 3.14

2. Using format() Method


Syntax
"{}".format(value)
Example
name = "Rahul"
age = 20

print("Name: {} Age: {}".format(name, age))


Output
Name: Rahul Age: 20

Positional Formatting
print("{1} is older than {0}".format("Amit", "Rahul"))
Output
Rahul is older than Amit
Named Formatting
print("Name: {n}, Age: {a}".format(n="Rahul", a=20))
Output
Name: Rahul, Age: 20

3. Using f-Strings (Modern Method)


Introduced in Python 3.6.
Syntax
f"text {variable}"
Example
name = "Rahul"
age = 20

print(f"My name is {name} and I am {age} years old.")


Output
My name is Rahul and I am 20 years old.

Expressions in f-Strings
a = 10
b = 20

print(f"Sum = {a+b}")
Output
Sum = 30

Role of strip() Function in Python


The strip() method is used to remove unwanted characters from the beginning and end of a string.
By default, it removes whitespace characters such as:
 Spaces ( )
 Tabs (\t)
 Newline characters (\n)

 Example 1: Remove Leading and Trailing


Spaces
 s = " Python Programming "

print([Link]())
How can we access the middle element of a string

 To access the middle element of a string, first find the length of the string
using len() and then calculate the middle index.

 For a String with Odd Length
 Example
 s = "Python"

mid = len(s) // 2

print("Middle character =", s[mid])


 Output
 Middle character = t
For an Even-Length String (Two Middle Characters)
 s = "Python"

mid1 = len(s)//2 - 1
mid2 = len(s)//2

print("Middle characters =", s[mid1], s[mid2])


 Output:
 Middle characters = t h

General Program
s = input("Enter a string: ")

n = len(s)

if n % 2 == 1:
print("Middle character =", s[n//2])
else:
print("Middle characters =", s[n//2 - 1], s[n//2])

(g) Explain how f-string works in Python. (2–4 Marks)


Definition
f-string (Formatted String Literal) is a modern string formatting technique introduced in Python 3.6.
It allows variables and expressions to be embedded directly inside a string using curly braces {}.
Syntax
f"string {variable}"
Example 1: Using Variables
name = "Rahul"
age = 20

print(f"My name is {name} and I am {age} years old.")


Output
My name is Rahul and I am 20 years old.

5(c) What are Magic Methods in Python? Explain with Example. (4 Marks)
Definition
Magic methods (also called dunder methods, meaning double underscore methods) are special
methods in Python whose names begin and end with double underscores.
Examples:
__init__()
__str__()
__len__()
__add__()
These methods allow us to define how objects of a class behave with built-in operators and
functions.

Common Magic Methods


Magic Method Purpose
__init__() Constructor; initializes an object
__str__() Defines string representation of an object
__len__() Returns length using len()
__add__() Defines behavior of + operator
__del__() Destructor

Example 1: __init__() and __str__()


class Student:
def __init__(self, name):
[Link] = name

def __str__(self):
return [Link]

s = Student("Rahul")

print(s)
Output
Rahul
Explanation
 __init__() is called automatically when an object is created.
 __str__() is called automatically when print() is used.

Example 2: __len__()
class Demo:
def __len__(self):
return 10

d = Demo()

print(len(d))
Output
10

CU Exam Answer (4 Marks)


Magic methods are special methods in Python whose names start and end with double underscores
(__). They are automatically invoked by Python to implement built-in operations on objects.
Example:
class Student:
def __init__(self, name):
[Link] = name

def __str__(self):
return [Link]

s = Student("Rahul")
print(s)
Output:
Rahul
Here, __init__() initializes the object and __str__() defines how the object is displayed. Magic
methods help customize the behavior of Python objects.

With a suitable code snippet explain how inheritance works in Python.


Inheritance is the process by which one class acquires the properties and methods of another class.
The class being inherited is called the parent class and the inheriting class is called the child class.
Example:
class Animal:
def sound(self):
print("Animal Sound")

class Dog(Animal):
pass

d = Dog()
[Link]()
Output:
Animal Sound

Explain what is aliasing. (2 Marks)


Definition
Aliasing occurs when two or more variables refer to the same object in memory.
Changes made through one variable are reflected in the other variable because both point to the
same object.

Example
list1 = [10, 20, 30]
list2 = list1

[Link](40)

print("list1 =", list1)


print("list2 =", list2)
Output
list1 = [10, 20, 30, 40]
list2 = [10, 20, 30, 40]
Explanation
 list2 = list1 does not create a new list.
 Both variables refer to the same list object.
 Therefore, modifying list2 also modifies list1.

(a) What is the role of the function zip()?


The zip() function combines elements from two or more iterables (lists, tuples, etc.) into pairs as
tuples.
Example
name = ["A", "B", "C"]
marks = [80, 85, 90]

print(list(zip(name, marks)))
Output:
[('A', 80), ('B', 85), ('C', 90)]

(b) How can we access the second last element of a string?


We use negative indexing. The second last element is at index -2.
Example
s = "PYTHON"

print(s[-2])
Output:
O

(c) Explain how string formatting works in Python.


String formatting is the process of inserting variables or values into a string.
Python supports three methods:
1. % formatting
2. format() method
3. f-string
Example using f-string
name = "Rahul"

print(f"Welcome {name}")
Output:
Welcome Rahul

(d) What is the role of int() function?


The int() function converts a value into an integer.
Example
x = "25"

print(int(x))
Output:
25
It can convert strings, floats, etc., into integers.

(e) How do break and continue statements work in Python?


break
Terminates the loop immediately.
for i in range(5):
if i == 3:
break
print(i)
Output:
0
1
2

continue
Skips the current iteration and moves to the next iteration.
for i in range(5):
if i == 3:
continue
print(i)
Output:
0
1
2
4

(f) Differentiate between lists and tuples in Python.


List Tuple
Mutable Immutable
Uses [ ] Uses ( )
List Tuple
Can be modified Cannot be modified
More methods available Fewer methods
Example: [1,2,3] Example: (1,2,3)

(g) What is the functionality of hash() function in Python?


The hash() function returns the hash value (an integer) of an object.
Hash values are used in dictionaries and sets for fast lookup.
Example
print(hash("Python"))
Output:
(Some integer value)
Note: The hash value may differ from system to system.

(h) How is the try-except block used in Python for exception handling?
The try-except block is used to handle runtime errors and prevent program termination.
Syntax
try:
# risky code
except Exception:
# handling code
Example
try:
a = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed")
Output:
Division by zero is not allowed
Thus, exception handling makes programs more robust and prevents abrupt termination due to
errors.

4. Create a string with the value "Hello world". Print the string from 2nd character to 4th
character. Reverse the string with proper parameters without using loop. How the read function
works? Explain the role of seek function in context to read. (2+2+2+2+2)

(a) Create a string with the value "Hello world". (2 Marks)


s = "Hello world"

print(s)
Output
Hello world

(b) Print the string from 2nd character to 4th character. (2 Marks)
In Python, indexing starts from 0.
H e l l o w o r l d
0 1 2 3 4 5 6 7 8 9 10
The 2nd to 4th characters are e, l, l.
s = "Hello world"

print(s[1:4])
Output
ell

(c) Reverse the string without using loop. (2 Marks)


Use slicing with step -1.
s = "Hello world"

print(s[::-1])
Output
dlrow olleH
Explanation
[start : stop : step]
Here step = -1, so the string is traversed in reverse order.

(d) How does the read() function work? (2 Marks)


The read() method is used to read data from a file.
Syntax
[Link](size)
 If size is omitted, the entire file is read.
 If size is specified, only that many characters are read.
Example
f = open("[Link]", "r")

data = [Link]()

print(data)

[Link]()
The read() function returns the contents of the file as a string.

(e) Explain the role of seek() function in context to read(). (2 Marks)


The seek() function changes the current position of the file pointer.
Syntax
[Link](position)
Example
f = open("[Link]", "r")

print([Link](5))
[Link](0)

print([Link]())

[Link]()
Explanation
 After read(5), the file pointer moves forward by 5 characters.
 seek(0) moves the pointer back to the beginning of the file.
 The file can then be read again from the start.

CU Exam Answer (2 Marks)


seek() is used to move the file pointer to a specified position in a file. It is often used with read() to
reread data from a desired location.
Example:
[Link](0)
This moves the file pointer to the beginning of the file.

4. Create a simple function which takes a string as input and returns its length. (3 Marks)
Program
def string_length(s):
return len(s)

text = input("Enter a string: ")

print("Length =", string_length(text))


Sample Output
Enter a string: Python
Length = 6

1. What is the use of Lambda Expression? (2 Marks)


Definition
A lambda expression is an anonymous (nameless) function in Python used for writing small
functions in a single line.
Syntax
lambda arguments : expression
Example
square = lambda x: x*x

print(square(5))
Output
25
Uses of Lambda Expression
1. Creates small one-line functions.
2. Commonly used with map(), filter(), and reduce().
3. Improves code readability.
2. Explain how the map() function works. (2 Marks)
Definition
The map() function applies a given function to each element of an iterable (list, tuple, etc.) and
returns a map object.
Syntax
map(function, iterable)
Example 1: Using Normal Function
def square(x):
return x*x

L = [1, 2, 3, 4]

result = list(map(square, L))

print(result)
Output
[1, 4, 9, 16]

Example 2: Using Lambda Function


L = [1, 2, 3, 4]

result = list(map(lambda x: x*x, L))

print(result)
Output
[1, 4, 9, 16]
Explanation
map() applies the function to every element of the list and returns the transformed values.

3. Explain different access modifiers available in Python. (3 Marks)


Definition
Access modifiers specify the accessibility of class members (variables and methods).
Python provides three types of access modifiers:
Access Modifier Syntax Accessibility
Public name Accessible everywhere
Protected _name Accessible within class and subclasses
Private __name Accessible only within the class

1. Public Member
class Student:
name = "Rahul"

s = Student()
print([Link])
Output:
Rahul

2. Protected Member
class Student:
_marks = 90

s = Student()

print(s._marks)
Although accessible, it is intended for internal use.

3. Private Member
class Student:
__age = 20

s = Student()

# print(s.__age) # Error
Private members cannot be accessed directly outside the class.

7(a) What is a module in Python? Explain how you can use the module in your program with an
example. (5 Marks)
Definition
A module in Python is a file containing Python code such as functions, classes, and variables that can
be reused in other programs.
Modules help in:
 Code reusability
 Better organization of programs
 Easy maintenance
Python provides:
1. Built-in modules (e.g., math, os, random)
2. User-defined modules

Importing a Module
Modules are imported using the import statement.
Syntax
import module_name

Example 1: Using Built-in math Module


import math
print([Link](25))
print([Link](5))
Output
5.0
120
Explanation
 [Link](25) computes square root.
 [Link](5) computes factorial.

Different Ways to Import Modules


Import Entire Module
import math

print([Link])

Import Specific Function


from math import sqrt

print(sqrt(16))
Output:
4.0

Import with Alias


import math as m

print([Link](4))
Output:
24

User-Defined Module
Suppose there is a file named [Link]
def add(a, b):
return a + b
Another file:
import mymodule

print([Link](5, 3))
Output:
8

CU Exam Answer (5 Marks)


A module is a Python file containing functions, classes, and variables that can be used in other
programs. Modules promote code reusability and modular programming.
Example:
import math

print([Link](36))
Output:
6.0

7(b) Explain Python Built-in Exceptions. (5 Marks)


Definition
An exception is an error that occurs during program execution and interrupts the normal flow of the
program.
Python provides many built-in exceptions to handle runtime errors.

Common Built-in Exceptions


Exception Cause
ZeroDivisionError Division by zero
NameError Undefined variable
TypeError Invalid operation between data types
ValueError Invalid value
IndexError Invalid list index
KeyError Invalid dictionary key
FileNotFoundError File not found
ImportError Module import failure

Examples
1. ZeroDivisionError
a = 10
b=9

print(a / b)
Output:
ZeroDivisionError: division by zero

2. IndexError
L = [10, 20, 30]

print(L[5])
Output:
IndexError: list index out of range

3. KeyError
d = {"A": 1}

print(d["B"])
Output:
KeyError: 'B'

Exception Handling Using try-except


try:
x = 10 / 5
except ZeroDivisionError:
print("Cannot divide by zero")
return x
Output:
Cannot divide by zero

8(a) What is a variable? How is it created and assigned a value of a particular datatype? (5 Marks)
Definition
A variable is a named memory location used to store data values in a program. The value stored in a
variable can be changed during program execution.

In Python, variables are created automatically when a value is assigned using the assignment
operator =.
Creating Variables
Syntax
variable_name = value
Examples
a = 10
name = "Rahul"
pi = 3.14
flag = True
Here:
 a stores an integer.
 name stores a string.
 pi stores a float.
 flag stores a boolean value.

Python supports various datatypes such as int, float, str, and bool. The datatype of a variable can be
checked using the type() function.
Checking Datatype
Python provides the type() function.
x = 25
print(type(x))
Output:
<class 'int'>

Explain Command Line Arguments using [Link] (5 Marks)


Definition
Command line arguments are values supplied to a program at the time of execution from the
command line.
In Python, command line arguments are accessed using the argv list of the sys module.
 argv stands for argument vector.
 [Link] stores all command line arguments as strings.

Importing sys Module


import sys

Syntax
[Link][index]
where,
 [Link][0] → Program name
 [Link][1] → First argument
 [Link][2] → Second argument
 and so on.

Example 1: Display Command Line Arguments


Program ([Link])
import sys

print([Link])
Execution
python [Link] Hello Python 2025
Output
['[Link]', 'Hello', 'Python', '2025']
Explanation
Index Value
[Link][0] [Link]
[Link][1] Hello
[Link][2] Python
[Link][3] 2025

Example 2: Addition of Two Numbers


Program
import sys

a = int([Link][1])
b = int([Link][2])

print("Sum =", a + b)
Execution
python [Link] 10 20
Output
Sum = 30
Difference Between *args and **kwargs
*args **kwargs
Accepts positional arguments Accepts keyword arguments
Stored as tuple Stored as dictionary
Uses single * Uses double **
Example: (1,2,3) Example: {'a':1,'b':2}

*args and **kwargs are used to pass a variable number of arguments to a function.
 *args accepts multiple positional arguments and stores them in a tuple.
 **kwargs accepts multiple keyword arguments and stores them in a dictionary.
Example:
def add(*args):
return sum(args)

print(add(1, 2, 3, 4))
Output:
10
Example:
def info(**kwargs):
print(kwargs)

info(name="Rahul", age=20)
Output:
{'name': 'Rahul', 'age': 20}
Thus, *args and **kwargs provide flexibility in function definitions.

Q1. Write a function to find factorial of a number.


def factorial(n):
fact = 1

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


fact *= i

return fact
num=int(input("enter a number :"))
print(factorial(num))
Output:
120

Q2. Write a function to check prime number.


def is_prime(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False

return True

print(is_prime(7))
Output:
True

Q3. Write a function to return the length of a string.


def string_length(s):
return len(s)
text=input("enter a string")
print("lenght=",string_length(text))
Output:
6

Q4. Write a function using *args to calculate sum.


def add(*args):
return sum(args)

print(add(1,2,3,4,5))
Output:
15

Q5. Write a function using **kwargs.


def student(**kwargs):
for k, v in [Link]():
print(k, ":", v)

student(name="Rahul", age=20)
Output:
name : Rahul
age : 20

1. Default Arguments
Definition
A default argument is a parameter that has a predefined value. If no value is passed during function
call, the default value is used.
Syntax
def function_name(parameter = default_value):
statements
Example 1
def greet(name = "Guest"):
print("Hello", name)

greet()
greet("Rahul")
Output
Hello Guest
Hello Rahul
Explanation
 In greet(), no argument is passed.
 Therefore, the default value "Guest" is used.
 In greet("Rahul"), "Rahul" replaces the default value.

Example 2
def power(x, y = 2):
return x ** y

print(power(5))
print(power(5, 3))
Output
25
125
Explanation:
 power(5) computes 5² = 25.
 power(5, 3) computes 5³ = 125.

Rules for Default Arguments


1. Default parameters must come after non-default parameters.
✔ Correct:
def add(a, b = 0):
return a + b
✘ Incorrect:
def add(a = 0, b):
return a + b
This produces a SyntaxError.

1. Default Arguments
Definition
A default argument is a parameter that has a predefined value. If no value is passed during function
call, the default value is used.
Syntax
def function_name(parameter = default_value):
statements
Example 1
def greet(name = "Guest"):
print("Hello", name)

greet()
greet("Rahul")
Output
Hello Guest
Hello Rahul
Explanation
 In greet(), no argument is passed.
 Therefore, the default value "Guest" is used.
 In greet("Rahul"), "Rahul" replaces the default value.

Example 2
def power(x, y = 2):
return x ** y

print(power(5))
print(power(5, 3))
Output
25
125
Explanation:
 power(5) computes 5² = 25.
 power(5, 3) computes 5³ = 125.

Rules for Default Arguments


1. Default parameters must come after non-default parameters.
✔ Correct:
def add(a, b = 0):
return a + b
✘ Incorrect:
def add(a = 0, b):
return a + b
This produces a SyntaxError.

2. Keyword Arguments
Definition
Arguments passed using the parameter name are called keyword arguments.
In keyword arguments, the order of arguments does not matter.
Syntax
function_name(parameter = value)

Example 1
def student(name, age):
print("Name =", name)
print("Age =", age)

student(age = 20, name = "Rahul")


Output
Name = Rahul
Age = 20
Explanation
Even though age is written first, Python matches arguments using parameter names.

Example 2
def info(city, country):
print(city, country)

info(country = "India", city = "Kolkata")


Output
Kolkata India

Difference Between Default and Keyword Arguments


Default Arguments Keyword Arguments
Parameter has a default value Arguments are passed by name
Used when no value is supplied Order of arguments does not matter
Defined in function definition Used during function call
Example: def f(x=10) Example: f(x=10)

Decision Control Statements in Python


Decision control statements allow a program to make decisions and execute different blocks of code
based on conditions.
Python provides the following decision control statements:
1. if
2. if...else
3. if...elif...else
4. Nested if

1. if Statement
Definition
The if statement executes a block of code only when the given condition is True.
Syntax
if condition:
statement(s)

Flowchart
Condition
|
True
|
Statements

Example 1
age = 20

if age >= 18:


print("Eligible to vote")
Output
Eligible to vote
Explanation
Since 20 >= 18 is True, the statement inside if executes.

Example 2
num = 10

if num > 0:
print("Positive Number")
Output:
Positive Number

2. if...else Statement
Definition
The if...else statement executes one block if the condition is True and another block if the condition
is False.
Syntax
if condition:
statements1
else:
statements2

Flowchart
Condition
/ \
True False
| |
Statements1 Statements2

Example: Even or Odd


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

if num % 2 == 0:
print("Even")
else:
print("Odd")
Output
Enter a number: 7
Odd

Example: Pass or Fail


marks = 45

if marks >= 40:


print("Pass")
else:
print("Fail")
Output:
Pass

3. if...elif...else Statement
Definition
When there are multiple conditions to check, we use if...elif...else.
elif means else if.
Syntax
if condition1:
statements1
elif condition2:
statements2
elif condition3:
statements3
else:
statements4

Example: Grade Calculation


marks = int(input("Enter marks: "))

if marks >= 90:


print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")
Output
Enter marks: 82
Grade B
Execution Rule
Python checks conditions from top to bottom.
 If a condition is True, its block executes.
 Remaining conditions are skipped.

4. Nested if Statement
Definition
An if statement inside another if statement is called a nested if.
Syntax
if condition1:
if condition2:
statements

Example: Positive Even Number


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

if num > 0:
if num % 2 == 0:
print("Positive Even Number")
Output
Enter a number: 8
Positive Even Number

Example: Eligibility for Scholarship


marks = 85
income = 40000

if marks >= 80:


if income < 50000:
print("Scholarship Granted")
Output:
Scholarship Granted

Difference Between if, if...else, and if...elif...else


Statement Purpose
if Executes code when condition is True
if...else Chooses between two alternatives
if...elif...else Chooses among multiple alternatives

Important Programs for CU Exams


1. Largest of Two Numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if a > b:
print("Largest =", a)
else:
print("Largest =", b)

2. Largest of Three Numbers


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b and a >= c:


print("Largest =", a)
elif b >= a and b >= c:
print("Largest =", b)
else:
print("Largest =", c)

3. Check Leap Year


year = int(input("Enter year: "))

if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):


print("Leap Year")
else:
print("Not a Leap Year")

4. Check Positive, Negative, or Zero


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

if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")

While Loop, Continue and Break, Exception Handling using try and except
These are very important topics for Calcutta University (CU) [Link]. Honors examinations.

1. While Loop
Definition
A while loop repeatedly executes a block of code as long as the given condition is True.
It is generally used when the number of iterations is not known in advance.

Syntax
while condition:
statements

Flowchart
Condition
/ \
True False
| |
Statements Exit
|
Repeat

Example 1: Print Numbers from 1 to 5


i=1

while i <= 5:
print(i)
i=i+1
Output
1
2
3
4
5
Explanation
 Initially i = 1
 The loop continues until i <= 5
 After each iteration, i increases by 1

Example 2: Sum of First N Natural Numbers


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

i=1
sum = 0

while i <= n:
sum += i
i+=1

print("Sum =", sum)


Output
Enter n: 5
Sum = 15

2. Infinite While Loop


A loop that never terminates is called an infinite loop.
while True:
print("Hello")
This loop runs forever until interrupted.

3. break Statement
Definition
The break statement immediately terminates the loop and transfers control outside the loop.

Syntax
break

Example
for i in range(1, 10):
if i == 5:
break
print(i)
Output
1
2
3
4
Explanation
When i becomes 5, the loop stops immediately.

Example with While Loop


i=1

while True:
if i == 6:
break

print(i)
i += 1
Output:
1
2
3
4
5

4. continue Statement
Definition
The continue statement skips the remaining statements of the current iteration and moves to the
next iteration.
Syntax
continue

Example
for i in range(1, 6):
if i == 3:
continue

print(i)
Output
1
2
4
5
Explanation
When i = 3, the print() statement is skipped.

Example: Print Odd Numbers


for i in range(1, 11):
if i % 2 == 0:
continue

print(i)
Output:
1
3
5
7
9

Difference Between break and continue


break continue
Terminates the loop Skips current iteration
Control exits loop Control goes to next iteration
Used to stop loop Used to ignore some iterations

5. Exception Handling using try and except


Definition
An exception is an error that occurs during program execution and interrupts the normal flow of the
program.
Exception handling prevents abrupt termination of programs.

Syntax
try:
statements
except ExceptionName:
statements

Working
1. Code inside try block is executed.
2. If no error occurs, except block is skipped.
3. If an exception occurs, control transfers to except.

Example 1: Division by Zero


try:
a = 10
b=0

print(a / b)

except ZeroDivisionError:
print("Cannot divide by zero")
Output
Cannot divide by zero

Example 2: Invalid Input


try:
num = int(input("Enter a number: "))
print(num)

except ValueError:
print("Invalid input")

Example 3: Index Error


try:
L = [10, 20, 30]

print(L[5])

except IndexError:
print("Index out of range")
Output
Index out of range

Multiple Exceptions
try:
a = int(input("Enter a number: "))
print(10 / a)
except ZeroDivisionError:
print("Division by zero")

except ValueError:
print("Invalid input")

try-except-else
The else block executes if no exception occurs.
try:
x = 10 / 2

except ZeroDivisionError:
print("Error")

else:
print("No Exception")
Output
No Exception

finally Block
The finally block executes whether an exception occurs or not.
try:
print(10 / 2)

except ZeroDivisionError:
print("Error")

finally:
print("Program Ended")
Output
5.0
Program Ended

1. Class
Definition
A class is a blueprint or template for creating objects. It defines the properties (variables) and
behaviors (methods) of objects.
Real-Life Example
 Class: Student
 Objects: Rahul, Amit, Priya
All students have common properties like name and roll number.

Syntax of Class
class ClassName:
statements

Example
class Student:
pass
Here, Student is a class and pass means the class body is empty.

2. Object
Definition
An object is an instance of a class. It is created from a class.
Syntax
object_name = ClassName()

Example
class Student:
pass

s1 = Student()
s2 = Student()
Here:
 s1 and s2 are objects of class Student.

3. Creating Classes in Python


A class may contain:
1. Data members (variables)
2. Member functions (methods)

Example
class Student:
name = "Rahul"

def display(self):
print("Name =", [Link])

s = Student()
[Link]()
Output
Name = Rahul

Explanation
 name is a class variable.
 display() is a method.
 self refers to the current object.
4. Creating Objects in Python
Objects are created by calling the class name like a function.
class Car:
pass

c1 = Car()
c2 = Car()
Here, c1 and c2 are objects of class Car.

5. Accessing Attributes and Methods


Use the dot (.) operator.
class Student:
name = "Rahul"

s = Student()

print([Link])
Output:
Rahul

6. Constructor Method
Definition
A constructor is a special method that is automatically called when an object is created.
In Python, the constructor method is:
__init__()

Syntax
class ClassName:
def __init__(self):
statements

Example 1: Constructor Without Parameters


class Student:
def __init__(self):
print("Constructor called")

s = Student()
Output
Constructor called

Example 2: Parameterized Constructor


class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age
def display(self):
print("Name =", [Link])
print("Age =", [Link])

s = Student("Rahul", 20)

[Link]()
Output
Name = Rahul
Age = 20

Explanation of self
self refers to the current object of the class.
Example:
[Link] = name
means:
[Link] = value

Working of Constructor
When this statement executes:
s = Student("Rahul", 20)
Python internally does:
Student.__init__(s, "Rahul", 20)
Thus, the constructor initializes object attributes.

Advantages of Constructor
1. Automatically initializes objects.
2. Reduces code repetition.
3. Makes programs more organized.

Long Questions with Solutions

Q1. Create a class Student with name and age. Display the details.
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age

def display(self):
print("Name =", [Link])
print("Age =", [Link])

s = Student("Rahul", 20)
[Link]()
Output
Name = Rahul
Age = 20

Q2. Create a class Rectangle to calculate area.


class Rectangle:
def __init__(self, length, breadth):
[Link] = length
[Link] = breadth

def area(self):
return [Link] * [Link]

r = Rectangle(10, 5)

print("Area =", [Link]())


Output
Area = 50

Q3. Create a class Circle to calculate area.


class Circle:
def __init__(self, radius):
[Link] = radius

def area(self):
return 3.14 * [Link] * [Link]

c = Circle(7)

print("Area =", [Link]())


Output
Area = 153.86

Difference Between Class and Object


Class Object
Blueprint/template Instance of class
Logical entity Physical entity
No memory allocated Memory allocated
Example: Student Example: Rahul

Difference Between Method and Constructor


Method Constructor
Called explicitly Called automatically
Any name Always __init__()
Performs operations Initializes objects

Polymorphism means many forms. It allows the same method, function, or operator to behave
differently for different objects.
Polymorphism in Python is achieved mainly through:
1. Operator Overloading
2. Method Overriding
Example:
class Animal:
def sound(self):
print("Animal Sound")

class Dog(Animal):
def sound(self):
print("Dog Barks")

d = Dog()
[Link]()
Output:
Dog Barks
Here, the child class method overrides the parent class method, demonstrating polymorphism.

Operator Overloading
The same operator behaves differently for different data types.
Example: + Operator
print(10 + 20)
print("Hello" + " World")
print([1,2] + [3,4])
Output
30
Hello World
[1, 2, 3, 4]
Explanation
Expression Operation
10 + 20 Addition
"Hello" + "World" String concatenation
[1,2] + [3,4] List concatenation
Thus, the + operator has multiple forms, showing polymorphism.

Q4. Demonstrate polymorphism through method overriding.


class Bird:
def sound(self):
print("Bird sound")

class Sparrow(Bird):
def sound(self):
print("Chirp Chirp")

s = Sparrow()

[Link]()

1. Classes with Multiple Objects


Definition
A class can have multiple objects. Each object has its own copy of instance variables but shares class
variables.

Example
class Student:
def __init__(self, name, roll):
[Link] = name
[Link] = roll

def display(self):
print("Name =", [Link])
print("Roll =", [Link])

s1 = Student("Rahul", 1)
s2 = Student("Amit", 2)

[Link]()
[Link]()
Output
Name = Rahul
Roll = 1
Name = Amit
Roll = 2
Explanation
 s1 and s2 are two different objects.
 Each object stores its own data.

2. Class Attributes vs Data (Instance) Attributes


(A) Class Attributes
Class attributes are shared by all objects of the class.
Example
class Student:
college = "CU"

s1 = Student()
s2 = Student()

print([Link])
print([Link])
Output
CU
CU

(B) Instance (Data) Attributes


Instance attributes belong to individual objects.
Example
class Student:
def __init__(self, name):
[Link] = name

s1 = Student("Rahul")
s2 = Student("Amit")

print([Link])
print([Link])
Output
Rahul
Amit

Difference Between Class and Instance Attributes


Class Attribute Instance Attribute
Shared by all objects Unique to each object
Defined inside class Defined using self
Memory efficient Separate memory for each object

3. Encapsulation
Definition
Encapsulation is the process of wrapping data and methods into a single unit (class) and restricting
direct access to data.
It provides data hiding.

Access Modifiers in Python


Modifier Syntax Accessibility
Public name Accessible everywhere
Protected _name Accessible in class and subclasses
Modifier Syntax Accessibility
Private __name Accessible only within class

Example of Encapsulation
class Student:
def __init__(self):
self.__marks = 90

def show(self):
print(self.__marks)

s = Student()

[Link]()
Output
90
Trying:
print(s.__marks)
gives:
AttributeError

Advantages of Encapsulation
1. Data security
2. Data hiding
3. Better program organization

4. Inheritance
Definition
Inheritance is the mechanism by which one class acquires the properties and methods of another
class.
 Parent Class (Base Class)
 Child Class (Derived Class)

Syntax
class Child(Parent):
pass

Example
class Animal:
def sound(self):
print("Animals make sound")

class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()

[Link]()
[Link]()
Output
Animals make sound
Dog barks

Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance

Example: Multilevel Inheritance


class A:
def showA(self):
print("Class A")

class B(A):
def showB(self):
print("Class B")

class C(B):
def showC(self):
print("Class C")

obj = C()

[Link]()
[Link]()
[Link]()

Advantages of Inheritance
1. Code reusability
2. Easy maintenance
3. Extensibility
(a) Give an example of a ternary operator in Python with example. (2 Marks)
Definition
A ternary operator is a shorthand form of if-else used in a single line.
Syntax
value_if_true if condition else value_if_false
Example
a = 10
b = 20

max = a if a > b else b

print(max)
Output
20

(b) List two differences between list and dictionary. (2 Marks)


List Dictionary
Elements are accessed by index Elements are accessed by keys
Uses [ ] Uses { }
Example: [1,2,3] Example: {'a':1}

(c) Briefly remark about variable declaration in Python in comparison with C. (2 Marks)
Python
 Variables are created automatically during assignment.
 No datatype declaration is required.
x = 10
name = "Rahul"
C
 Variables must be declared before use.
int x = 10;
char name[10];
Conclusion
Python is dynamically typed, whereas C is statically typed.

(d) Explain with a code snippet, how an element of a list can be changed. (2 Marks)
List elements can be modified using indexing.
Example
L = [10, 20, 30, 40]

L[2] = 100

print(L)
Output
[10, 20, 100, 40]
Thus, the element at index 2 is changed from 30 to 100.

(e) Explain the use of file object. (2 Marks)


A file object is created when a file is opened using the open() function.
It is used to perform operations such as:
 Reading data
 Writing data
 Appending data
 Closing the file
Example
f = open("[Link]", "r")

content = [Link]()

[Link]()
Here, f is the file object.

(f) Are tuples mutable? Explain with code snippet. (2 Marks)


No, tuples are immutable, meaning their elements cannot be changed after creation.
Example
t = (10, 20, 30)

t[1] = 50
Output
TypeError: 'tuple' object does not support item assignment
Thus, tuples are immutable.

(g) Explain how f-string works in Python. (2 Marks)


An f-string (formatted string literal) allows variables and expressions to be inserted directly into
strings.
Example
name = "Rahul"
age = 20

print(f"My name is {name} and I am {age} years old.")


Output
My name is Rahul and I am 20 years old.

(h) Identify different string formatting techniques available in Python with example. (2 Marks)
Python provides three string formatting methods:
1. % Formatting
name = "Rahul"

print("Name: %s" % name)

2. format() Method
print("Name: {}".format("Rahul"))

3. f-String
name = "Rahul"

print(f"Name: {name}")
Among these, f-strings are the most modern and efficient method.

append() adds an element at the end of the list.

2(d) Delete the element OS. On this context discuss other ways to delete an element from a list. (3
Marks)
Method 1: Using remove()
subjects = ["OS", "DBMS", "CA", "Java"]

[Link]("OS")

print(subjects)
Output
['DBMS', 'CA', 'Java']
remove() deletes the specified value.

Other Methods of Deleting List Elements


(i) Using del
Deletes by index.
subjects = ["OS", "DBMS", "CA", "Java"]

del subjects[0]

print(subjects)
Output:
['DBMS', 'CA', 'Java']

(ii) Using pop()


Deletes and returns an element.
subjects = ["OS", "DBMS", "CA", "Java"]

x = [Link](0)

print("Deleted =", x)
print(subjects)

(a) Describe different logical operators of Python with suitable examples. (4 Marks)
Definition
Logical operators are used to combine two or more conditions and return either True or False.
Python provides three logical operators:
1. and
2. or
3. not

1. and Operator
Returns True only if both conditions are True.
Syntax
condition1 and condition2
Example
a = 10
b = 20

print(a > 5 and b > 15)


Output
True
Explanation:
 a > 5 → True
 b > 15 → True
 True and True → True

2. or Operator
Returns True if at least one condition is True.
Example
a = 10
b = 20

print(a > 15 or b > 15)


Output
True
Explanation:
 a > 15 → False
 b > 15 → True
 False or True → True

3. not Operator
Reverses the logical value.
Example
a = 10

print(not(a > 5))


Output
False
Explanation:
 a > 5 → True
 not True → False
3(b) Write a code snippet for creating a list containing first five odd positive integers using the
range() function. (3 Marks)
The first five odd positive integers are:
1, 3, 5, 7, 9
Program
odd_list = list(range(1, 10, 2))

print(odd_list)
Output
[1, 3, 5, 7, 9]
Explanation
Syntax of range():
range(start, stop, step)
Here:
 start = 1
 stop = 10
 step = 2

3(c) Write a code snippet to extract "today" from "today is a funday". (3 Marks)
Method 1: Using String Slicing
s = "today is a funday"

print(s[:5])
Output
today
Explanation
Indices:
t o d a y i s ...
01234
[:5] extracts characters from index 0 to 4.

Alternative Method
s = "today is a funday"

word = [Link]()[0]

print(word)

4(a) Explain with example how indexing and slicing work in Python lists or strings. (4 Marks)
1. Indexing
Indexing is used to access individual elements of a list or string.
Python supports:
 Positive indexing
 Negative indexing
Example with String
s = "PYTHON"

print(s[0])
print(s[3])
print(s[-1])
Output
P
H
N
Index Positions
String : P Y T H O N
Index : 0 1 2 3 4 5
Neg. :-6 -5 -4 -3 -2 -1

Example with List


L = [10, 20, 30, 40]

print(L[1])
print(L[-1])
Output
20
40

2. Slicing
Slicing extracts a portion of a list or string.
Syntax
sequence[start : stop : step]
 start → Starting index (included)
 stop → Ending index (excluded)
 step → Increment value

Example with String


s = "PYTHON"

print(s[1:4])
print(s[:3])
print(s[2:])
print(s[::-1])
Output
YTH
PYT
THON
NOHTYP
Example with List
L = [10, 20, 30, 40, 50]

print(L[1:4])
Output
[20, 30, 40]

Difference Between Indexing and Slicing


Indexing Slicing
Accesses one element Accesses multiple elements
Uses single index Uses start:stop:step
Example: s[2] Example: s[1:4]

CU Exam Answer (4 Marks)


Indexing is used to access individual elements of a sequence using indices, whereas slicing extracts a
part of a sequence.
Example:
s = "Python"

print(s[0]) # Indexing
print(s[1:4]) # Slicing
Output:
P
yth

4(b) Explain with example packing and unpacking. (4 Marks)


Packing
Packing means placing multiple values into a single tuple.
Example
t = 10, 20, 30

print(t)
print(type(t))
Output
(10, 20, 30)
<class 'tuple'>
Python automatically packs the values into a tuple.

Unpacking
Unpacking means extracting tuple elements into separate variables.
Example
t = (10, 20, 30)

a, b, c = t
print(a)
print(b)
print(c)
Output
10
20
30

4(c) Give example how zip() works. (2 Marks)


Definition
The zip() function combines elements from two or more iterables into tuples.
Syntax
zip(iterable1, iterable2)

Example
names = ["Rahul", "Amit", "Riya"]
marks = [80, 85, 90]

result = list(zip(names, marks))

print(result)
Output
[('Rahul', 80), ('Amit', 85), ('Riya', 90)]

(a) Explain different operators on the data type set with example. (5 Marks)
Definition
A set is an unordered collection of unique elements enclosed within { }.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
Python provides several operators on sets.

1. Union Operator (|)


Returns all unique elements from both sets.
A = {1, 2, 3}
B = {3, 4, 5}

print(A | B)
Output
{1, 2, 3, 4, 5}

2. Intersection Operator (&)


Returns common elements.
A = {1, 2, 3}
B = {2, 3, 4}
print(A & B)
Output
{2, 3}

3. Difference Operator (-)


Returns elements present in the first set but not in the second.
A = {1, 2, 3}
B = {2, 3, 4}

print(A - B)
Output
{1}

4. Symmetric Difference (^)


Returns elements present in either set but not in both.
A = {1, 2, 3}
B = {2, 3, 4}

print(A ^ B)
Output
{1, 4}

5. Membership Operators (in, not in)


A = {1, 2, 3}

print(2 in A)
print(5 not in A)
Output
True
True

(b) Give an example of (i) ValueError, (ii) KeyError in Python. (3 Marks)


(i) ValueError
Occurs when a function receives an argument of the correct type but invalid value.
Example
x = int("abc")
Output
ValueError: invalid literal for int()
Explanation:
"abc" cannot be converted to an integer.

(ii) KeyError
Occurs when a dictionary key does not exist.
Example
d = {"A": 1, "B": 2}

print(d["C"])
Output
KeyError: 'C'
Explanation:
Key "C" is not present in the dictionary.

(c) What is the use of % operator in Python? (2 Marks)


The % operator has two uses in Python:

1. Modulus Operator
Returns the remainder after division.
print(10 % 3)
Output
1

2. String Formatting
Used for old-style string formatting.
name = "Rahul"

print("Hello %s" % name)


Output
Hello Rahul

(b) Explain Lambda Function with a suitable example. (4 Marks)


Definition
A lambda function is an anonymous (nameless) function written in a single line using the lambda
keyword.

Syntax
lambda arguments : expression

Example 1: Square of a Number


square = lambda x: x * x

print(square(5))
Output
25

Example 2: Addition of Two Numbers


add = lambda a, b: a + b

print(add(10, 20))
Output
30

Advantages of Lambda Function


1. Short and concise syntax.
2. Useful with map(), filter(), and reduce().
3. No need to define a function using def.

Explain what is aliasing. (2


Marks)
4. Definition
Aliasing occurs when two or more variables refer to the same object in memory.
Changes made through one variable are reflected in the other variable.
5. Example
list1 = [10, 20, 30]

list2 = list1

[Link](40)

print(list1)
print(list2)

6. Output
7. [10, 20, 30, 40]
[10, 20, 30, 40]
8. Explanation
9. Both list1 and list2 refer to the same list object. Therefore, modifying list2 also
changes list1.

2(a) With a suitable code snippet explain how inheritance works in Python. (4 Marks)
Definition
Inheritance is the OOP feature by which one class acquires the properties and methods of another
class.
 Parent Class (Base Class)
 Child Class (Derived Class)

Example
class Animal:
def sound(self):
print("Animals make sound")

class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()

[Link]()
[Link]()
Output
Animals make sound
Dog barks
Explanation
The Dog class inherits the sound() method from the Animal class.

Let's explain the Armstrong number program line by line.


Program
def armstrong(n):
temp = n
digits = len(str(n))
sum = 0

while temp > 0:


digit = temp % 10
sum += digit ** digits
temp = temp // 10

if sum == n:
return True
else:
return False

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

if armstrong(num):
print("Armstrong Number")
else:
print("Not an Armstrong Number")

Magic Methods in Python (Dunder Methods)


Definition
Magic methods are special methods in Python whose names begin and end with double
underscores (__).
They are also called Dunder Methods (Double Underscore methods).
Examples:
__init__()
__str__()
__len__()
__add__()
__del__()
These methods are automatically called by Python to define the behavior of objects.
Why are Magic Methods Used?
Magic methods allow us to:
 Initialize objects
 Print objects
 Perform operations on objects
 Overload operators
 Define object behavior

1. __init__() Method (Constructor)


It is automatically called when an object is created.
Example
class Student:
def __init__(self, name):
[Link] = name

s = Student("Rahul")

print([Link])
Output
Rahul

a) What is the role of the function strip()? (2 Marks)


Definition
The strip() method removes leading (left) and trailing (right) spaces or specified characters from a
string.
Syntax
[Link]()
Example
s = " Hello Python "

print([Link]())
Output
Hello Python
Example with Characters
s = "###Python###"

print([Link]("#"))
Output:
Python
Note: strip() does not remove spaces in the middle of the string.

(b) How can we access the middle element of a string? (2 Marks)


The middle element can be accessed using the index:
len(string) // 2
Example
s = "Python"

mid = len(s) // 2

print(s[mid])
Output
h
Explanation:
P y t h o n
0 1 2 3 4 5
Length = 6
Middle index = 6 // 2 = 3
Character at index 3 is h.

(c) What is the role of the function index()? (2 Marks)


The index() method returns the first occurrence of a specified element in a string or list.
Syntax
[Link](value)
Example
s = "Python"

print([Link]("t"))
Output
2
Note
If the element is not found, index() raises a ValueError.
[Link]("z")
Output:
ValueError: substring not found

(d) Explain how string formatting works in Python. (2 Marks)


String formatting is used to insert variables into strings.
Python supports:
1. % formatting
2. format() method
3. f-string
Example (f-string)
name = "Rahul"
age = 20

print(f"My name is {name} and I am {age} years old.")


Output
My name is Rahul and I am 20 years old.
(e) Explain with examples how break and continue statements work. (2 Marks)
break
Terminates the loop immediately.
for i in range(1, 6):
if i == 4:
break
print(i)
Output:
1
2
3

continue
Skips the current iteration.
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5

(f) How exception handling works in Python? (2 Marks)


Exception handling is done using try and except.
Syntax
try:
statements
except Exception:
statements
Example
try:
print(10 / 0)

except ZeroDivisionError:
print("Division by zero is not allowed")
Output:
Division by zero is not allowed

(g) How can an element be detected from a dictionary? (2 Marks)


Use the membership operator in.
Example
d = {"A": 1, "B": 2}

print("A" in d)
Output
True
To check values:
print(2 in [Link]())
Output:
True

(h) What are different parameters in range()? (2 Marks)


The range() function has three parameters:
range(start, stop, step)
Parameter Meaning
start Starting value
stop Ending value (excluded)
step Increment/decrement
Example
for i in range(1, 10, 2):
print(i)
Output:
13579

2(c) State the differences between deep copy and shallow copy. (3 Marks)
Definition
Copying an object can be done in two ways:
1. Shallow Copy
2. Deep Copy

Shallow Copy
A shallow copy creates a new object but nested objects are shared.
Changes in nested objects affect both copies.
Example
import copy

a = [[1, 2], [3, 4]]


b = [Link](a)

b[0][0] = 100

print(a)
print(b)
Output
[[100, 2], [3, 4]]
[[100, 2], [3, 4]]

Deep Copy
A deep copy creates a completely independent copy including nested objects.
Example
import copy

a = [[1, 2], [3, 4]]


b = [Link](a)

b[0][0] = 100

print(a)
print(b)
Output
[[1, 2], [3, 4]]
[[100, 2], [3, 4]]

Difference Between Deep Copy and Shallow Copy


Shallow Copy Deep Copy
Copies only outer object Copies entire object recursively
Nested objects are shared Nested objects are independent
Changes may affect original Changes do not affect original
Uses [Link]() Uses [Link]()

CU Exam Answer (3 Marks)


 Shallow Copy: Creates a new object but shares nested objects with the original.
 Deep Copy: Creates a completely independent copy of the original object.

2(b) State the purpose of enumerate() in Python. (3 Marks)


Definition
The enumerate() function is used to iterate over an iterable while keeping track of the index of
each element.

Syntax
enumerate(iterable, start=0)
 iterable → list, tuple, string, etc.
 start → starting index (default is 0)

Example
fruits = ["Apple", "Mango", "Orange"]
for index, value in enumerate(fruits):
print(index, value)
Output
0 Apple
1 Mango
2 Orange

Example with Starting Index


for i, fruit in enumerate(fruits, start=1):
print(i, fruit)
Output:
1 Apple
2 Mango
3 Orange
(a) Write a program in Python that takes input from user and calculate area and perimeter of a
cylinder. (4 Marks)
A cylinder has:
 Radius (r)
 Height (h)
Formulae
Curved Surface Area (CSA)
CSA = 2πrh
Total Surface Area (TSA)
TSA = 2πr(h + r)
Perimeter (Circumference of Base)
Perimeter = 2πr

Python Program
pi = 3.14

r = float(input("Enter radius: "))


h = float(input("Enter height: "))

area = 2 * pi * r * (h + r) # Total Surface Area


perimeter = 2 * pi * r # Circumference of base

print("Area =", area)


print("Perimeter =", perimeter)
Sample Output
Enter radius: 7
Enter height: 10
Area = 747.32
Perimeter = 43.96
Note: In geometry, a cylinder does not have a perimeter in the usual sense. In exams, "perimeter of
a cylinder" generally means the circumference of its circular base, i.e., 2 πr .
(b) Explain mutability in Python. (4 Marks)
Definition
Mutability is the ability of an object to change its value after creation.
Objects in Python are of two types:
1. Mutable objects
2. Immutable objects

Mutable Objects
Objects whose contents can be modified after creation are called mutable objects.
Examples:
 List
 Dictionary
 Set
Example
L = [1, 2, 3]

L[0] = 10

print(L)
Output
[10, 2, 3]
The list changes after creation, so lists are mutable.

Immutable Objects
Objects that cannot be modified after creation are called immutable objects.
Examples:
 Integer
 Float
 String
 Tuple
Example
s = "Python"

s[0] = "J"
Output
TypeError: 'str' object does not support item assignment
Strings cannot be changed, so they are immutable.

Difference Between Mutable and Immutable Objects


Mutable Immutable
Can be modified Cannot be modified
Example: List, Set, Dictionary Example: String, Tuple, Integer
Same object changes New object is created
4(a) What is the use of Lambda expression? Explain how the map() function works. (2+2 Marks)
(i) Lambda Expression (2 Marks)
Definition
A lambda expression is an anonymous (nameless) function written in a single line using the lambda
keyword.
It is generally used for short functions and with functions like map(), filter(), and reduce().

Syntax
lambda arguments : expression

Example
square = lambda x: x*x

print(square(5))
Output
25
Explanation
Here,
lambda x: x*x
returns the square of x.
It is equivalent to:
def square(x):
return x*x

Uses of Lambda Expression


1. Creates short one-line functions.
2. Reduces code size.
3. Commonly used with map(), filter(), and reduce().

(ii) map() Function (2 Marks)


Definition
The map() function applies a function to every element of an iterable (list, tuple, etc.) and returns a
map object.

Syntax
map(function, iterable)

Example Using Normal Function


def square(x):
return x*x

L = [1, 2, 3, 4]

result = list(map(square, L))


print(result)
Output
[1, 4, 9, 16]

Example Using Lambda Function


L = [1, 2, 3, 4]

result = list(map(lambda x: x*x, L))

print(result)
Output
[1, 4, 9, 16]
Explanation
map() applies the function to each element of the list.
1 → 1² = 1
2 → 2² = 4
3 → 3² = 9
4 → 4² = 16

CU Exam Answer (2+2 Marks)


A lambda expression is an anonymous one-line function defined using the lambda keyword.
Example:
square = lambda x: x*x
print(square(4))
Output:
16
The map() function applies a function to each element of an iterable.
Example:
L = [1,2,3]

print(list(map(lambda x: x*x, L)))


Output:
[1, 4, 9]

4(b) Explain different access modifiers available in Python. Create a simple function which takes a
string as input and returns its length. (3+3 Marks)
(i) Access Modifiers in Python (3 Marks)
Definition
Access modifiers determine the accessibility of variables and methods of a class.
Python provides three access modifiers:
Access Modifier Syntax Accessibility
Public name Accessible everywhere
Protected _name Accessible in class and subclasses
Access Modifier Syntax Accessibility
Private __name Accessible only inside class

1. Public Member
class Student:
name = "Rahul"

s = Student()

print([Link])
Output
Rahul

2. Protected Member
class Student:
_marks = 90

s = Student()

print(s._marks)
Output:
90

3. Private Member
class Student:
__age = 20

s = Student()

# print(s.__age) # Error
Attempting to access __age directly gives:
AttributeError

CU Exam Answer (3 Marks)


Python supports three access modifiers:
1. Public (name)
2. Protected (_name)
3. Private (__name)
Private members cannot be accessed directly outside the class.

(ii) Function to Return Length of a String (3 Marks)


Program
def string_length(s):
return len(s)
text = input("Enter a string: ")

print("Length =", string_length(text))


Sample Output
Enter a string: Python
Length = 6

(a) Create a string with the value 'Computer Science'. Print the string as "cOMPUTER sCIENCE". (6
Marks)
We have to convert:
Computer Science
into
cOMPUTER sCIENCE
This means changing uppercase letters to lowercase and lowercase letters to uppercase.
Python provides the swapcase() method for this purpose.

Program Using swapcase()


s = "Computer Science"

print([Link]())
Output
cOMPUTER sCIENCE

Explanation
The swapcase() method:
 Converts uppercase letters to lowercase.
 Converts lowercase letters to uppercase.

6(b) Explain different types of operators in Python with examples. (5 Marks)


Python provides the following types of operators:
1. Arithmetic Operators
2. Relational (Comparison) Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

1. Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
Operator Meaning
% Modulus
// Floor division
** Exponentiation
Example
a = 10
b=3

print(a + b)
print(a % b)
print(a ** b)
Output:
13
1
1000

2. Comparison Operators
Operator Meaning
== Equal
!= Not equal
> Greater than
< Less than
>= Greater or equal
<= Less or equal
Example:
print(10 > 5)
Output:
True

3. Logical Operators
Operator Meaning
and Logical AND
or Logical OR
not Logical NOT
Example:
print(10 > 5 and 20 > 10)
Output:
True

4. Assignment Operators
Examples:
x=5
x += 2
print(x)
Output:
7

5. Bitwise Operators
Operator Meaning
& AND
` `
^ XOR
~ NOT
<< Left shift
>> Right shift
Example:
print(5 & 3)
Output:
1

6. Membership Operators
Operators: in, not in
Example:
L = [1, 2, 3]

print(2 in L)
Output:
True

7. Identity Operators
Operators: is, is not
Example:
a = [1, 2]
b=a

print(a is b)
Output:
True

6(a) Write a program in Python to display the following pattern. (5 Marks)


The pattern is:
1
01
101
0101
10101
Python Program
n=5

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

# Print spaces
for j in range(n - i):
print(" ", end="")

# Print pattern of 0 and 1


for j in range(i):
print((i + j) % 2, end="")

print()
(a) How is a tuple created in Python? Explain with example. (2–3 Marks)
Definition
A tuple is an ordered collection of elements enclosed within parentheses ( ). Tuples are immutable,
meaning their elements cannot be changed after creation.

Creating a Tuple
Example 1
t = (10, 20, 30, 40)

print(t)
Output
(10, 20, 30, 40)

Example 2: Tuple with Different Data Types


t = (1, "Python", 3.14)

print(t)
Output:
(1, 'Python', 3.14)

Single Element Tuple


A comma is necessary for a single-element tuple.
t = (5,)

print(type(t))
Output:
<class 'tuple'>

9(b) Differentiate between Syntax Error and Exception. (2–3 Marks)


Syntax Error Exception
Occurs due to incorrect syntax Occurs during program execution
Program does not start Program starts but stops due to error
Detected before execution Detected at runtime
Cannot be handled using try-except Can be handled using try-except

Example of Syntax Error


if x > 5
print(x)
Output:
SyntaxError: invalid syntax
Reason: Missing : after if.

Example of Exception
print(10 / 0)
Output:
ZeroDivisionError

9(d) Explain the utility of doc string. (2 Marks)


Definition
A docstring (documentation string) is a string literal used to describe the purpose of a module,
function, class, or method.
It is written inside triple quotes (''' ''' or """ """).

Example
def add(a, b):
"""Returns the sum of two numbers"""
return a + b

print(add.__doc__)
Output
Returns the sum of two numbers

Utility of Docstrings
1. Explains the purpose of code.
2. Improves readability and maintenance.
3. Used to generate documentation automatically.
4. Accessible using the __doc__ attribute.
8(a) Write a program in Python that can read a text file and display the number of characters,
number of words, and lines contained in the text file. (4 Marks)
Program
f = open("[Link]", "r")

content = [Link]()
# Number of characters
characters = len(content)

# Number of words
words = len([Link]())

# Number of lines
lines = len([Link]())

print("Number of characters =", characters)


print("Number of words =", words)
print("Number of lines =", lines)

[Link]()

Explanation
Step 1: Open the file
f = open("[Link]", "r")
 Opens the file in read mode ("r").

Step 2: Read file contents


content = [Link]()
 Reads the entire file as a string.

Step 3: Count characters


characters = len(content)
 len() returns the total number of characters, including spaces and newline characters.

Step 4: Count words


words = len([Link]())
 split() breaks the text into words.
 len() counts the number of words.

Step 5: Count lines


lines = len([Link]())
 splitlines() separates text line by line.
 len() counts the number of lines.
8(b) What are the usages of \t and * operators on string in Python? When does ValueError occur in
Python? (2+2+2 Marks)
(i) Use of \t in String (2 Marks)
\t is the tab escape sequence.
It inserts a horizontal tab space in a string.
Example
print("Name\tAge")
print("Rahul\t20")
Output
Name Age
Rahul 20
Thus, \t is used for formatting text in tabular form.

(ii) Use of * Operator on String (2 Marks)


The * operator is used for string repetition.
Example
print("Hi " * 3)
Output
Hi Hi Hi
Another example:
print("*" * 5)
Output:
*****
Thus, * repeats a string a specified number of times.

(iii) When does ValueError occur in Python? (2 Marks)


A ValueError occurs when a function receives an argument of the correct type but with an invalid
value.
Example
x = int("abc")
Output
ValueError: invalid literal for int()
Explanation:
 int() expects a string representing an integer.
 "abc" is not a valid integer.

CU Exam Answer (5 Marks)


A magic number is a number whose repeated sum of digits becomes 1.
def magic(n):
if n < 10:
return n == 1

s=0
while n > 0:
s += n % 10
n //= 10

return magic(s)

num = int(input("Enter number: "))


if magic(num):
print("Magic Number")
else:
print("Not Magic Number")

7(b) What is the utility of append() function? Explain with an example. (5 Marks)
Definition
The append() function is a list method used to add an element at the end of a list.

Syntax
[Link](element)

Example
L = [10, 20, 30]

[Link](40)

print(L)
Output
[10, 20, 30, 40]

Example with String


fruits = ["Apple", "Mango"]

[Link]("Orange")

print(fruits)
Output
['Apple', 'Mango', 'Orange']

Important Points
1. append() adds only one element at a time.
2. The new element is inserted at the end of the list.
3. The original list is modified.
4. It returns None.

Difference Between append() and extend()


append() extend()
Adds a single element Adds multiple elements
Element added as one item Elements added individually
Example
L = [1, 2]

[Link]([3, 4])
print(L)
Output:
[1, 2, [3, 4]]
Whereas:
L = [1, 2]

[Link]([3, 4])

print(L)
Output:
[1, 2, 3, 4]

(a) Define Python Interpreter. (2 Marks)


Definition
A Python Interpreter is a program that reads, translates, and executes Python code line by line.
Unlike compiled languages (such as C), Python is an interpreted language.
Example
print("Hello")
The interpreter directly executes the statement and displays:
Hello
CU Exam Answer
A Python interpreter is software that converts Python source code into machine-understandable
instructions and executes it line by line.

(b) Write down characteristics of Tuple data type. (2 Marks)


Characteristics of Tuple
1. Tuples are ordered collections.
2. Tuples are immutable (cannot be modified).
3. They can store heterogeneous data types.
4. Duplicate elements are allowed.
5. Elements are accessed using indexing.
6. Tuples are enclosed within ( ).
Example
t = (1, "Python", 3.14)
print(t)

(c) "There is no use of + operator in Python strings." — Comment. (2 Marks)


The statement is incorrect.
The + operator is used for string concatenation.
Example
s1 = "Hello "
s2 = "World"

print(s1 + s2)
Output
Hello World
Thus, the + operator joins two or more strings.

(d) Identify different string formats available in Python with example. (2 Marks)
Python provides three string formatting methods:
1. % Formatting
name = "Rahul"

print("Hello %s" % name)


Output:
Hello Rahul

2. format() Method
print("Hello {}".format("Rahul"))
Output:
Hello Rahul

3. f-String
name = "Rahul"

print(f"Hello {name}")
Output:
Hello Rahul

(e) Write down usage of pass statement with a small code snippet. (2 Marks)
Definition
The pass statement is a null statement. It does nothing and is used as a placeholder.
Example
for i in range(5):
if i == 3:
pass
print(i)
Output:
0
1
2
3
4
Another example:
class Student:
pass
Here, pass creates an empty class.

(f) Briefly discuss negative indexing in Python string. (2 Marks)


Negative indexing accesses elements from the end of a string.
Example
s = "Python"

print(s[-1])
print(s[-2])
Output:
n
o
Index Table
String : P y t h o n
Index : 0 1 2 3 4 5
Neg. :-6 -5 -4 -3 -2 -1
Thus, -1 refers to the last character.

(g) Let
List1 = ['1', 'a', 'abc', '2', 'Def', 'z']
[Link]()
print(List1)
What is the output?
Python sorts strings lexicographically (dictionary order) based on ASCII values.
ASCII values:
'1' < '2' < 'D' < 'a' < 'abc' < 'z'
Output
['1', '2', 'Def', 'a', 'abc', 'z']
Explanation
Uppercase letters come before lowercase letters in ASCII.

2(a) Write a program in Python to reverse a string given as user input. (3 Marks)
There are multiple ways to reverse a string in Python.

Method 1: Using Slicing (Recommended)


s = input("Enter a string: ")

rev = s[::-1]

print("Reversed string =", rev)


Sample Output
Enter a string: Python
Reversed string = nohtyP
Explanation
The slicing syntax is:
string[start : stop : step]
Here:
s[::-1]
means traverse the string from end to beginning (step = -1).

Method 2: Using Loop


s = input("Enter a string: ")

rev = ""

for ch in s:
rev = ch + rev

print("Reversed string =", rev)

CU Exam Answer (3 Marks)


s = input("Enter a string: ")

print("Reversed string =", s[::-1])

2(b) What do you mean by deep copy and shallow copy in Python? (3 Marks)
Shallow Copy
A shallow copy creates a new object, but nested objects are shared with the original object.
Example
import copy

a = [[1, 2], [3, 4]]

b = [Link](a)

b[0][0] = 100

print(a)
print(b)
Output
[[100, 2], [3, 4]]
[[100, 2], [3, 4]]
The change in b also affects a because nested objects are shared.

Deep Copy
A deep copy creates a completely independent copy of the object, including nested objects.
Example
import copy

a = [[1, 2], [3, 4]]

b = [Link](a)
b[0][0] = 100

print(a)
print(b)
Output
[[1, 2], [3, 4]]
[[100, 2], [3, 4]]
The original list remains unchanged.

Difference Between Deep Copy and Shallow Copy


Shallow Copy Deep Copy
Copies only outer object Copies entire object recursively
Nested objects are shared Nested objects are independent
Uses [Link]() Uses [Link]()

2(c) Write a code snippet illustrating MRO (Method Resolution Order) in multiple inheritance. (4
Marks)
What is MRO?
MRO (Method Resolution Order) determines the order in which Python searches for methods in
multiple inheritance.
Python follows the left-to-right C3 linearization algorithm.

Example
class A:
def show(self):
print("Class A")

class B(A):
def show(self):
print("Class B")

class C(A):
def show(self):
print("Class C")

class D(B, C):


pass

obj = D()

[Link]()

print([Link]())
Output
Class B

[<class '__main__.D'>,
<class '__main__.B'>,
<class '__main__.C'>,
<class '__main__.A'>,
<class 'object'>]

Explanation
When Python executes:
[Link]()
it searches in this order:
D → B → C → A → object
Since B contains show(), Python executes:
Class B

CU Exam Answer (4 Marks)


class A:
def show(self):
print("A")

class B:
def show(self):
print("B")

class C(A, B):


pass

obj = C()

[Link]()

print([Link]())
Output
A
[<class '__main__.C'>, <class '__main__.A'>,
<class '__main__.B'>, <class 'object'>]
Thus, MRO defines the order in which Python searches for methods in inheritance hierarchies.

3(a) Discuss the method to split Python strings. What is the function used to perform the said
operation? Give examples. (4 Marks)
Definition
Splitting a string means breaking a string into smaller parts (substrings) based on a separator.
Python uses the split() method to perform this operation.
Syntax
[Link](separator, maxsplit)
Parameters
 separator: Character/string at which splitting occurs (optional).
 maxsplit: Maximum number of splits (optional).
If no separator is given, splitting occurs at whitespace.

Example 1: Splitting by Space


s = "Python is easy"

result = [Link]()

print(result)
Output
['Python', 'is', 'easy']

Example 2: Splitting by Comma


s = "apple,mango,orange"

print([Link](","))
Output
['apple', 'mango', 'orange']

Example 3: Using maxsplit


s = "one two three four"

print([Link](" ", 2))


Output
['one', 'two', 'three four']
Only the first two splits are performed.

3(b) Differentiate dynamically typed language from statically typed language. Give suitable
examples. (4 Marks)
Dynamically Typed Language Statically Typed Language
Variable type is decided at runtime Variable type is decided before execution
No explicit type declaration required Type declaration is mandatory
More flexible More strict
Example: Python Example: C, Java

Python Example (Dynamically Typed)


x = 10
x = "Hello"

print(x)
Output:
Hello
The variable x changes from integer to string.

C Example (Statically Typed)


int x = 10;
x = "Hello"; // Error
The datatype of x cannot be changed.
4(b) Write a code snippet to sort a list containing names of all the months of a year in descending
order. (4 Marks)
Program
months = ["January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"]

[Link](reverse=True)

print(months)
Output
['September', 'October', 'November', 'May',
'March', 'June', 'July', 'January',
'February', 'December', 'August', 'April']

CU Exam Answer (4 Marks)


Opening a file is done using open() and closing is done using close().
f = open("[Link]", "r")

data = [Link]()

print(data)

[Link]()
Steps:
1. Open the file.
2. Read/Write data.
3. Close the file.

(d) Write a loop to iterate over the student records and print each student's name, age and subject
on separate lines. (3 Marks)
Program using items()
for name, details in student_records.items():
print("Name:", name)
print("Age:", details["Age"])
print("Subject:", details["Subject"])
print()
Output
Name: Aman
Age: 19
Subject: CMSA

Name: Binay
Age: 18
Subject: ZOOA

Explanation
student_records.items()
returns:
('Aman', {'Age': 19, 'Subject': 'CMSA'})
('Binay', {'Age': 18, 'Subject': 'ZOOA'})
Here:
 name stores the student's name.
 details stores the inner dictionary.

 6(a) Discuss different ways of


deleting an element from a
list with examples. (3 Marks)
 Python provides several methods to delete elements from a list.

 1. Using remove()
 Deletes the first occurrence of a specified value.
 L = [10, 20, 30, 20]

[Link](20)

print(L)
 Output
 [10, 30, 20]

 2. Using pop()
 Deletes an element by index and returns it.
 L = [10, 20, 30, 40]

x = [Link](2)

print(x)
print(L)
 Output
 30
[10, 20, 40]

 3. Using del
 Deletes an element or slice by index.
 L = [10, 20, 30, 40]

del L[1]

print(L)
 Output
 [10, 30, 40]

 4. Using clear()
 Removes all elements from the list.
 L = [1, 2, 3]

[Link]()

print(L)
 Output
 []

 6(b) What is the purpose of self

keyword? (1 Mark)
 self refers to the current object of a class.
 It is used to access instance variables and methods of the class.
 Example
 class Student:
def __init__(self, name):
[Link] = name

s = Student("Rahul")

print([Link])
 Output
Rahul
Here, [Link] belongs to the object s.

6(c) AccountBalance Class Program (6 Marks)


Program
class AccountBalance:

def __init__(self, accountnumber, customername, balance):


[Link] = accountnumber
[Link] = customername
[Link] = balance
def deposit(self, amount):
[Link] += amount
print("Deposited =", amount)
print("Current Balance =", [Link])

def withdraw(self, amount):


if [Link] - amount >= 1000:
[Link] -= amount
print("Withdrawn =", amount)
print("Current Balance =", [Link])
else:
print("Withdrawal not allowed.")
print("Minimum balance of 1000 must be maintained.")

def display(self):
print("Account No:", [Link])
print("Customer Name:", [Link])
print("Balance:", [Link])

# Creating object
a1 = AccountBalance(101, "Aman", 5000)

[Link]()

# Transaction 1: Deposit
[Link](2000)

# Transaction 2: Withdrawal
[Link](3000)

Sample Output
Account No: 101
Customer Name: Aman
Balance: 5000

Deposited = 2000
Current Balance = 7000

Withdrawn = 3000
Current Balance = 4000
If withdrawal violates minimum balance:
[Link](3500)
Output:
Withdrawal not allowed.
Minimum balance of 1000 must be maintained.

7(a) What is Lambda in Python? (2 Marks)


Definition
A Lambda function is an anonymous (nameless) function defined using the lambda keyword. It can
take any number of arguments but contains only one expression.
Syntax
lambda arguments : expression
Example
square = lambda x: x*x

print(square(5))
Output
25
Thus, lambda functions are used for short one-line functions.

7(b) Differentiate between mutable and immutable data type in Python. (3 Marks)
Mutable Data Type Immutable Data Type
Can be changed after creation Cannot be changed after creation
Same object is modified New object is created
Examples: List, Set, Dictionary Examples: String, Tuple, Integer
Example of Mutable Object
L = [1, 2, 3]
L[0] = 10
print(L)
Output:
[10, 2, 3]

Example of Immutable Object


s = "Python"
s[0] = "J"
Output:
TypeError
Hence, strings are immutable.

7(c) What is __init__? (1 Mark)


The __init__() method is a constructor in Python. It is automatically called when an object of a class
is created and is used to initialize object attributes.
Example
class Student:
def __init__(self, name):
[Link] = name
s = Student("Aman")

print([Link])
Output
Aman

7(d) Discuss with a code snippet, input and output to remove white space from any position of a
Python string. (4 Marks)
If we want to remove all white spaces from a string, we can use replace().
Program
s = input("Enter a string: ")

result = [Link](" ", "")

print("String after removing spaces:", result)


Sample Input
Python Programming Language
Output
String after removing spaces: PythonProgrammingLanguage

Explanation
replace(" ", "")
replaces every space " " with an empty string "".
Alternative: Remove Leading and Trailing Spaces
s = " Python "

print([Link]())
Output:
Python
strip() removes spaces only from the beginning and end, whereas replace() removes spaces from any
position.

8(a) List two advantages of using a set over a list for certain operations in Python. (2 Marks)
1. Sets automatically remove duplicate elements.
2. Membership testing (in) is faster in sets than in lists.
Example:
S = {1, 2, 2, 3}

print(S)
Output:
{1, 2, 3}

8(b) Explain the purpose of the pop() method for dictionaries in Python. (2 Marks)
The pop() method removes a specified key from a dictionary and returns its value.
Syntax
[Link](key)
Example
d = {"A": 10, "B": 20}

x = [Link]("A")

print(x)
print(d)
Output
10
{'B': 20}

8(c) What is the use of del statement? Explain with example. (2 Marks)
The del statement is used to delete variables, list elements, dictionary items, or entire objects.
Example
L = [10, 20, 30, 40]

del L[1]

print(L)
Output
[10, 30, 40]
Here, the element at index 1 is deleted.

8(d) Explain how error handling works in Python with suitable code snippet. (4 Marks)
Python handles errors using the try-except block.
Syntax
try:
statements
except Exception:
statements

Example
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))

print(a / b)

except ZeroDivisionError:
print("Division by zero is not allowed.")

except ValueError:
print("Invalid input.")
Sample Output 1
Enter a number: 10
Enter another number: 0
Division by zero is not allowed.
Sample Output 2
Enter a number: abc
Invalid input.
Explanation
 try block contains code that may produce an error.
 except block handles the error and prevents program termination.
Thus, exception handling makes programs robust and user-friendly.

(c) What are the differences between set and dictionary? (2 Marks)
Set Dictionary
Stores only values Stores key-value pairs
Uses {1,2,3} Uses {'A':1}
No duplicate elements allowed Keys must be unique
Elements are not accessed by keys Values are accessed using keys
Example
S = {1, 2, 3}
D = {'A': 1, 'B': 2}

(e) How does list constructor work? (2 Marks)


The list() constructor creates a list from an iterable such as string, tuple, or range.
Example 1
L = list("Python")
print(L)
Output:
['P', 'y', 't', 'h', 'o', 'n']
Example 2
L = list((1, 2, 3))
print(L)
Output:
[1, 2, 3]

(f) State the difference between .py and .pyc files. (2 Marks)
.py File .pyc File

Contains Python source code Contains compiled bytecode


Human readable Not human readable
Can be edited Cannot be easily edited

Created by programmer Generated automatically by Python


Example:
[Link]
[Link]

(g) How are the following statements different from each other? (2 Marks)
list2 = list1
list2 = [Link]()
1.
list2 = list1
This creates aliasing.
Both variables refer to the same list object.
list1 = [1, 2, 3]
list2 = list1

[Link](4)

print(list1)
Output:
[1, 2, 3, 4]
Changes in list2 affect list1.

2.
list2 = [Link]()
This creates a shallow copy.
list1 = [1, 2, 3]
list2 = [Link]()

[Link](4)

print(list1)
print(list2)
Output:
[1, 2, 3]
[1, 2, 3, 4]
Changes in list2 do not affect list1.

(h) “An item in a set cannot be accessed through index.” — Comment. (2 Marks)
The statement is True.
A set is an unordered collection, so its elements do not have fixed positions or indices.
Hence, indexing is not allowed.

2(b) Explain the use of split() method in Python. (2 Marks)


Definition
The split() method breaks a string into a list of substrings based on a separator.

Syntax
[Link](separator)
If no separator is specified, splitting occurs at whitespace.

Example
s = "Python is easy"

print([Link]())
Output
['Python', 'is', 'easy']

Example with Separator


s = "A,B,C"

print([Link](","))
Output
['A', 'B', 'C']

Creating a List Using range() (2 Marks)


The list() constructor converts a range object into a list.
Example 1
L = list(range(5))

print(L)
Output
[0, 1, 2, 3, 4]

Example 2: Even Numbers


even = list(range(2, 11, 2))

print(even)
Output
[2, 4, 6, 8, 10]

3(a) Discuss with examples the different modes to open a file in Python. (3 Marks)
Python uses the open() function to open files.
Syntax
file_object = open("filename", "mode")
Different file modes are:
Mode Meaning
r Read mode
w Write mode
a Append mode
x Create new file
rb Read binary file
Mode Meaning
wb Write binary file
r+ Read and write
a+ Append and read

1. Read Mode (r)


Opens an existing file for reading.
f = open("[Link]", "r")
print([Link]())
[Link]()

2. Write Mode (w)


Creates a new file or overwrites an existing file.
f = open("[Link]", "w")
[Link]("Hello Python")
[Link]()

3. Append Mode (a)


Adds data at the end of the file.
f = open("[Link]", "a")
[Link](" Welcome")
[Link]()

4. Binary Mode (rb, wb)


Used for binary files like images.
f = open("[Link]", "rb")
data = [Link]()
[Link]()

3(c) Explain with an example how exceptions are handled in Python. (4 Marks)
Definition
An exception is an error that occurs during program execution.
Python handles exceptions using the try-except block.

Syntax
try:
statements
except Exception:
statements

Example: Division by Zero


try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c=a/b

print("Result =", c)

except ZeroDivisionError:
print("Cannot divide by zero.")

3(b) Write a code snippet to sort a dictionary according to the values. (3 Marks)
Suppose we have the dictionary:
d = {'A': 30, 'B': 10, 'C': 20}
To sort according to values:
d = {'A': 30, 'B': 10, 'C': 20}

sorted_dict = dict(sorted([Link](), key=lambda x: x[1]))

print(sorted_dict)
Output
{'B': 10, 'C': 20, 'A': 30}
Explanation
 [Link]() returns key-value pairs.
 key=lambda x: x[1] sorts using the value part.
 dict() converts the result back into a dictionary.

Descending Order
sorted_dict = dict(sorted([Link](),
key=lambda x: x[1],
reverse=True))

print(sorted_dict)
Output:
{'A': 30, 'C': 20, 'B': 10}

(a) What will be the value of res after execution? (2 Marks)


Code:
[Link](i for i in list1 if i not in (list2 + list3))
Step 1: Compute list2 + list3
list2 + list3
gives
[2, 4, 6, 8, 1, 3, 7, 3]

Step 2: Check elements of list1


i Present in list2+list3? Included in res?
1 Yes No
2 Yes No
i Present in list2+list3? Included in res?

3 Yes No
4 Yes No
5 No Yes
Thus only 5 is added.
res = [5]
Output
[5]

(b) Write a code snippet to display all elements in list2 which are not in list1. (2 Marks)
Program
for i in list2:
if i not in list1:
print(i)
Output
6
8
Alternative using list comprehension
result = [i for i in list2 if i not in list1]

print(result)
Output:
[6, 8]

(c) Write a code snippet to display the duplicate elements of list3. (2 Marks)
Given:
list3 = [1, 3, 7, 3]
The duplicate element is 3.
Program
for i in set(list3):
if [Link](i) > 1:
print(i)
Output
3
Alternative
duplicates = []

for i in list3:
if [Link](i) > 1 and i not in duplicates:
[Link](i)

print(duplicates)
Output:
[3]

(d) Write a Python function that accepts a list as an argument and returns True if the list is empty
and False otherwise. (4 Marks)
Program
def is_empty(L):
if len(L) == 0:
return True
else:
return False

print(is_empty([]))
print(is_empty([1, 2, 3]))
Output
True
False

6(a) Write Python statements to print the following regarding current date and time. (4 Marks)
To work with date and time in Python, we use the datetime module.
import datetime

now = [Link]()

print("Date and Time:", now)


print("Year:", [Link])
print("Day of Week:", [Link]("%A"))
print("Month Name:", [Link]("%B"))
Sample Output
Date and Time: 2026-06-17 12:30:45.123456
Year: 2026
Day of Week: Wednesday
Month Name: June
Explanation
 [Link]() → returns current date and time.
 [Link] → extracts the year.
 strftime("%A") → prints day name.
 strftime("%B") → prints month name.
6(b) Write the purposes of super keyword. (2 Marks)
Definition
The super() function is used to access methods and constructors of the parent class from the child
class.
Purposes of super()
1. Calls the parent class constructor.
2. Accesses parent class methods.
3. Avoids explicitly using the parent class name.
4. Useful in inheritance and multiple inheritance.
Example
class Parent:
def show(self):
print("Parent class")

class Child(Parent):
def show(self):
super().show()
print("Child class")

c = Child()
[Link]()
Output
Parent class
Child class

6(c) Write Python statements to perform the following tuple operations. (4 Marks)
Suppose:
t = (10, 20, 30, 40, 50)

(i) Print all items from the third position to the end
print(t[2:])
Output
(30, 40, 50)
Explanation: Indexing starts from 0, so the third element has index 2.

(ii) Add a tuple to the end of another tuple


t1 = (1, 2, 3)
t2 = (4, 5)

t3 = t1 + t2

print(t3)
Output
(1, 2, 3, 4, 5)

(iii) Loop through a tuple


t = (10, 20, 30)

for x in t:
print(x)
Output
10
20
30

(iv) Multiply contents of a tuple


t = (1, 2, 3)

print(t * 3)
Output
(1, 2, 3, 1, 2, 3, 1, 2, 3)
Tuple multiplication repeats the tuple multiple times.

7(b) "try block can't exist without any except block." — Justify your answer. (4 Marks)
The statement is True.
In Python, a try block must be followed by at least one of the following:
 except
 finally
A try block alone is invalid and produces a SyntaxError.

Invalid Code
try:
x = 10 / 0
This gives:
SyntaxError: expected 'except' or 'finally' block

Correct Code
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
Output
Division by zero is not allowed.

Note
A try block may exist without except if there is a finally block.
Example:
try:
print("Hello")
finally:
print("Finished")
Thus, a try block cannot stand alone; it must be accompanied by except or finally.

8(b) Write a program that copies one Python script into another in such a way that all comment
lines are skipped and not copied in the destination file. (4 Marks)
Program
f1 = open("[Link]", "r")
f2 = open("[Link]", "w")

for line in f1:


if not [Link]("#"):
[Link](line)

[Link]()
[Link]()

print("File copied successfully.")

Explanation
 [Link] → Source file
 [Link] → Destination file
 startswith("#") checks whether a line is a comment.
 Comment lines are skipped and not copied.
Example
Suppose [Link] contains:
# This is a comment
print("Hello")
# Another comment
print("Python")
After execution, [Link] contains:
print("Hello")
print("Python")

8(c) How can a list be used as a QUEUE data structure with a proper code snippet? (3 Marks)
Definition
A Queue follows the FIFO (First In First Out) principle.
The first inserted element is removed first.
In Python lists:
 append() → Insert element at rear.
 pop(0) → Delete element from front.

Program
queue = []

# Insertion
[Link](10)
[Link](20)
[Link](30)

print("Queue:", queue)
# Deletion
x = [Link](0)

print("Deleted element:", x)
print("Queue after deletion:", queue)
Output
Queue: [10, 20, 30]
Deleted element: 10
Queue after deletion: [20, 30]

Explanation
Operation Function
Insert (Enqueue) append()
Delete (Dequeue) pop(0)
Since 10 was inserted first and removed first, the queue follows FIFO.

You might also like