Python
Python
🔹 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)
print(t)
Tuple to List
t = (1, 2, 3)
l = list(t)
print(l)
print(result)
Output
Hello World
Here, the + operator combines the strings "Hello" and "World" into a single string.
2. format() Method
Introduced in Python 3 for better readability.
Example
name = "Rahul"
age = 20
print(f"Sum = {a+b}")
Output:
Sum = 30
4. String Concatenation Using +
Strings can also be joined using the + operator.
Example
name = "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
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.
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.
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.
result = [Link](",")
print(result)
Output
['apple', 'banana', 'mango']
3. Using maxsplit
s = "one two three four"
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.
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
print(x)
Output
[2, 3, 4, 5, 6, 7]
print(x)
Output
[1, 3, 5, 7, 9]
Explanation
Numbers increase by 2.
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 = ()
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)
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
T=tuple(L)
print(T)
Output
(1,2,3)
L=list(T)
print(L)
Output
[1,2,3]
print(tuple([Link]()))
Output
(('A',1),('B',2))
print(d[(1,2)])
Output
Python
Unpacking
a,b,c = t
print(a)
print(b)
print(c)
Output
10
20
30
Example
name = ["A","B","C"]
marks = [80,85,90]
z = list(zip(name,marks))
print(z)
Output
[('A',80),('B',85),('C',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
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}
[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]()
print(20 in s)
Output
True
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})
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
}
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.
3. Creating Dictionaries
Method 1: Using Curly Braces
d={
"A":1,
"B":2
}
print(d)
Output
{'A':1,'B':2}
print(d)
Output
{'A':1,'B':2}
d = dict(zip(keys,values))
print(d)
Output
{'A':10,'B':20,'C':30}
Empty Dictionary
d = {}
or
d = dict()
print(student["Name"])
Output
Rahul
KeyError
print(student["Marks"])
Output
KeyError
because key does not exist.
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
student["Age"] = 21
print(student)
Output
{'Age':21}
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'}
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
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}
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.
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
[Link]("Rahul\n")
[Link]("Computer Science")
[Link]()
Output in file
Rahul
Computer Science
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']
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
[Link](b"Python")
[Link]()
data = [Link]()
print(data)
[Link]()
Output:
b'Python'
Import Pickle
import pickle
student = {
"Name":"Rahul",
"Age":20
}
f = open("[Link]","wb")
[Link](student,f)
[Link]()
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.
f = open("[Link]","w",newline="")
writer = [Link](f)
[Link](["Name","Age","City"])
[Link](["Rahul",20,"Kolkata"])
[Link]()
f = open("[Link]","r")
reader = [Link](f)
[Link]()
Output:
['Name', 'Age', 'City']
['Rahul', '20', 'Kolkata']
f = open("[Link]","w",newline="")
writer = [Link](
f,
fieldnames=["Name","Age"]
)
[Link]()
[Link]({
"Name":"Rahul",
"Age":20
})
[Link]()
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]")
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
# 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.
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'
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.
writer = [Link](f)
[Link]()
f = open("[Link]", "r")
reader = [Link](f)
[Link]()
Output
['Name', 'Age', 'City']
['Rahul', '20', 'Kolkata']
Advantages of CSV
1. Easy data storage.
2. Compatible with Excel.
3. Efficient for tabular data.
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]
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
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]
Empty List
L = []
or
L = list()
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]
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]
del L[1:4]
print(L)
Output:
[10, 50]
del L
[Link](40)
print(L)
Output:
[10, 20, 30, 40]
Common Methods
append()
extend()
insert()
remove()
pop()
sort()
reverse()
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.
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]()
Creating Strings
Using Single Quotes
s = 'Python'
print(s)
Output:
Python
print(s)
Output:
Welcome
to
Python
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
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"]
print(result)
Output:
I Love Python
print("-".join(words))
Output:
2025-06-11
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
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
Expressions in f-Strings
a = 10
b = 20
print(f"Sum = {a+b}")
Output
Sum = 30
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
mid1 = len(s)//2 - 1
mid2 = len(s)//2
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])
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.
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
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.
class Dog(Animal):
pass
d = Dog()
[Link]()
Output:
Animal Sound
Example
list1 = [10, 20, 30]
list2 = list1
[Link](40)
print(list(zip(name, marks)))
Output:
[('A', 80), ('B', 85), ('C', 90)]
print(s[-2])
Output:
O
print(f"Welcome {name}")
Output:
Welcome Rahul
print(int(x))
Output:
25
It can convert strings, floats, etc., into integers.
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
(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)
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
print(s[::-1])
Output
dlrow olleH
Explanation
[start : stop : step]
Here step = -1, so the string is traversed in reverse order.
data = [Link]()
print(data)
[Link]()
The read() function returns the contents of the file as a string.
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.
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)
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]
print(result)
Output
[1, 4, 9, 16]
print(result)
Output
[1, 4, 9, 16]
Explanation
map() applies the function to every element of the list and returns the transformed values.
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
print([Link])
print(sqrt(16))
Output:
4.0
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
print([Link](36))
Output:
6.0
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'
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'>
Syntax
[Link][index]
where,
[Link][0] → Program name
[Link][1] → First argument
[Link][2] → Second argument
and so on.
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
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.
return fact
num=int(input("enter a number :"))
print(factorial(num))
Output:
120
return True
print(is_prime(7))
Output:
True
print(add(1,2,3,4,5))
Output:
15
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.
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.
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)
Example 2
def info(city, country):
print(city, country)
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
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
if num % 2 == 0:
print("Even")
else:
print("Odd")
Output
Enter a number: 7
Odd
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
4. Nested if Statement
Definition
An if statement inside another if statement is called a nested if.
Syntax
if condition1:
if condition2:
statements
if num > 0:
if num % 2 == 0:
print("Positive Even Number")
Output
Enter a number: 8
Positive Even 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
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
i=1
sum = 0
while i <= n:
sum += i
i+=1
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.
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.
print(i)
Output:
1
3
5
7
9
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.
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")
Output
Cannot divide by zero
except ValueError:
print("Invalid input")
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.
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.
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
s = Student()
Output
Constructor called
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.
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
def area(self):
return [Link] * [Link]
r = Rectangle(10, 5)
def area(self):
return 3.14 * [Link] * [Link]
c = Circle(7)
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.
class Sparrow(Bird):
def sound(self):
print("Chirp Chirp")
s = Sparrow()
[Link]()
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.
s1 = Student()
s2 = Student()
print([Link])
print([Link])
Output
CU
CU
s1 = Student("Rahul")
s2 = Student("Amit")
print([Link])
print([Link])
Output
Rahul
Amit
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.
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
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
print(max)
Output
20
(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.
content = [Link]()
[Link]()
Here, f is the file object.
t[1] = 50
Output
TypeError: 'tuple' object does not support item assignment
Thus, tuples are immutable.
(h) Identify different string formatting techniques available in Python with example. (2 Marks)
Python provides three string formatting methods:
1. % Formatting
name = "Rahul"
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.
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.
del subjects[0]
print(subjects)
Output:
['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
2. or Operator
Returns True if at least one condition is True.
Example
a = 10
b = 20
3. not Operator
Reverses the logical value.
Example
a = 10
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
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
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]
print(s[0]) # Indexing
print(s[1:4]) # Slicing
Output:
P
yth
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
Example
names = ["Rahul", "Amit", "Riya"]
marks = [80, 85, 90]
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.
print(A | B)
Output
{1, 2, 3, 4, 5}
print(A - B)
Output
{1}
print(A ^ B)
Output
{1, 4}
print(2 in A)
print(5 not in A)
Output
True
True
(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.
1. Modulus Operator
Returns the remainder after division.
print(10 % 3)
Output
1
2. String Formatting
Used for old-style string formatting.
name = "Rahul"
Syntax
lambda arguments : expression
print(square(5))
Output
25
print(add(10, 20))
Output
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.
if sum == n:
return True
else:
return False
if armstrong(num):
print("Armstrong Number")
else:
print("Not an Armstrong Number")
s = Student("Rahul")
print([Link])
Output
Rahul
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.
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.
print([Link]("t"))
Output
2
Note
If the element is not found, index() raises a ValueError.
[Link]("z")
Output:
ValueError: substring not found
continue
Skips the current iteration.
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
except ZeroDivisionError:
print("Division by zero is not allowed")
Output:
Division by zero is not allowed
print("A" in d)
Output
True
To check values:
print(2 in [Link]())
Output:
True
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
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
b[0][0] = 100
print(a)
print(b)
Output
[[1, 2], [3, 4]]
[[100, 2], [3, 4]]
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
Python Program
pi = 3.14
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.
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
Syntax
map(function, iterable)
L = [1, 2, 3, 4]
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
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
(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.
print([Link]())
Output
cOMPUTER sCIENCE
Explanation
The swapcase() method:
Converts uppercase letters to lowercase.
Converts lowercase letters to uppercase.
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
# Print spaces
for j in range(n - i):
print(" ", 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)
print(t)
Output:
(1, 'Python', 3.14)
print(type(t))
Output:
<class 'tuple'>
Example of Exception
print(10 / 0)
Output:
ZeroDivisionError
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]())
[Link]()
Explanation
Step 1: Open the file
f = open("[Link]", "r")
Opens the file in read mode ("r").
s=0
while n > 0:
s += n % 10
n //= 10
return magic(s)
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]
[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.
[Link]([3, 4])
print(L)
Output:
[1, 2, [3, 4]]
Whereas:
L = [1, 2]
[Link]([3, 4])
print(L)
Output:
[1, 2, 3, 4]
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"
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.
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.
rev = s[::-1]
rev = ""
for ch in s:
rev = ch + rev
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
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
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.
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")
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
class B:
def show(self):
print("B")
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.
result = [Link]()
print(result)
Output
['Python', 'is', 'easy']
print([Link](","))
Output
['apple', 'mango', 'orange']
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
print(x)
Output:
Hello
The variable x changes from integer to string.
[Link](reverse=True)
print(months)
Output
['September', 'October', 'November', 'May',
'March', 'June', 'July', 'January',
'February', 'December', 'August', 'April']
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.
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
[]
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.
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.
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]
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: ")
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}
(f) State the difference between .py and .pyc files. (2 Marks)
.py File .pyc File
(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.
Syntax
[Link](separator)
If no separator is specified, splitting occurs at whitespace.
Example
s = "Python is easy"
print([Link]())
Output
['Python', 'is', 'easy']
print([Link](","))
Output
['A', 'B', 'C']
print(L)
Output
[0, 1, 2, 3, 4]
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
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
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}
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}
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]()
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.
t3 = t1 + t2
print(t3)
Output
(1, 2, 3, 4, 5)
for x in t:
print(x)
Output
10
20
30
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")
[Link]()
[Link]()
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.