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

Grade11 Python TestPaper WithAnswers

The document is a test paper for Grade 11 students on Data Science: Python, AI, and ML, covering multiple choice, short answer, and long answer questions. It includes questions on Python programming concepts, data structures, and object-oriented programming. Each question is accompanied by an answer key for self-study and revision.

Uploaded by

iguf11854
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 views24 pages

Grade11 Python TestPaper WithAnswers

The document is a test paper for Grade 11 students on Data Science: Python, AI, and ML, covering multiple choice, short answer, and long answer questions. It includes questions on Python programming concepts, data structures, and object-oriented programming. Each question is accompanied by an answer key for self-study and revision.

Uploaded by

iguf11854
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

Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

SCHOOLS OF SPECIALIZED EXCELLENCE


Delhi Board of School Education

TEST PAPER WITH ANSWERS


Data Science: Python, AI and ML | COD1102 | Grade XI
Maximum Marks: 80 Time Allowed: 3 Hours Units 1 – 4 (Full Syllabus)

General Instructions:
→ Section A contains 20 Multiple Choice Questions of 1 mark each.
→ Section B contains 10 Short Answer Questions of 3 marks each.
→ Section C contains 5 Long Answer Questions of 6 marks each.
→ Read each question carefully before answering. For code, write proper indentation.
→ The Answer Key section follows each question inline for self-study and revision.

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

SECTION A — Multiple Choice Questions [20 × 1 = 20 Marks]


Choose the most appropriate option. Each question carries 1 mark.

Q1. Which operator is used for Exponentiation (raising a number to a power) in Python? [1
mark]
(a) ^
(b) ** ✓ CORRECT
(c) ^^
(d) exp()
✎ Answer:
The correct answer is (b) **
💡 Concept Used:
In Python, the double-asterisk ** is the exponentiation operator. For example, 2 ** 3 means 2 raised to
the power 3, which equals 8. Python does NOT use the caret (^) for powers — the caret is actually the
bitwise XOR operator in Python, which is a common mistake. The built-in function pow(2, 3) also gives 8
but is a function call, not an operator.

Q2. What will the following statement print? print(10 % 3) [1 mark]


(a) 3
(b) 3.33
(c) 1 ✓ CORRECT
(d) 0
✎ Answer:
The correct answer is (c) 1
💡 Concept Used:
The % symbol is the Modulus operator in Python. It does NOT perform percentage calculations — instead,
it returns the REMAINDER after integer division. When we divide 10 by 3, the quotient is 3 and the
remainder is 1. So 10 % 3 = 1. This operator is very useful for checking whether a number is even or odd
(number % 2 == 0 means even), or for cycling through a fixed range of values.

Q3. Which keyword is used to define a function in Python? [1 mark]


(a) function
(b) define
(c) def ✓ CORRECT
(d) func
✎ Answer:
The correct answer is (c) def
💡 Concept Used:
In Python, the keyword def (short for 'define') is used to declare a function. A function is a named,
reusable block of code that performs a specific task. The syntax is: def function_name(parameters):
followed by an indented body. Other languages like JavaScript use 'function', C uses a return type, but

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

Python uses the simple and readable keyword 'def'. Functions promote the concept of code reuse — write
once, use many times.

Q4. Which Python data structure stores data in the form of key-value pairs? [1 mark]
(a) List
(b) Tuple
(c) Set
(d) Dictionary ✓ CORRECT
✎ Answer:
The correct answer is (d) Dictionary
💡 Concept Used:
A Dictionary in Python is a data structure that maps keys to values — just like a real-world dictionary
maps a word to its definition. Each entry has a unique key (like 'name') and an associated value (like
'Alice'). You access values using their key: student['name']. Dictionaries are defined using curly braces {}
with colon-separated pairs. They are perfect for storing structured, labelled data such as student records,
configuration settings, or any lookup table.

Q5. Which of the following data structures is IMMUTABLE — meaning it cannot be changed
after creation? [1 mark]
(a) List
(b) Dictionary
(c) Tuple ✓ CORRECT
(d) Set
✎ Answer:
The correct answer is (c) Tuple
💡 Concept Used:
Immutable means 'cannot be changed after creation'. A Tuple is Python's immutable sequence. Once you
create a tuple like t = (1, 2, 3), you cannot add, remove, or modify its elements — attempting to do so
causes a TypeError. This makes tuples reliable for storing data that should never change, such as GPS
coordinates, RGB colour values, or database records. In contrast, Lists are mutable (changeable), Sets can
have items added or removed, and Dictionaries can be updated.

Q6. What does len('Python') return? [1 mark]


(a) 5
(b) 6 ✓ CORRECT
(c) 7
(d) 4
✎ Answer:
The correct answer is (b) 6
💡 Concept Used:
The built-in function len() returns the number of characters (length) in a string, including spaces and
punctuation. The string 'Python' has exactly 6 characters: P-y-t-h-o-n. Indexing in Python starts at 0, so

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

the characters are at positions 0 through 5. len() works on all sequences — strings, lists, tuples, and
dictionaries — making it one of the most commonly used built-in functions.

Q7. Which symbol is used to write a single-line comment in Python? [1 mark]


(a) //
(b) /* */
(c) # ✓ CORRECT
(d) --
✎ Answer:
The correct answer is (c) #
💡 Concept Used:
Comments are lines in a program that are ignored by the Python interpreter — they exist only to explain
the code to human readers. In Python, a single-line comment starts with the hash symbol #. Everything
written after # on that line is treated as a comment. For example: x = 5 # this stores the number 5. Multi-
line comments can be written using triple quotes ''' or """. Good programmers always comment their
code to make it readable and maintainable.

Q8. What is the output of: print('Hi' * 3)? [1 mark]


(a) Hi Hi Hi
(b) HiHiHi ✓ CORRECT
(c) Hi3
(d) Error
✎ Answer:
The correct answer is (b) HiHiHi
💡 Concept Used:
In Python, the * operator when used between a string and an integer performs String Repetition — it
repeats the string that many times without any space in between. So 'Hi' * 3 produces 'HiHiHi'. This is
different from option (a) 'Hi Hi Hi', which would require joining with spaces. This operation is unique to
Python and does not cause an error because Python allows operators to work differently depending on
the data types involved — a concept called operator overloading.

Q9. Which list method adds an element to the END of a list? [1 mark]
(a) insert()
(b) add()
(c) append() ✓ CORRECT
(d) push()
✎ Answer:
The correct answer is (c) append()
💡 Concept Used:
The append() method is one of the most commonly used list methods. It adds a single element to the very
end of an existing list without affecting the other elements. For example: fruits = ['apple', 'banana'] →
[Link]('cherry') → ['apple', 'banana', 'cherry']. Note the difference: insert(index, value) adds at a

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

specific position, add() does not exist for lists (it exists for sets), and push() is from other languages like
JavaScript, not Python.

Q10. In Object-Oriented Programming, what do we call the blueprint or template used to


create objects? [1 mark]
(a) Object
(b) Class ✓ CORRECT
(c) Method
(d) Module
✎ Answer:
The correct answer is (b) Class
💡 Concept Used:
In Object-Oriented Programming (OOP), a Class is the blueprint or template that defines the structure and
behaviour of objects. Just like an architect's blueprint defines how a building should be constructed, a
class defines what attributes (data) and methods (functions) its objects will have. An Object is a specific
instance created from that class — like an actual building constructed from the blueprint. For example:
class Dog: defines the blueprint, and d = Dog('Buddy') creates a real object named Buddy.

Q11. What is the name of the special method in Python that is automatically called when a
new object is created from a class? [1 mark]
(a) __start__
(b) __init__ ✓ CORRECT
(c) __create__
(d) __begin__
✎ Answer:
The correct answer is (b) __init__
💡 Concept Used:
__init__ is called the Constructor method in Python. It is a special (or 'dunder') method — dunder stands
for 'double underscore'. This method is automatically invoked by Python every time a new object is
created from a class. Its job is to initialise the object's attributes with starting values. The first parameter
is always 'self', which refers to the specific object being created. For example: def __init__(self, name):
[Link] = name — when you write Dog('Buddy'), Python automatically calls __init__ and sets
[Link] = 'Buddy'.

Q12. Which of the following is the correct command to install a Python package called 'numpy'
using pip? [1 mark]
(a) python install numpy
(b) pip install numpy ✓ CORRECT
(c) install pip numpy
(d) import numpy
✎ Answer:
The correct answer is (b) pip install numpy
💡 Concept Used:

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

pip stands for 'Package Installer for Python'. It is a command-line tool that comes bundled with Python
and is used to download and install third-party modules (packages) from the Python Package Index
(PyPI). The syntax is simply: pip install package_name. Once installed, you use import numpy inside your
Python code to access it. Note that 'import' only loads an already-installed package into your program —
it does not download or install anything. You must run pip commands in the terminal/command prompt,
not inside Python code.

Q13. Which file opening mode appends new content to an existing file without deleting what is
already in it? [1 mark]
(a) "r" — Read mode
(b) "w" — Write mode
(c) "a" — Append mode ✓ CORRECT
(d) "x" — Create mode
✎ Answer:
The correct answer is (c) "a" — Append mode
💡 Concept Used:
Python's open() function accepts a mode argument that tells it how to access the file. The four main
modes are: 'r' (read-only, file must exist), 'w' (write — creates new or OVERWRITES existing content,
which means all old data is deleted), 'a' (append — opens the file and adds new content at the END
without removing existing data), and 'x' (exclusive create — creates a new file but fails if the file already
exists). Choosing the wrong mode, especially 'w' instead of 'a', is a common mistake that causes
permanent data loss.

Q14. What sequence of numbers does range(1, 6) produce? [1 mark]


(a) 0, 1, 2, 3, 4, 5
(b) 1, 2, 3, 4, 5 ✓ CORRECT
(c) 1, 2, 3, 4, 5, 6
(d) 0, 1, 2, 3, 4
✎ Answer:
The correct answer is (b) 1, 2, 3, 4, 5
💡 Concept Used:
The range() function generates a sequence of numbers. When called with two arguments range(start,
stop), it produces numbers starting from 'start' and going UP TO BUT NOT INCLUDING 'stop'. This is called
an exclusive upper bound. So range(1, 6) gives 1, 2, 3, 4, 5 — the number 6 is excluded. If you write
range(6), it starts from 0 and gives 0, 1, 2, 3, 4, 5. This off-by-one behaviour is very important to
remember. You can also add a third argument for step size: range(0, 10, 2) gives 0, 2, 4, 6, 8.

Q15. Which of the following is NOT a valid built-in data type in Python? [1 mark]
(a) int
(b) char ✓ CORRECT
(c) float
(d) bool
✎ Answer:
The correct answer is (b) char

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

💡 Concept Used:
Python does NOT have a 'char' data type. In languages like C or Java, 'char' stores a single character. In
Python, there is no need for this — a single character is simply a string of length 1, using the 'str' type.
Python's built-in types include: int (whole numbers), float (decimal numbers), str (text/strings), bool (True
or False), list, tuple, dict, set, and NoneType. This simplicity is one reason Python is beginner-friendly —
fewer data types to memorise.

Q16. What does 'Python'[1:4] return? [1 mark]


(a) Pyt
(b) yth ✓ CORRECT
(c) ytho
(d) thon
✎ Answer:
The correct answer is (b) yth
💡 Concept Used:
This question tests String Slicing. In Python, strings are indexed starting from 0. The string 'Python' has
characters at positions: P=0, y=1, t=2, h=3, o=4, n=5. The slice [1:4] means: start at index 1 (inclusive) and
stop at index 4 (exclusive). So we get characters at positions 1, 2, and 3, which are y, t, h — giving us 'yth'.
The key rule is: the end index is always excluded. Slicing is one of Python's most powerful string features
and works the same way on lists too.

Q17. Which set operation returns ONLY the elements that are common to BOTH sets? [1 mark]
(a) Union ( | )
(b) Difference ( - )
(c) Intersection ( & ) ✓ CORRECT
(d) Concatenation ( + )
✎ Answer:
The correct answer is (c) Intersection ( & )
💡 Concept Used:
Python sets support mathematical set operations. Intersection (&) finds elements present in BOTH sets —
like the overlapping region of a Venn diagram. For example: {1,2,3,4} & {3,4,5,6} = {3,4}. Union (|)
combines ALL elements from both sets with no duplicates. Difference (-) returns elements in the first set
that are NOT in the second. Concatenation (+) does not work on sets. These operations are very fast
because sets use a hash-table internally, making membership testing much quicker than in lists.

Q18. Which keyword in Python is used inside a child class to call a method from its parent
class? [1 mark]
(a) parent()
(b) base()
(c) super() ✓ CORRECT
(d) inherit()
✎ Answer:
The correct answer is (c) super()

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

💡 Concept Used:
super() is a built-in Python function used inside a child (derived) class to call methods from the parent
(base) class. It is most commonly used inside __init__ to ensure the parent class also initialises properly.
For example, if Dog inherits from Animal, writing super().__init__(name) inside Dog's __init__ calls
Animal's __init__ and sets the name attribute. Without super(), the child class would need to repeat all
the parent's initialisation code, which breaks the principle of code reuse that is central to OOP.

Q19. Which tkinter widget is used to accept single-line text input from the user? [1 mark]
(a) Label
(b) Entry ✓ CORRECT
(c) Text
(d) Button
✎ Answer:
The correct answer is (b) Entry
💡 Concept Used:
Tkinter is Python's built-in GUI (Graphical User Interface) library. It provides several widgets for building
windows: Label displays text or images, Button creates a clickable button, Entry creates a single-line text
input box (like a login form field), and Text creates a multi-line text area. Entry is the correct choice for
short inputs like names or passwords. To get the value typed by the user, you use entry_widget.get(). GUI
programming makes programs visual and interactive, allowing users who are not programmers to use
them easily.

Q20. How is Python best described as a programming language? [1 mark]


(a) Low-level compiled language
(b) High-level interpreted language ✓ CORRECT
(c) Machine-level assembly language
(d) Binary language
✎ Answer:
The correct answer is (b) High-level interpreted language
💡 Concept Used:
Python is described as a high-level interpreted language. 'High-level' means the code is written in human-
readable English-like syntax, far removed from the 0s and 1s a computer actually understands — this
makes Python easy to write and read. 'Interpreted' means Python code is executed line by line in real-time
by an interpreter, rather than being compiled entirely into machine code before running (like C or C++).
This makes Python beginner-friendly and great for debugging, because you see errors immediately. The
trade-off is that interpreted languages are generally slightly slower than compiled ones.

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

SECTION B — Short Answer Questions [10 × 3 = 30 Marks]


Answer each question in 4–6 sentences or with a short program. Show your reasoning.

Q1. What is a Flowchart? Draw and explain any THREE flowchart symbols with their purpose.
[3 marks]

✎ Answer:
A flowchart is a visual, diagrammatic representation of an algorithm or process. It uses standardised
geometric shapes connected by arrows to show the order of steps in a program or a decision-making
process. Flowcharts are written BEFORE actual code to plan the logic of a program. They make
complex programs easier to understand because they turn written steps into a visual picture.

The three key flowchart symbols are:


1. Terminal Symbol (Oval / Rounded Rectangle): This shape marks the START or STOP of a program.
Every flowchart must begin with an oval labelled 'Start' and end with one labelled 'Stop'. Without
these, the flowchart has no clear beginning or end.
2. Input / Output Symbol (Parallelogram): This shape represents any operation that reads data from
the user (input) or displays a result to the user (output). For example, reading a number the user
types, or printing a result on screen, would both use this symbol.
3. Decision Symbol (Rhombus / Diamond): This shape represents a point in the program where a
condition is checked. It always has a YES branch and a NO branch coming out of it, allowing the
program to follow different paths based on the result. For example: 'Is age >= 18?' — if Yes, go to
'Grant Access', if No, go to 'Deny Access'.
💡 Concept Used:
Concept: Algorithm Design and Program Planning. A flowchart helps a programmer think through the
logic step by step before writing any code, reducing errors. Pseudocode is a text-based alternative to
flowcharts — both serve the same purpose of planning.

Q2. What is indentation in Python? Why is it compulsory? Write an example showing correct
and incorrect indentation. [3 marks]
✎ Answer:
Indentation refers to the spaces or tabs added at the beginning of a line of code. In most
programming languages, indentation is optional and used only for readability. However, in Python,
indentation is MANDATORY — it is part of the language's syntax and is used to define code blocks. A
code block is a group of statements that belong together, such as the body of an if statement, a loop,
or a function.
Python typically uses 4 spaces per indentation level. Lines at the same indentation level belong to the
same block. If you break the indentation rules, Python raises an IndentationError and the program will
not run.

Correct Indentation:
age = 20
if age >= 18:
print('You are an adult') # correctly indented
print('You can vote') # same block
print('Program finished') # outside the if block
Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

Incorrect Indentation (causes IndentationError):


if age >= 18:
print('Adult') # ERROR — not indented, Python does not know this
belongs to if

💡 Concept Used:
Concept: Python Syntax and Code Blocks. Python's indentation rule enforces clean, readable code by
design. This is one of the features that makes Python stand out from other languages like Java or C, which
use curly braces {} to define blocks. The Python creator Guido van Rossum intentionally made indentation
mandatory so that all Python code looks consistent and readable.

Q3. Write a Python program that asks the user to enter a number and checks whether it is Even
or Odd. [3 marks]
✎ Answer:
This program uses the modulus operator (%) to find the remainder when the number is divided by 2. If
the remainder is 0, the number is even; otherwise, it is odd.

# Program to check Even or Odd

num = int(input('Enter a number: ')) # read input and convert to integer

if num % 2 == 0:
print(num, 'is an Even number')
else:
print(num, 'is an Odd number')

Output: Enter a number: 7


Output: 7 is an Odd number

💡 Concept Used:
Concepts Used: (1) input() reads user input as a string; int() converts it to an integer so we can do
arithmetic. (2) The Modulus operator % returns the remainder of division — any even number divided by
2 gives remainder 0. (3) The if-else control structure makes a decision based on a condition. If the
condition (num % 2 == 0) is True, the first block runs; if False, the else block runs.

Q4. Explain any FOUR methods of the Python List data structure with examples. [3 marks]
✎ Answer:
A List in Python is an ordered, mutable (changeable) collection that can hold multiple values of any
data type. Lists come with many built-in methods that allow us to manipulate them easily.

Method 1: append(element)
Adds a single element to the END of the list. The list grows by one item.
fruits = ['apple', 'banana']
[Link]('cherry')
Output: ['apple', 'banana', 'cherry']

Method 2: insert(index, element)

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

Inserts an element at a specific position (index). Elements after that position shift one place to the
right.
[Link](1, 'mango') # insert 'mango' at position 1
Output: ['apple', 'mango', 'banana', 'cherry']

Method 3: remove(element)
Searches the list for the first occurrence of the given element and removes it. If the element is not
found, it raises a ValueError.
[Link]('banana')
Output: ['apple', 'mango', 'cherry']

Method 4: sort()
Sorts the list in ascending order by default (A-Z for strings, smallest to largest for numbers). To sort in
descending order, use sort(reverse=True). This modifies the original list.
nums = [5, 2, 8, 1, 9]
[Link]()
Output: [1, 2, 5, 8, 9]

💡 Concept Used:
Concept: List Data Structure and Methods. Lists are one of the most versatile data structures in Python
because they are ordered (items maintain their position), mutable (can be changed after creation), and
allow duplicate values. The methods above are essential for day-to-day programming tasks such as
building shopping carts, tracking student records, or managing any collection of data.

Q5. Differentiate between a Tuple and a Set in Python with one example of each. [3 marks]
✎ Answer:
Both Tuple and Set are built-in Python data structures, but they have very different properties and are
used in different situations.

Property Tuple Set


Mutability Immutable — cannot be changed Mutable — can add/remove items
Order Ordered — maintains insertion Unordered — no guaranteed
order order
Duplicates Allowed — can have repeated NOT allowed — all values are
values unique
Syntax Uses parentheses ( ) Uses curly braces { }
Use Case Fixed data like coordinates, RGB Removing duplicates, set
operations

Tuple Example:
location = (28.6139, 77.2090) # latitude, longitude — should not change
print(location[0]) # access by index
Output: 28.6139

Set Example:
tags = {'python', 'coding', 'python', 'ai'} # duplicate 'python' added
print(tags)

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

Output: {'python', 'coding', 'ai'} # duplicate is automatically removed

💡 Concept Used:
Concept: Choosing the Right Data Structure. Understanding when to use a Tuple versus a Set is
important. Use a Tuple when data is fixed and order matters (e.g., storing a date as (day, month, year)).
Use a Set when you need fast membership checking or when you want to automatically eliminate
duplicate values from a collection.

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

Q6. What is a Dictionary in Python? Create a dictionary of 3 students with their marks and print
each student's name and marks using a loop. [3 marks]
✎ Answer:
A Dictionary is a built-in Python data structure that stores data as key-value pairs. Each key acts as a
unique identifier (like a label), and each value is the data associated with that key. Dictionaries are
defined using curly braces {}, with each entry written as key: value and entries separated by commas.
Keys must be unique and are typically strings or numbers; values can be of any type.
Dictionaries are ideal for representing structured data — for example, a student record where the key
is the student's name and the value is their marks.

# Creating a dictionary of students and their marks


student_marks = {
'Alice' : 92,
'Bob' : 78,
'Charlie' : 85
}

# Printing each student's name and marks using a for loop


for name, marks in student_marks.items():
print(name, 'scored', marks, 'marks')

Output: Alice scored 92 marks


Output: Bob scored 78 marks
Output: Charlie scored 85 marks

💡 Concept Used:
Concepts Used: (1) Dictionary creation with key-value pairs. (2) The .items() method returns each key-
value pair as a tuple, which we unpack into two variables (name, marks) in the for loop. (3) The for loop
iterates through the dictionary automatically. Dictionaries are one of the most powerful and widely-used
data structures in Python, used in web development, data science, and almost every real-world Python
application.

Q7. What is the purpose of the __init__ method in Python? Write a class called 'Rectangle' with
length and width attributes, and a method to calculate its area. [3 marks]
✎ Answer:
The __init__ method (also called the constructor) is a special method in Python classes that is
automatically called by Python every time a new object is created from that class. Its purpose is to
initialise the object's attributes — that is, to set the starting values for the object's data. Without
__init__, every object created from the class would have no attributes until you manually set them,
which is error-prone.
The first parameter of __init__ is always 'self', which is a reference to the specific object being
created. Any attributes defined as self.attribute_name = value inside __init__ become part of that
object.

class Rectangle:

def __init__(self, length, width):


[Link] = length # initialise length attribute
[Link] = width # initialise width attribute

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

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

# Creating two Rectangle objects


r1 = Rectangle(10, 5)
r2 = Rectangle(7, 3)

print('Area of r1:', [Link]())


print('Area of r2:', [Link]())

Output: Area of r1: 50


Output: Area of r2: 21

💡 Concept Used:
Concepts Used: (1) OOP — classes and objects. A class is the blueprint and an object is an instance of it.
(2) __init__ as constructor to set up initial state. (3) Instance methods — functions defined inside a class
that operate on the object's own data using 'self'. (4) Encapsulation — the Rectangle class bundles its
data (length, width) and behaviour (area()) together in one place.

Q8. What are modules in Python? How do you import a module? Give examples of at least
TWO built-in modules and show how to use them. [3 marks]
✎ Answer:
A module in Python is a file that contains Python code — specifically functions, classes, and variables
— that can be imported and reused in other Python programs. Instead of writing the same code again
and again, you can put it in a module and import it wherever needed. Python comes with a large
Standard Library of built-in modules that are ready to use.
There are three main ways to import a module:
1. import module_name — imports the whole module; access items using module_name.item
2. from module_name import function — imports only a specific function directly
3. import module_name as alias — imports with a short nickname for convenience

Example 1: The math module


import math

print([Link](81)) # square root of 81 = 9.0


print([Link]) # value of pi = 3.14159...
print([Link](4.9)) # round down = 4
print([Link](5)) # 5! = 120

Example 2: The random module


import random

print([Link](1, 6)) # random integer between 1 and 6


(dice roll)
print([Link](['a','b','c'])) # randomly picks one item from the
list

💡 Concept Used:
Concept: Modular Programming. The ability to import modules is one of Python's greatest strengths. It
allows programmers to stand on the shoulders of giants — using thousands of pre-written, tested
functions without having to write them from scratch. Built-in modules like math, random, and os are

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

always available. Third-party modules like numpy, pandas, and tensorflow must first be installed using
pip.

Q9. Write a Python program using a for loop that prints the multiplication table of any number
entered by the user (from 1 to 10). [3 marks]
✎ Answer:
A for loop in Python is used when we know in advance how many times we want to repeat a block of
code. Combined with range(), it gives us precise control over the iteration. For a multiplication table
from 1 to 10, we loop through the numbers 1 to 10 and multiply each by the user's chosen number.

# Multiplication Table Program

num = int(input('Enter a number for its table: '))

print(f'--- Multiplication Table of {num} ---')

for i in range(1, 11): # i goes from 1 to 10 (11 is excluded)


result = num * i
print(f'{num} x {i:2} = {result}')

Output: --- Multiplication Table of 7 ---


Output: 7 x 1 = 7
Output: 7 x 2 = 14
Output: 7 x 3 = 21 ...and so on up to 7 x 10 = 70

💡 Concept Used:
Concepts Used: (1) for loop with range(1, 11) — iterates exactly 10 times, with i taking values 1 through
10. (2) f-strings (formatted string literals) — the f before the quote allows variables inside {}. (3) :2 inside
the f-string pads the number with spaces for neat alignment. (4) int(input()) converts the user's text input
to an integer for arithmetic.

Q10. What is File Handling in Python? Write a program to write 'Hello World' to a file, then
read it back and display it. [3 marks]
✎ Answer:
File handling in Python refers to the ability of a program to create, read, write, and manage files
stored on a computer's disk. This is essential for data persistence — saving data so that it survives
even after the program closes. Without file handling, all data stored in variables is lost as soon as the
program ends.
Python's built-in open() function is used to work with files. It takes two arguments: the filename and
the mode ('r' for read, 'w' for write, 'a' for append). The recommended way to open files is using the
'with' statement, which automatically closes the file when the block ends, even if an error occurs —
preventing data corruption.

# Step 1: Write data to the file


with open('[Link]', 'w') as file:
[Link]('Hello World')
[Link]('\nThis is my first file in Python')

print('File written successfully.')

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

# Step 2: Read data back from the file


with open('[Link]', 'r') as file:
content = [Link]()
print('File Contents:')
print(content)

Output: File written successfully.


Output: File Contents:
Output: Hello World
Output: This is my first file in Python

💡 Concept Used:
Concepts Used: (1) open() with mode 'w' creates a new file (or overwrites an existing one) and opens it for
writing. (2) [Link]() writes a string to the file. The escape character \n adds a newline. (3) open() with
mode 'r' opens the file for reading. (4) [Link]() reads the entire file content as a single string. (5) The
'with' statement ensures the file is properly closed after the block, which is best practice in Python.

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

SECTION C — Long Answer Questions [5 × 6 = 30 Marks]


Answer each question in detail. Include explanations, comparisons, and code where required.

Q1. Explain in detail the four main Data Structures in Python — List, Tuple, Set, and Dictionary.
For each structure, describe its key properties, when it should be used, and provide a code
example demonstrating its creation and access. [6 marks]
✎ Answer:
Python provides four primary built-in data structures. Each is designed for a different purpose. A data
structure is essentially a way to organise and store multiple pieces of data so that we can access and
work with them efficiently. Understanding which one to use in which situation is a fundamental skill in
Python programming.

1. LIST — [ ] Ordered, Mutable, Allows Duplicates


A List is the most commonly used data structure in Python. It is an ordered collection, meaning items
retain their insertion order and can be accessed by their index (position number, starting from 0). Lists
are mutable — you can add, remove, or change items after creation. They allow duplicate values, so
the same item can appear multiple times. Lists are best used when you need a modifiable, ordered
collection — like a shopping cart, a list of student names, or a sequence of scores.
# Creating and using a List
marks = [85, 92, 78, 92, 65] # ordered, duplicates allowed
print(marks[0]) # access by index → 85
[Link](88) # add to end
[Link]() # sort in place
print(marks)
Output: [65, 78, 85, 88, 92, 92]

2. TUPLE — ( ) Ordered, Immutable, Allows Duplicates


A Tuple is like a List but with one critical difference: it is immutable. Once a tuple is created, its
contents cannot be changed — no adding, removing, or modifying elements. This makes tuples
reliable for data that must remain constant throughout the program. They are ordered and allow
duplicates. Tuples are used for fixed data such as GPS coordinates, RGB colour values, or function
return values where multiple pieces of data must be returned together.
# Creating and using a Tuple
coordinates = (28.6139, 77.2090) # latitude, longitude — must not
change
print(coordinates[0]) # access by index → 28.6139
print(coordinates[1]) # → 77.2090
# coordinates[0] = 30 → This would cause a TypeError (immutable)

3. SET — { } Unordered, Mutable, No Duplicates


A Set is an unordered collection that automatically removes duplicate values. Because sets are
unordered, you cannot access items by index — you can only iterate through them or check
membership. Sets are mutable so you can add and remove items. The defining feature of a set is that
every element is unique. Sets are perfect for removing duplicates from data, checking if an item exists
in a large collection quickly, and performing mathematical set operations (union, intersection,
difference).
# Creating and using a Set
votes = {'Alice', 'Bob', 'Alice', 'Charlie', 'Bob'} # duplicates entered

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

print(votes) # duplicates removed automatically


Output: {'Alice', 'Bob', 'Charlie'}
print('Alice' in votes) # fast membership check → True
[Link]('David') # add new item

4. DICTIONARY — { key: value } Ordered (Python 3.7+), Mutable, Unique Keys


A Dictionary stores data as key-value pairs — similar to a real dictionary where you look up a word
(key) to find its meaning (value). Keys must be unique; values can repeat. Dictionaries are ordered
(since Python 3.7) and mutable. They are the best structure for associating one piece of data with
another — like mapping student names to grades, product IDs to prices, or country names to capitals.
# Creating and using a Dictionary
student = {
'name' : 'Alice',
'age' : 17,
'grade' : 11
}
print(student['name']) # access by key → Alice
student['city'] = 'Delhi' # add new key-value pair
for key, value in [Link]():
print(key, ':', value)

💡 Concept Used:
Key Takeaway: Choose List when order matters and data changes. Choose Tuple when data is fixed.
Choose Set when uniqueness matters. Choose Dictionary when you need to look up values by a
meaningful label (key). These four structures cover virtually every data storage need in Python
programming.

Q2. Explain Object-Oriented Programming (OOP). What is Inheritance? Write a Python program
demonstrating inheritance with a parent class 'Animal' and two child classes 'Dog' and 'Cat'.
Your program must include: use of super(), method overriding, and creating objects. [6 marks]
✎ Answer:
Object-Oriented Programming (OOP) is a programming approach that organises code around objects
rather than functions and procedures. An object is a real-world entity that has two things: attributes
(data/properties) and methods (behaviours/functions). For example, a 'Car' object has attributes like
colour and speed, and methods like drive() and stop().
OOP is built on four key principles:
(1) Encapsulation: Bundling data and methods that work on that data together inside a class.
(2) Inheritance: A child class can acquire all properties and methods of a parent class and add its own.
(3) Polymorphism: The same method name can behave differently in different classes.
(4) Abstraction: Hiding the complex implementation details and showing only what is necessary.

What is Inheritance?
Inheritance is one of the most powerful features of OOP. It allows a new class (called the child class or
derived class) to inherit all the attributes and methods of an existing class (called the parent class or
base class). This promotes code reuse — you write the common functionality once in the parent, and
all child classes automatically get it. The child can also override inherited methods to give them
different behaviour, and can add entirely new methods of its own.

Python Program — Animal, Dog, and Cat:

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

# Parent class
class Animal:

def __init__(self, name, age):


[Link] = name
[Link] = age

def describe(self):
print(f'Name: {[Link]}, Age: {[Link]} years')

def speak(self):
print(f'{[Link]} makes a sound') # generic — will be
overridden

# Child class 1 — inherits from Animal


class Dog(Animal):

def __init__(self, name, age, breed):


super().__init__(name, age) # calls Animal's __init__ to set
name and age
[Link] = breed # Dog-specific attribute

def speak(self): # METHOD OVERRIDING


print(f'{[Link]} says: Woof!')

def fetch(self): # Dog-specific method


print(f'{[Link]} fetches the ball!')

# Child class 2 — also inherits from Animal


class Cat(Animal):

def __init__(self, name, age, indoor):


super().__init__(name, age)
[Link] = indoor

def speak(self): # METHOD OVERRIDING


print(f'{[Link]} says: Meow!')

# Creating objects and testing


d = Dog('Buddy', 3, 'Labrador')
c = Cat('Whiskers', 2, True)

[Link]() # inherited from Animal


[Link]() # overridden in Dog
[Link]() # Dog-specific

[Link]() # inherited from Animal


[Link]() # overridden in Cat

Output: Name: Buddy, Age: 3 years


Output: Buddy says: Woof!
Output: Buddy fetches the ball!

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

Output: Name: Whiskers, Age: 2 years


Output: Whiskers says: Meow!

💡 Concept Used:
Concepts Demonstrated: (1) Inheritance — Dog and Cat both inherit from Animal, so they get describe()
for free. (2) super().__init__() — calls the parent constructor to initialise shared attributes (name, age),
avoiding code repetition. (3) Method Overriding — both Dog and Cat define their own speak() method,
replacing the parent's generic version. (4) Polymorphism — both [Link]() and [Link]() call the same
method name but produce different output based on the object's type.

Q3. Write a complete Python program that creates a 'Student' class with attributes for name,
age, and marks. Include a method that calculates and returns the grade based on marks. Create
at least three student objects and print a formatted report. [6 marks]
✎ Answer:
This program demonstrates how OOP can model a real-world scenario — a school's student grading
system. Instead of using separate variables for each student, we create a Student class that bundles all
student data and the grading logic together. This makes the code organised, reusable, and easy to
extend.
The grading logic uses if-elif-else, which is a chain of conditions checked one by one. As soon as one
condition is True, its block runs and the rest are skipped.

class Student:

def __init__(self, name, age, marks):


[Link] = name
[Link] = age
[Link] = marks

def grade(self):
'''Returns grade based on marks using if-elif-else'''
if [Link] >= 90:
return 'A — Outstanding'
elif [Link] >= 80:
return 'B — Very Good'
elif [Link] >= 70:
return 'C — Good'
elif [Link] >= 60:
return 'D — Satisfactory'
else:
return 'F — Fail (Need Improvement)'

def report(self):
'''Prints a formatted student report card'''
print('=' * 40)
print(f' Student Name : {[Link]}')
print(f' Age : {[Link]}')
print(f' Marks : {[Link]} / 100')
print(f' Grade : {[Link]()}')
print('=' * 40)

# Creating student objects


s1 = Student('Alice', 16, 94)

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

s2 = Student('Bob', 17, 73)


s3 = Student('Charlie', 16, 55)

# Printing reports
students = [s1, s2, s3]
for student in students:
[Link]()

Output: ========================================
Output: Student Name : Alice
Output: Age : 16
Output: Marks : 94 / 100
Output: Grade : A — Outstanding
Output: ========================================
Output: Student Name : Bob ... Grade: C — Good
Output: Student Name : Charlie ... Grade: F — Fail

💡 Concept Used:
Concepts Demonstrated: (1) Class design — the Student class combines name, age, marks as attributes,
and grade() and report() as methods. (2) if-elif-else chain — the grade() method checks conditions in
order from highest to lowest. (3) List of objects — storing s1, s2, s3 in a list and looping through them
shows how OOP and data structures work together. (4) String formatting with f-strings — makes output
clean and readable. (5) Docstrings (triple quotes inside methods) — document what the method does.

Q4. Explain control structures and loops in Python with detailed examples. Your answer must
cover: (a) if/elif/else, (b) while loop, (c) for loop with range(), and (d) the use of break and
continue. [6 marks]
✎ Answer:
Control structures are the decision-making tools of programming. Without them, every program
would execute every line from top to bottom exactly once — which is not very useful. Control
structures let us make decisions, repeat actions, and skip certain parts of code based on conditions.
Python has two categories: conditional statements (if/elif/else) and loops (while and for).

(a) if / elif / else — Conditional Statements


The if statement checks a condition. If the condition is True, it runs the indented block. If False, it
moves to elif (else if), which checks another condition. If none of the conditions are True, the else
block runs as the default. This allows programs to make intelligent decisions based on data.
# Determine ticket price based on age
age = int(input('Enter age: '))

if age < 5:
print('Free entry')
elif age < 18:
print('Child ticket: Rs. 100')
elif age < 60:
print('Adult ticket: Rs. 250')
else:
print('Senior citizen ticket: Rs. 150')

(b) while Loop — Condition-Controlled Repetition


The while loop keeps repeating a block of code AS LONG AS its condition remains True. It is used when
we do not know in advance how many times the loop should run. We must be careful to ensure the
Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

condition eventually becomes False, otherwise the loop will run forever (called an infinite loop). A
common use is asking for input repeatedly until the user types something valid.
# Count down from 5 to 1
count = 5
while count > 0:
print(f'T-minus {count}...')
count -= 1 # count decreases each time, so condition
eventually becomes False
print('Blast off!')
Output: T-minus 5... T-minus 4... T-minus 3... T-minus 2... T-minus
1... Blast off!

(c) for Loop with range() — Count-Controlled Repetition


The for loop is used when we know exactly how many times to repeat. range(start, stop, step)
generates a sequence of numbers. The loop variable takes each value in that sequence, one at a time.
This is the most common type of loop in Python for processing lists, printing tables, and iterating over
sequences.
# Print squares of numbers 1 to 6
print('Number Square')
for n in range(1, 7): # n = 1, 2, 3, 4, 5, 6
print(f' {n} {n**2}')
Output: 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36

(d) break and continue — Loop Control


break immediately exits the loop entirely — even if the loop condition is still True. It is used when a
certain condition signals that there is no need to continue. continue skips the rest of the current
iteration and goes back to the top of the loop to check the condition again — it does NOT exit the
loop, it just skips one cycle.
# Demonstration of break and continue
for num in range(1, 11):
if num == 5:
continue # skip 5, go to next iteration
if num == 9:
break # stop the loop when we reach 9
print(num, end=' ')
Output: 1 2 3 4 6 7 8
Notice: 5 was skipped (continue), and 9, 10 never printed (break stopped the loop at 9).
💡 Concept Used:
Summary of When to Use Each: Use if/elif/else for making decisions. Use while when you loop until a
condition changes (number of iterations unknown). Use for when you loop a fixed number of times or
over a sequence. Use break to exit a loop early when a goal is achieved. Use continue to skip unwanted
iterations while staying in the loop.

Q5. Write a detailed explanation of Python Libraries covering: (a) what modules are and why
they are useful, (b) the math module with at least 5 functions, (c) the random module with 4
examples, (d) the os module and its uses, and (e) what tkinter is with a working GUI window
example. [6 marks]
✎ Answer:

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

One of Python's greatest strengths is its vast ecosystem of modules and libraries. Instead of writing
every function from scratch, Python programmers can import pre-built, tested, optimised code from
modules. This follows the programming principle of 'Do not reinvent the wheel'.

(a) What are Modules and Why are They Useful?


A module is a Python file (.py) containing functions, classes, and variables that can be reused across
multiple programs. Python's Standard Library includes over 200 built-in modules. Third-party modules
(numpy, pandas, flask, etc.) must be installed using pip. Using modules promotes code reuse, makes
programs shorter, and takes advantage of code written and tested by experts around the world.
import math # import the entire module
from math import sqrt # import only the sqrt function
import numpy as np # import with a short alias 'np'

(b) The math Module — Mathematical Functions


The math module provides access to mathematical functions beyond the basic arithmetic operators. It
must be imported before use.
import math

print([Link](144)) # Square root → 12.0


print([Link]) # Pi constant → 3.14159265358979
print([Link](7.9)) # Round DOWN to nearest integer → 7
print([Link](7.1)) # Round UP to nearest integer → 8
print([Link](6)) # 6! = 6×5×4×3×2×1 → 720
print([Link](2, 10)) # 2 raised to 10 → 1024.0
print([Link](100, 10)) # log base 10 of 100 → 2.0

(c) The random Module — Generating Random Values


The random module is used whenever a program needs unpredictable values — for games,
simulations, password generation, shuffling playlists, random sampling in data science, and more.
import random

# 1. Random float between 0 and 1


print([Link]()) # e.g. 0.7432...

# 2. Random integer in a range (inclusive both ends)


print([Link](1, 6)) # simulates a dice roll → 1 to 6

# 3. Random choice from a list


colours = ['red', 'green', 'blue', 'yellow']
print([Link](colours)) # picks one randomly

# 4. Shuffle a list in place


cards = ['Ace', 'King', 'Queen', 'Jack', '10']
[Link](cards)
print(cards) # order is now randomised

(d) The os Module — Interacting with the Operating System


The os module lets Python programs interact with the underlying operating system — creating and
deleting folders, listing directory contents, reading environment variables, and working with file paths.
This is extremely useful for automation scripts that organise files.
import os

Page
Data Science: Python, AI & ML (COD1102) | Grade 11 | DBSE

print([Link]()) # prints current working directory path


[Link]('my_new_folder') # creates a new folder
print([Link]('.')) # lists all files in current directory
print([Link]('my_new_folder')) # True if folder was created
[Link]('my_new_folder', 'renamed_folder') # rename a folder

(e) Tkinter — Building GUI Applications


Tkinter is Python's built-in standard GUI (Graphical User Interface) library. It allows you to build
desktop applications with windows, buttons, labels, text fields, and other visual components. A GUI
makes programs accessible to non-programmers who are not comfortable with the command line.
Tkinter uses an event-driven model — the program waits for user actions (clicks, key presses) and
responds to them.
The mainloop() call at the end is essential — it starts the event loop that keeps the window open and
responsive.
import tkinter as tk

# ── Create the main window ──


window = [Link]()
[Link]('My First Python GUI')
[Link]('350x200') # width x height in pixels

# ── Add a Label widget ──


greeting = [Link](window, text='Welcome to Python GUI!',
font=('Arial', 14), fg='navy')
[Link](pady=20) # pack places the widget in the
window

# ── Define what happens when button is clicked ──


def on_click():
[Link](text='Button was clicked!')

# ── Add a Button widget ──


btn = [Link](window, text='Click Me', command=on_click,
bg='navy', fg='white', width=15)
[Link](pady=10)

# ── Start the event loop (keeps window open) ──


[Link]()

💡 Concept Used:
Summary of Modules Covered: math — mathematical calculations; random — generating randomness
for games and simulations; os — system-level file and folder operations; tkinter — building visual desktop
applications. Together, these modules demonstrate how Python's Standard Library covers a huge range
of tasks without installing anything extra. For even more powerful libraries (numpy for arrays, pandas for
data, matplotlib for graphs), you can install them using pip.

~ End of Test Paper ~


All the best!

Page

You might also like