XI Informatics Practices
XI Informatics Practices
PATRON
EDITOR
CONTENT CREATORS:
1 SYLLABUS 1-2
✓ Computer Memory 5
✓ Software: Purpose and types of software 7
3 Unit-2 Introduction to Python
✓ Statements 30
✓ Lists in Python 45
✓ Dictionary in Python 53
✓ Introduction to NumPy 60
✓ Database Concepts 69
1 | Page
Relational data model: Concept of domain, tuple, relation, candidate key, primary key,
alternate key Advantages of using Structured Query Language, Data Definition Language, Data
Query Language and Data Manipulation Language, Introduction to MySQL, creating a database
using MySQL, Data Types
Data Definition: CREATE DATABASE, CREATE TABLE, DROP, ALTER
Data Query: SELECT, FROM, WHERE with relational operators, BETWEEN, logical operators, IS
NULL, IS NOT NULL
Data Manipulation: INSERT, DELETE, UPDATE
Unit 4: Introduction to the Emerging Trends
Artificial Intelligence, Machine Learning, Natural Language Processing, Immersive experience
(AR, VR), Robotics, Big data and its characteristics, Internet of Things (IoT), Sensors, Smart cities,
Cloud Computing and Cloud Services (SaaS, IaaS, PaaS); Grid Computing, Block chain technology.
Practical Marks Distribution
Sr. No. Unit Name Marks
1 Problem solving using Python programming language 11
2 Creating database using MySQL and performing Queries 7
3 Practical file (minimum of 14 python programs, and 14 SQL queries) 7
4 Viva-Voce 5
Total 30
5. Suggested Practical List
5.1 Programming in Python
1. To find average and grade for given marks.
2. To find sale price of an item with given cost and discount (%).
3. To calculate perimeter/circumference and area of shapes such as triangle, rectangle,
square and circle.
4. To calculate Simple and Compound interest.
5. To calculate profit-loss for given Cost and Sell Price.
6. To calculate EMI for Amount, Period and Interest.
7. To calculate tax - GST / Income Tax.
8. To find the largest and smallest numbers in a list.
9. To find the third largest/smallest number in a list.
10. To find the sum of squares of the first 100 natural numbers.
11. To print the first ‘n’ multiples of given number.
12. To count the number of vowels in user entered string.
13. To print the words starting with an alphabet in a user entered string.
14. To print number of occurrences of a given alphabet in each string.
15. Create a dictionary to store names of states and their capitals.
16. Create a dictionary of students to store names and marks obtained in 5 subjects.
17. To print the highest and lowest values in the dictionary.
5.2 Data Management: SQL Commands
1. To create a database
2. To create student table with the student id, class, section, gender, name, dob, and
marks as attributes where the student id is the primary key.
3. To insert the details of at least 10 students in the above table.
4. To display the entire content of table.
5. To display Rno, Name and Marks of those students who are scoring marks more than 50.
6. To display Rno, Name, DOB of those students who are born between ‘2005- 01-01’ and
‘2005-12-31’.
Suggested material
NCERT Informatics Practices - Text book for class - XI (ISBN- 978-93-5292-148-5)
2 | Page
Unit 1: Introduction to Computer System
Mind Map
3 | Page
3. Components of a computer system:
● Components: The hardware includes the CPU, memory, input/output devices, and
storage.
● CPU: The "brain" of the computer, consisting of:
o ALU (Arithmetic and Logical Unit): Performs arithmetic & logical operations.
o Control Unit: Manages instruction execution.
o Registers: Used to access data and instructions from memory during of the
execution of instructions.
● Input Devices: An input device or hardware that allow the user to input data,
instructions to the computer. Some common input devices are keyboard, mouse, scanner,
webcam, barcode reader etc.
● Output Devices: An output device or hardware that retrieves and presents the
result/information on the basis of input data in human understandable language. Some
Common output devices are Monitor, printer, speakers, plotter etc.
4 | Page
4. Computer Memory
It is used to store data / information temporarily or permanently.
● Units: From bit (smallest) to Yottabyte (largest).
bit->Nibble(4 bit)->Byte(8 bit)->KB->MB->GB->TB->PB-> EB->ZB->YB
● Types of memory:
5 | Page
Primary Memory:
● RAM (Volatile) – Random Access Memory stores data temporarily.
▪ It is a volatile memory that means it lose the data when power is turned off.
▪ A computer can't operate/run without primary memory.
▪ It is faster than secondary storage memory.
▪ Types of RAM (SRAM, DRAM)
● ROM (Non-volatile) – It retains the information, even when the power is turned off.
It stores the boot-up instructions (primarily used to start a computer). Instructions
in the ROM are written by the programmer, which are called firmware and BIOS.
Types of ROM:
● PROM Programmable Read Only Memory
● EPROM Erasable Programmable Read Only Memory
● EEPROM Electronic Erasable Read Only Memory
Cache Memory:
Cache memory is a small, high-speed memory located inside or very close to the CPU. It
temporarily stores frequently accessed data and instructions so the CPU can retrieve
them much faster than from the main memory (RAM). This reduces data access time,
improves processing speed, and increases overall system performance. Cache memory is
more expensive and has a smaller storage capacity as compare to RAM.
🡺 It helps in reducing the time taken to access data, thereby improving the overall
performance of the computer.
o High-speed temporary storage between CPU & RAM.
Secondary Memory:
Secondary memory is used for the permanent storage of data, files, software, and the
operating system. it is non-volatile Memory meaning data is not lost when the computer
is turned off.
➤ Characteristics of Secondary Memory:
● It is not directly accessible by the CPU; data must be loaded into primary memory
(RAM) before processing.
● It has large storage capacity compared to primary memory.
● It is slower than primary memory, but suitable for long-term data retention.
➤ Examples of Secondary Storage Devices:
Hard Disk Drive (HDD), Solid State Drive (SSD), Optical Disks (CD/DVD), Flash Drives
(Pen Drive, Memory Cards/SD Cards)
6 | Page
5. Software:Purpose and Types of Software (Follow Mind Map given in the
beginning of the chapter)
Software is a collection of programs that enables hardware to function. It governs the
operations of a computer system and is used for various purposes.
There are three types of software:
A. System Software: It act as an interface between user and hardware. System software is a
type of software that controls and manages the hardware components of a computer and
helps to install or run application software.
a) Operating System (OS):
• Acts as an interface between user and hardware.
• Manages files, memory, processes, and devices.
• Examples: Windows, Linux, macOS, Android
b) System Utilities:
• Programs that perform maintenance and support tasks.
• Examples: Antivirus, Disk Cleanup, File Compression Tools (WinZip)
c) Device Drivers:
• Specialized software that allows the OS to communicate with hardware devices.
• Each device (printer, keyboard, etc.) needs its own driver.
• Example: Printer Driver, Graphics Driver
8 | Page
7 Which of the following is a volatile memory?
a) RAM b) CD c) ROM d) Hard Disk
8 Arrange the following units of memory in decreasing order of storage:
i) KB (Kilobyte) ii) GB (Gigabyte) iii) MB (Megabyte) iv) TB (Terabyte)
a) iv) TB → ii) GB → iii) MB → i) KB
b) ii) GB → iv) TB → i) KB → iii) MB
c) iv) TB → iii) MB → i) KB → ii) GB
d) iv) TB → ii) GB → i) KB → iii) MB
9 Which of the following is NOT an input device?
a) Scanner b) Speakers c) Webcam d) Joystick
10 A ______ is an electronic pathway composed of cables that connects the major parts of a
computer system.
a) Motherboard b) Processor c) Bus d) Cache
Answer (Multiple Choice Questions)
1 (c) Electronic
2 (c) Hardware
3 (b) MS Office
6 (a) ii) IC → iv) LSI → iii) VLSI → i) SLSI
7 (b) Cache
8 (b) 0, 1
9 (a) RAM
10 (a) iv) TB → ii) GB → iii) MB → i) KB
11 (b) Speakers
12 (c) Bus
Assertion and Reasoning Questions
Choose correct option for given Assertion (A) and Reasoning (R)
a) Both A and R are true, and R is the correct explanation of A.
b) Both A and R are true, but R is NOT the correct explanation of A.
c) A is true, but R is false. d) A is false, but R is true.
1 Assertion (A): Computers use binary code (0s and 1s) to represent and process data.
Reason (R): Binary code is the fundamental language of computers, where 0 represents
OFF and 1 represents ON in the context of electronic switches.
2 Assertion (A): Main/Primary memory is volatile.
Reason (R): ROM, which is a part of main memory, is non-volatile
3 Assertion (A): It is always good to keep passwords encrypted while storing.
Reason (R): Encrypted data cannot be easily stolen by hackers.
4 Assertion (A): RAM (Random Access Memory) is volatile memory.
Reason (R): RAM retains its data even when the computer is powered off.
5 Assertion (A): Software designed for a school will work only for the school admin.
Reason (R): Customized software is tailor-made according to user requirements
6 Assertion (A): Cache memory is faster than RAM.
Reason (R): Cache memory is placed between the processor and RAM to reduce the
access time.
7 Assertion (A): ROM (Read-Only Memory) is used to store data that does not change
frequently.
Reason (R): ROM is volatile memory and loses data when the power is turned off.
8 Assertion (A): An operating system is an example of system software.
Reason (R): An operating system provides an interface between hardware and software
applications.
9 | Page
Answer (Assertion and Reasoning Questions)
1 (a) Both A and R are true, and R is the correct explanation of A
2 (b) Both A and R are true, but R is NOT the correct explanation of A.
3 (a) Both A and R are true, and R is the correct explanation of A
4 (c) A is true, but R is false.
5 (d) A is false, but R is true.
6 (a) Both A and R are true, and R is the correct explanation of A.
7 (c) A is true, but R is false.
8 (a) Both A and R are true, and R is the correct explanation of A.
Very Short Questions with Answers
1 Explain the role of an ALU in processing operations within a CPU.
Answer: The ALU (Arithmetic Logic Unit) performs arithmetic operations like addition
and subtraction, and logical operations such as comparisons, essential for processing
instructions.
2 Identify the type of memory that loses data when power is turned off and justify its use.
Answer: RAM (Random Access Memory) is volatile; it temporarily holds data and
instructions that the CPU is actively using for faster access.
3 Explain the use of utility software by naming one and describing its function.
1. Answer: Antivirus software like Windows Defender scans and removes malware,
ensuring system security and performance.
4 Earlier the computer size is used to be very big, but now it is very compact. What do you
think the reason behind its change?
Answer: Earlier the Computers were made with Vacuum Tubes, so the size of computers
was very big. But now a days VLSI (Very Large-Scale Integration) circuit chips are used
in computer; due to these invention computers are very compact in size.
Vacuum Tubes-> Transistors-> ICs -> LSI->VLSI
Remember: ICs : Integrated Circuit Chips
LSI: Large Scale Integrated Circuit Chips
VLSI: Very Large Scale Integrated Circuit Chips
5 Write the use of printer based on its function in a computer system.
Answer: A printer is an output device because it produces hard copies of digital
documents.
62. Differentiate between an operating system used in mobile devices and one used in
computers.
Answer: Android is a mobile OS designed for touchscreen interfaces, while Windows
is a computer OS supporting multitasking on desktops and laptops.
7 Explain the impact of John von Neumann's concept on modern computing.
Answer: He introduced the stored-program concept, enabling programs to be stored
in memory, forming the foundation of modern computer architecture.
8Discuss how the Control Unit contributes to the execution of instructions within the CPU.
Answer: The Control Unit (CU) directs the operation of the processor by fetching,
decoding, and coordinating instruction execution.
9 Justify the importance of USB in modern computing environments.
10 | Page
Answer: USB (Universal Serial Bus) standardizes connections for data transfer and
peripheral communication, enhancing device compatibility and ease of use.
10 Explain why a bit is considered the smallest unit of memory in a computer system
Answer: A bit (binary digit) represents the most basic unit of data, holding a value of
either 0 or 1, forming the basis for all computing processes.
12 | Page
● Storage Unit (Secondary Storage):
o Includes Hard Disk Drives (HDD), Solid State Drives (SSD), CDs, DVDs, and USB
drives to store data permanently.
Q2. What is hardware? What type of software is required to run hardware devices? Give one
example.
Answer:
● Hardware:
o Hardware refers to the physical components of a computer system, including
input devices, output devices, memory, and the processor.
o Examples: Keyboard, Mouse, Monitor, Hard Disk, Printer.
● Software Required to Run Hardware Devices:
o Device Drivers: These are specialized programs that allow the operating system
to communicate with hardware components.
o Example: A printer driver is required to make the printer function correctly with
a computer.
Q3. Name the memory that is fastest in a computer system. What is the role of such memory,
and where is it placed?
Answer:
● Fastest Memory: Cache Memory
● Role of Cache Memory:
o Cache memory stores frequently used data and instructions close to the CPU.
o It reduces the time taken to access data from the main memory (RAM), thereby
improving system speed and efficiency.
● Placement of Cache Memory:
o It is located between the CPU and RAM or integrated directly inside the CPU chip
Q4. What is the purpose of using secondary memory? Give some examples of secondary memory
devices. What is the storage capacity of a CD?
Answer:
● Purpose of Secondary Memory:
o Secondary memory is used to store data permanently and retrieve it when
required.
o it supports long-term data storage and retains data even when the power is
turned off
● Examples of Secondary Memory Devices:
o Hard Disk Drive (HDD) ,Solid State Drive (SSD), Compact Disc (CD)
o Digital Versatile Disc (DVD), Pen Drive (USB Flash Drive)
● Storage Capacity of a CD:
o A CD-ROM (Compact Disc Read-Only Memory) typically has a storage capacity of
700 MB (Megabytes).
Case-Based Questions and Competency Based Question with Answer
Q1. Rohit bought a computer but noticed it runs very slowly when multiple applications are
opened. He asked a technician for advice on upgrading his system.
Give suitable answer of the following:
a) Which component is most likely responsible for multitasking performance?
● RAM, Hard Disk, Processor, Motherboard
b) What is the role of RAM in computer performance?
13 | Page
c) If upgrading RAM is not an option, suggest one other way to improve the system’s speed.
d) Rohit also wants to increase storage capacity. Which type of storage device should he
choose for faster performance: HDD or SSD? Why?
e) What utility software can help optimize system performance?
Answer:
a) The component most responsible for multitasking performance is: RAM
b) Role of RAM in computer performance:
RAM (Random Access Memory) temporarily stores data that the CPU needs while
running applications. More RAM allows smoother multitasking and faster performance.
c) Alternative way to improve system speed if upgrading RAM is not an option:
Use an SSD (Solid State Drive) instead of an HDD to speed up data access and system
performance.
d) Best storage device for faster performance:
SSD (Solid State Drive) is better than HDD because it has faster read/write speeds,
reducing loading times and improving overall system responsiveness.
e) Utility software for optimizing system performance:
• Disk Cleanup (removes unnecessary files), Disk Defragmenter (for HDDs)
• Task Manager (to manage background processes)
• Antivirus software (to remove malware that slows down the system)
Q2. Computers have transformed our lives, bringing both advantages and challenges. Analyze
the following aspects and state whether they have a positive or negative impact:
Give suitable answer the following:
a) Automation of jobs – Does it create employment opportunities or reduce them?
b) Health concerns – How does prolonged computer usage affect health?
c) Social networking – Has it improved communication or caused social isolation?
d) Accuracy of calculations – Does using computers in financial transactions reduce errors?
e) Cybersecurity issues – How has increased digitization affected data security?
Answer:
Impact of Computers on Society:
a) Automation of jobs: Negative impact: It reduces employment in traditional sectors by
replacing manual labor with machines. However, it creates new jobs in tech-related fields.
b) Health concerns: Negative impact: Prolonged computer usage can cause eye strain, back
pain, and carpal tunnel syndrome.
c) Social networking: Both positive and negative: It improves communication but can also
lead to social isolation if people spend too much time online instead of engaging in face-to-
face interactions.
d) Accuracy of calculations: Positive impact: Computers reduce human errors in financial
transactions, ensuring higher accuracy and reliability.
e) Cybersecurity issues: Negative impact: Increased digitization has led to cyber threats like
hacking, phishing, and data breaches.
Q3. Neha was working on an important project but forgot to save her work. Unfortunately, her
system crashed due to power failure.
Give suitable Answer of the following:
a) Will she be able to recover the unsaved data? Why or why not?
b) Which type of memory is responsible for temporary storage, and why is it lost after
shutdown?
c) Suggest one precaution Neha can take in the future to avoid data loss.
14 | Page
d) Name a hardware device that can help prevent unexpected shutdowns.
e) Between an external hard disk and a USB pen drive, which is better for long-term data
storage, and why?
Answer:
Answer:
Graphics Card and Performance
a) Primary function of a graphics card:
It processes and renders graphics for gaming, video editing, and visual applications.
b) Do all computers need a dedicated GPU?
No, basic tasks (browsing, office work) can be handled by integrated graphics.
Answer:
Mr. Sharma’s Laptop Purchase Decision
1(c) Windows comes pre-installed, and its cost is included in the laptop price.
2(c) Operating system (like Windows or Linux).
3(a) MS Excel
4(b) Windows Defender (Antivirus)
5(d) All of the above (Internet Explorer, Mozilla Firefox, Google Chrome).
16 | Page
Q7. Rahul frequently uses his personal computer for online banking, shopping, and work-related
activities. Recently, he noticed some unusual transactions in his bank account, which made
him suspect a security breach.
Answers:
a) All of the above (Weak passwords, malware, and phishing attacks can all lead to security
breaches).
b) Precautions for a strong password:
• Use a combination of uppercase, lowercase, numbers, and special characters
• Avoid using common words or personal information
c) Antivirus and Anti-Malware Software (e.g., Windows Defender, McAfee, or Norton)
d) Public Wi-Fi risks: Hackers can intercept data using man-in-the-middle attacks.
Rahul should use a VPN (Virtual Private Network) to encrypt his data.
e) Online safety practices:
• Avoid clicking on suspicious links or emails from unknown senders
• Enable two-factor authentication (2FA) for online accounts
Q8. A student deleted some files from a computer. Initially, the files were moved to the Recycle
Bin. Later, the student emptied the Recycle Bin but still recovered the files using recovery
software.
Give suitable answer of the following:
(a) Where do deleted files first go in Windows computers?
(b) Can files be recovered after emptying the Recycle Bin?
(c) Which software is used to restore deleted files?
(d) Why should sensitive files be securely deleted?
(e) Mention one risk of improper data deletion
Answers
(a) Deleted files first go to the Recycle Bin.
(b) Yes, files can still be recovered after emptying the Recycle Bin until the data is overwritten.
(c) Recovery software / Data recovery software is used to restore deleted files.
17 | Page
(d) Sensitive files should be securely deleted to prevent unauthorized access or misuse of
data.
(e) One risk of improper data deletion is data theft or privacy leakage.
Q9. A student uses a computer at home for online classes, gaming, drawing, and document
preparation. The computer uses Windows operating system and paint software.
Give suitable answer of the following:
a) Which software acts as an interface between user and hardware?
b) Is Paint an application software or system software?
c) Name one general purpose software from the case study.
d) Which type of software controls hardware devices?
e) Why is application software important for users?
Answers:
(a) Operating System (Windows) acts as an interface between user and hardware.
(b) Paint is an Application Software.
(c) One general purpose software from the case study is Paint.
(d) System Software controls hardware devices.
(e) Application software is important because it helps users perform specific tasks such as
drawing, gaming, document preparation, and online learning.
Q10. A photographer stores thousands of photos and videos on a computer for editing and
future use. The files are very large in size and need to be stored safely for a long time.
Give suitable answer of the following:
(a) Which type of memory is most suitable for storing large files permanently? Why?
(b) A photographer accidentally deletes an important project folder. The files are not in the
Recycle Bin. Suggest one possible way to recover the files and one precaution to improve
recovery chances.
(c) The photographer keeps all files only on one hard disk. Analyze one major risk and suggest
a better storage strategy.
(d) A photographer wants to share selected photos online while keeping private client data
secure. Which security measures should be followed?
(e) Why is cache memory important during photo or video editing?
Answers:
(a)Secondary Memory is most suitable because it can store large amounts of data
permanently.
(b) (i) Use data recovery software to recover deleted files.
(ii) Stop using the storage device immediately to avoid overwriting data.
(c) Risk: Data loss due to hard disk failure.
Better Strategy:
● Keep backup copies in external storage or cloud storage.
● Use multiple storage devices for safety
(d) (1) encrypt sensitive files
(2) Use strong passwords
(3) Keep backup regularly
(4) Securely delete unwanted confidential files
(e) Cache memory stores frequently used data temporarily and helps the CPU access data
faster, improving editing performance.
18 | Page
UNIT 2: INTRODUCTION TO PYTHON
Basics Of Python
Mind Map
• Script Mode:
○ A Python program is written in a file (.py), which are then executed as a whole
by the Python interpreter.
○ This mode is suited for developing larger programs or when you want to run a
sequence of Python commands that are stored in a file.
4. Indentation
In Python, indentation is critical and is used to define the structure of code blocks. Unlike
many other programming languages, Python does not use braces {} to define blocks of code
(like loops or functions). Instead, it uses whitespace indentation.
• Error if Inconsistent: If you mix spaces and tabs, or if the indentation is inconsistent,
Python will throw an Indentation Error.
Example:
if a==0:
print('Hello, World!') # print statement part of if block
print('Hello, World!') # print statement not part of if block
5. Identifiers
Identifiers in Python are names used to identify variables, functions, classes, and other objects.
Rules for naming identifiers:
○ Must begin with a letter (A-Z or a-z) or an underscore (_).
○ Can be followed by letters, digits (0-9), or underscores.
○ Case-sensitive: Schoolname, SchoolName, and SCHOOLNAME all three are
different identifiers in python.
○ Cannot be a keyword (e.g., if, else, def, etc.).
Example: my_variable = 10
Valid Identifiers: Rollno, ROLLNO, ROLL_NO, RNO92A, _RNO, RFILE, true, If
Invalid Identifiers: break(keyword), [Link], 19Rno, Roll No, True, if
21 | Page
6. Keywords
Keywords are reserved words in Python that have special meaning and cannot be used as
identifiers.
Example: if, else, elif, for, while, def, class, import
7. Constants(Literals)
Values that do not change during execution of program are called constants(literals). In
Python, there are no built-in constants (values that cannot be changed once set). However, it’s
a common convention to use uppercase letters for constant-like values, signaling that they
should not be changed.
○ Example: PI = 3.14159 MAX_USERS = 1000
8. Variables
A variable in Python is an identifier whose value can be changed. Python is a dynamically
typed language, meaning the type of a variable is determined at runtime, based on the value
it holds.
• Declaring Variables: You don't need to specify the type of the variable; Python
automatically assigns the appropriate type based on the value.
o Example:
▪ age = 25 # This assigns an integer value to 'age'
▪ name = "John" # This assigns a string value to 'name'
• Reassigning Variables: Python allows the reassignment of variables to different data
types.
age = 25 # 'age' contains value of integer type
age = "twenty-five" # now 'age' contains value of string type
9. Types of Operators
Python supports various types of operators to perform operations on variables and values:
• Arithmetic Operators (+, -, *, /, //, %, **): Used for mathematical calculations.
Operator Description Example
X=10, y=20
+ Addition Adds values on either side of the operator. >>>X + y
>>>30
- Subtraction Subtracts the right-hand operand from the >>>X – y
left-hand operand. >>>-10
* Multiplication Multiplies values on either side of the operator >>>X * y
>>>200
/ Division Divides the left-hand operand by the right-hand >>>X / y
operand and always returns a float data type. >>>0.5
// Floor The division of operands where the result is the >>>9//2
Division quotient in which the digits after the decimal >>>4
point are removed. But if one of the operands is ------------------
negative, the result is floored, i.e., rounded away >>>9.0//2
from zero (towards negative infinity) − >>>4.0
% Modulus Divides left hand operand by right hand operand >>>X % y
and returns remainder >>>10
** Exponent Performs exponential (power) calculation on >>>X**2
operators. a ** b means a raised to the power b. >>>100
22 | Page
X variable in Capital letter and y variable in small letter
Note: Python is case sensitive This means that uppercase and lowercase letters
are treated differently
Note: + and * operators are also used in Sequence Manipulation for
concatenation and repetition respectively.
for e.g. X= 'Welcome' Y='2025'
>>>X+Y
>>>Welcome2025
X='Welcome' Y=2
>>>X*Y
>>>WelcomeWelcome
• Relational Operators (==, !=, >, <, >=, <=): Used to compare two [Link] either
returns True or False according to the given condition.
Operator Description Example
X=20, y=10
== If values of two operands are equal, then returns True >>> (X == y)
otherwise False. >>> False
!= If values of two operands are not equal, then returns >>> (X != y)
True otherwise False. >>> True
> If the value of left operand is greater than the value of >>> (X> y)
right operand, then returns True otherwise False. >>> True
< If the value of left operand is less than the value of right >>> (X < y)
operand, then returns True otherwise False. >>> False
>= If the value of left operand is greater than or equal to the >>> (X >= y)
value of right operand, then returns True otherwise >>> True
False.
<= If the value of left operand is less than or equal to the >>> (X <= y)
value of right operand, then returns True otherwise >>> False
False.
Note: These operators can also be used for comparing string values. Python
compares strings lexicographically (alphabetical order used in English dictionary)
using Unicode values of characters. Unicode value of uppercase letters A=65, B=66 and
so on till Z=90 and that of lowercase letters a=97, b=98 and so on till z=122 and for digits
Unicode for 0 to 9 is 48 to 57.
e.g. >>> X= 'ABc'
>>> Y= 'Abc'
>>> X>Y # evaluates to False
• Assignment Operators (=, +=, -=, *=, /=,%=,**=,//=): Used to assign values to variables.
It evaluates right hand side expression and then assigns to identifier on the left hand
side of the operator.
Operator Description Example
23 | Page
+= It adds right operand to the left operand and X += Y is equivalent
assigns the result to left operand to X = X + Y
-= It subtracts right operand from the left operand X -= Y is equivalent
and assigns the result to left operand to X = X – Y
*= It multiplies right operand with the left operand X *= Y is equivalent
and assigns the result to left operand to X = X * Y
/= It divides left operand with the right operand and Y /= Z is equivalent
assigns the result to left operand to Y = Y / Z
%= It takes modulus using two operands and assigns m %=n is equivalent
the result to left operand to m = m % n
• Membership Operators (in, not in): Used to test membership of an item in a sequence
such as strings, lists, or tuples. There are two membership operators as explained below –
str= 'KVS 2025 Class IP'
Val='IP' in str
print(Val)
#output : True
Operator Description Example
24 | Page
• Identity Operators (is, is not): Used to compare the memory location of two objects.
is, is not are the identity operators both are used to check if two values are located on
the same part of the memory. Two variables that are equal does not imply that they are
identical.
25 | Page
To change the order of evaluation, use parentheses.
Operator precedence and associativity of operators decides the order in which parts of an
expression are evaluated. Precedence tells us which operators should be evaluated first, while
associativity determines the direction (left to right or right to left) in which operators with the
same precedence are evaluated.
11. Data Types
Data type identifies the type of data which a variable can hold and the operations that can be
performed on those data.
Python supports a variety of built-in data types that can store values:
• Numeric Types:
○ int: Integer numbers (e.g., 5, -3).
○ float: Floating-point numbers (e.g., 3.14, -0.001).
• Sequence Types:
○ str: Strings (e.g., "Hello", 'Python').
○ list: Ordered, mutable collections (e.g., [1, 2, 3]).
○ tuple: Ordered, immutable collections (e.g., (1, 2, 3)).
• Mapping Type:
○ dictionary: Key-value pairs (e.g., {"name": "John", "age": 25}).
• Boolean Type:
○ bool: True or False.
12. Mutable and Immutable Data Types
• Mutable Types: These are data types/objects content or values of which can be
changed after it is created.
○ Examples: list, dict.
○ These objects can be modified in place, so changes to a mutable object will affect
all references to that object.
• Immutable Types: These are data types content or values of which cannot be changed
after it is created.
○ Examples: int, str, tuple.
○ When an immutable object is modified, a new object is created, leaving the
original object unchanged.
Example of Mutability:
a = [1, 2, 3]
b=a
[Link](4) # Modifies the original list
print(b) # Output: [1, 2, 3, 4]
print(a) #Output: [1, 2, 3, 4]
print(id(a)) # returns memory location of object
print(id(a)) # returns memory location of object
Both variables a and b refer to the same memory location.
Immutable object (string)
x = "hello"
y=x
x = "world" # Creates a new string object
print(y) # Output: hello (y is unaffected)
print(x) # Output: world(x value changed)
print(id(x)) # gives memory location of object
print(id(y)) # gives memory location of object
both x and y variable having different location in memory
26 | Page
Multiple Choice Questions
1 Which function is used to display output in Python?
A) show() B) print() C) display() D) output()
2 Identify the valid relational operator among the following.
A) = B) += C) == D) and
3 Which of these is a valid Python identifier?
A) 1var B) _var C) var-name D) var name
4 What is the correct way to assign a value to a variable in Python?
A) x == 5 B) 5 = x C) x = 5 D) x := 5
5 Which operator is used for exponentiation in Python?
A) ^ B) ** C) exp() D) %
6 Predict the output of the following code:
print(3**2+55/11*-(-3+3))
A) -39.0 B) 27.0 C) -14.0 D) 9.0
Answer (Multiple Choice Questions)
1 B) print()
2 C) ==
3 B) _var
4 C) x = 5
5 B) **
6 D) 9.0
3 Write a Python program to find the average of three numbers where value of
a is 10, b is 20 and c is 30.
Ans:
4 Predict Output –
a, b, c = 2, 3, 4
a, b, c = a*a, a*b, a*c
print(a, b, c)
Ans. 4 6 8
28 | Page
5 Predict the Output –
a, b, c = 10, 20, 30
p, q, r = c-5, a+3, b-4
print('a, b, c : ', a, b, c, end = '### ')
print('p, q, r : ', p, q, r, sep = '$$ ')
Ans: a, b, c : 10 20 30###p, q, r : $$25$$13$$16
6 Payal is working in a firm and given a task to find the average of two numbers
x=7
y=5
print(x+y/2)
she is not getting the correct average, give suitable answer and rectify the code
Ans:
x=7
y=5
print((x+y)/2)
both x and y should be in parenthesis to increase precedence of addition than
division by 2, then she will be able to find correct average
29 | Page
13. Statements
● Instructions executed by the Python interpreter.
● Types of statements:
o Empty statement: – Statement which does nothing. Used for placeholder in codes.
It is as follows:
Mind Map
30 | Page
[Link] and Evaluation
• Valid combination of variables, operators, and values that yield a result.
• Examples:
o Arithmetic expressions: e.g. a=2 + 3
o Logical expressions: e.g. a and b , a or b
o String expressions: e.g. "Computer" + "Science"
• Can be part of a larger statement
Evaluation
o The process of computing the result of an expression.
o Python evaluates expressions using the rules of precedence and associativity.
15. Comments
• Used to annotate code and make it more understandable.
o Single-line comments: Begin with # symbol
e.g., #This is a comment.
o Multi-line comments: Enclosed in triple quotes
e.g. """ Multi-line comment
To give more description of code """
If the comment is more than one line then multi-line comment can be used.
16. Input and Output Statements
• Input:
o input (): Reads a line of text input from the user
o (e.g., name = input ("Enter your name: ")).
o Always returns a string.
• Output:
o print (): Outputs text or values of variables/expressions to the console
(e.g., print ("Hello, World!")).
o Can accept multiple arguments separated by commas (e.g., print ("Name:", name)).
o Optional arguments like sep and end can be used to customize the output
e.g., print ("Hello", "World", sep="-")
17. Data Type Conversion
Converting one data type to another.
• Two types:
o Implicit Data type conversion - takes place automatically by type promotion to
higher data type.
E.g. 5 + 2.5 => 5.0 (promoted to float) + 2.5 [ int + float => float + float ]
o Explicit data type conversion
Done forcefully/explicitly by the programmer. Some examples are as follows :
• Common functions:
o int(): Converts a value to an integer (e.g., int("42") result is 42)
o float(): Converts a value to a float (e.g., float("3") result is 3.0)
o str(): Converts a value to a string (e.g., str(42) result is “42”)
o list(): Converts a value to a list (e.g., list("abc") result is ['a', 'b', 'c'])
o tuple(): Converts a value to a tuple (e.g., tuple([1, 2, 3]) result is (1,2,3))
31 | Page
o dict(): Converts a value to a dictionary (when applicable, e.g., dict([('a', 1), ('b', 2)])
result is {'a':1 , 'b':2} )
18. Debugging in Python
• Definition:
o The process of finding and fixing errors or bugs in program code.
• Common Debugging Techniques:
o print Statements: Insert print () statements in your code to check values of variables
and program flow
e.g. print ("Checkpoint reached") #output Checkpoint reached
x=15
print ("Value of x:", x) #output Value of x: 15
3. child think about all options and choose one option (he selects decoration of house with
balloons) due to least cost. Selection statement🡪use of [if/ elif /else]
4. Child start inflating balloons one by one until 50 balloons are inflated with the help of pump.
(Repetition of task; inflation of balloon -> iteration statement 🡪 use of [for/ while]
Note: Students may use this real-life example to design Python programs based on control
statements
Selection Statements
• if statement:
o Executes a block of code if a condition is True.
o Example:
• if-else statement:
o Executes one block of code if a condition is True, and another block if it is False.
32 | Page
o Example:
• if-elif-else Statement:
o Checks multiple conditions in sequence, executing the first block of code where the
condition is true.
o Example:
Iterative Statements
• While Loop:
o Repeats a block of code as long as a condition is True.
Example:
• For Loop
o Iterates over a sequence (e.g., list, tuple, string) or range of numbers.
Syntax: for <variable> in <sequence>
statements_ to_repeat
o Example:
• Jump statements
Python offers two types of jump statements to be used within loops to jump out of loop iterations.
o break
break statement is a jump statement which terminates the very loop it lies within
and skips over a part of the code(i.e. rest of the loop) and jumps over to the
statement following the loop.
o continue
continue is a jump statement which forces the next iteration of the loop to take place
and skip the rest of the statements of current iteration.
Looping with break and continue:
• break: Exit the loop when the break statement will encounter.
• continue: Skip the rest of the code after continue and move to the next iteration.
Examples:
Choose correct option for given Assertion (A) and Reasoning (R)
a) Both A and R are True and R is the correct explanation of A.
36 | Page
b) Both A and R are True but R is not the correct explanation of A.
c) A is True but R is False.
d) A is False but R is True.
1 Assertion (A): The conditional flow of control can be defined with the help of if
statement.
Reasoning (R): if statement executes one or more statements based on the given
condition. If the condition evaluates to True, the statement block following the
indentation gets executed, otherwise nothing gets executed.
2 Assertion (A): break and continue are termed as Jump statements.
Reasoning (R): Jump statements can only be used with looping constructs but not
with conditional constructs.
3 Assertion (A): In an if-else statement, the if block is executed when expression
evaluates to True whereas else block is executed when expression evaluates to
False.
Reasoning (R): In a conditional construct, else block is mandatory.
4 Assertion (A): The data type of a variable is taken according to the type of value
assigned to it.
Reasoning (R): In Python, variables do not need explicit data type declaration
before assigning values. This feature is called dynamic typing.
Ans. B
5 What will be the output of the following code?
x=5
while x > 0:
print (x, end=" ")
x -= 2
if x == 1:
break
else:
print("Done")
Ans. 5 3
6 What do you mean by continue and break keywords
Ans. The break statement terminates the loop containing it. Control of the program
flows to the statement immediately after the body of the loop.
The continue statement is used to skip the rest of the code of the current iteration
only. Loop does not terminate but continues with the next iteration.
7 What is the use of While loop? With suitable example.
Ans. The while loop in Python is used to repeatedly execute a block of code as long
as a given condition remains True.
Example:
c=0
while c < 5:
print("C:", c)
c += 1
38 | Page
8 Find out the Error in the following Code Snippet. Rewrite the code after removing
all the errors and underline the corrections made.
Ans.
1 Write a program to test whether given number(other than 1 and 0) is prime or not.
Ans:
2 Write a program to compute the result when two numbers and one arithmetic
operator out of (+, -, *, /) is given by user.
Ans:
a = int(input('Enter 1st number: '))
b = int(input('Enter 2nd number: '))
c = input('Enter the Operator +,-,/,*: ')
print("The result is: ",end='')
if c=='+':
print(a+b)
elif c=='-':
print(a-b)
elif c=='/':
print(a/b)
elif c=='*':
print(a*b)
else:
print('Error : Wrong operator')
39 | Page
3 Write a program to find the sum of first n natural numbers
Ans:
6 Write a program to calculate the roots of a given quadratic equation. Values for a, b
and c will be entered by the user.
Ans:
40 | Page
to work for Rs. 60,000 a month. The following code shows his basic strategy for
evaluating a job offer.
On the basis of
the above code,
choose the right
statement which will be executed when different inputs for pay and location are
given.
(i) Input value: location = 'Chennai', pay = 50000
a) Statement 1 b) Statement 2 c) Statement 3 d) Statement 4
Answer: (b) Statement 2
(ii) Input value: location = "Surat", pay = 50000
a) Statement 2 b) Statement 4 c) Statement 5 d) Statement 6
Answer: (d) Statement 6
(iii) Input value: location = "Any Other City", pay = 1
a) Statement 1 b) Statement 2 c) Statement 6 d) Statement 4
Answer: (c) Statement 6
(iv) Input value: location = "Delhi", pay = 500000
a) Statement 6 b) Statement 5 c) Statement 4 d) Statement 3
Answer: (c) Statement 4
(v) Input value: location = "Lucknow", pay = 65000
a) Statement 2 b) Statement 3 c) Statement 4 d) Statement 5
Answer: (d) Statement 5
2 Sanjeev is, a Python Programmer he is trying to write a program of finding leap year
if the value of year is given by user
(A year is a leap year if it is divisible by 4, except that years divisible by 100 are not
leap years unless they are also divisible by 400. )
Ans:
41 | Page
OUTPUT:
Enter year: 1800
1800 is not a Leap Year
3 Read the following case and answer the questions:
A school is organizing a mock election. The eligibility to vote is based on the age of
the student. The program checks the student's age and prints if the student is
eligible to vote or not.
Questions:
a) What will be the output if the user inputs 20?
b) What is the purpose of the int() function in this code?
c) Modify the code to also print "Please wait until you are 18." if not eligible.
d) What will happen if the user enters a non-numeric input?
e) If a student is eligible to vote another message must be displayed on the screen
that is “choose a right person” , where will this print statement would be added
in the code.
Answer:
a) Eligible to vote.
b) It converts the input string to an integer.
c)
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to vote.")
else:
print("Not eligible to vote.")
print("Please wait until you are 18.")
d) It will raise a ValueError since int() cannot convert non-numeric input.
e) “choose a right person” line of code will be added in if block statement
42 | Page
4 A school uses the following grading system:
Marks >= 90 → Grade A
Marks >= 75 and < 90 → Grade B
Marks >= 50 and < 75 → Grade C
Marks < 50 → Grade D
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Grade D")
Questions:
a) What grade will be displayed for 88 marks?
b) What is the output if the marks entered are 45?
c) What will happen if the user enters -10 in the above code.
d) Modify the code to also check if the marks are within 0 to 100.
Answers:
a) Grade B
b) Grade D
c) The original code will still run and give Grade D, but it should be considered
invalid input.
d)
marks = int(input("Enter your marks: "))
if marks < 0 or marks > 100:
print("Invalid marks.")
elif marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Grade D")
43 | Page
5 A school wants to help students in revise multiplication tables. The following code
print the multiplication table of a number:
Questions:
a) What will be the output for input 5?
b) How many times will the loop run?
c) Modify the code to print the table in reverse order (from 10 to 1).
d) What is the role of range (1, 11)?
Answers:
a) 5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
b) 10 times.
c) for i in range (10, 0, -1):
print (num, "x", i, "=", num * i)
d) It generates numbers from 1 to 10.
44 | Page
LIST IN PYTHON
List is an ordered sequence which is mutable and made up of one or more elements. A list can
have elements of different data types such as integer, float, string, tuple or even another list.
Elements of a list are enclosed in square brackets [ ] and are separated by comma. It is a mutable
data type.
• Creating List
o We can create a list by placing elements inside square brackets [ ], separated by
commas.
Example : Number=['One', 'Two', 'Three']
o We can create list using list() method
data=list() Creates empty list
data=list([3,4,5])
• Accessing Elements in a List: Each element in the list is accessed using its index value (0
to n-1, where n is total number of elements in list).
o Forward (Positive) Indexing: If accessing of elements start from left to right then the first
index value is 0 and second index value is 1 and so on, upto n-1.
o Backward (Negative) Indexing: If accessing of elements start from right to left then the
index value ranges from -1 to –n.
• Traversing a List: We can access each element of the list or traverse a list using a loop.
Example:
L=[1,2,3,4]
for item in L:
print(item)
• Nested List: When a list appears as element of another list, it is called a nested list.
Example: L=[1,2,[3,4],5]
Mind Map:
45 | Page
• List Methods and Built-in Functions
There is a key difference between functions and methods in Python. Functions take objects as
inputs/parameter. Methods in contrast act on objects.
Function Method
A= [25,36,37,12,25] A= [25,36,37,12,25]
M=len(A) M=[Link](25)
print(M) print(M)
#output 5 #output 2
list named A passed count() method acts on
as parameter object A (list)
46 | Page
Output: [ ] #emply list created
list(sequence) Lst=list ("hi")
print (Lst)
Output:
['h', 'i']
#sequence(String) converted in to list
len (list) L= [2, 3, [4,5]]
print(len(L))
Output:
3 # Explanation: In above example 3rd element is list and
it is considered as single element
max(list) L=[1,-2,4,-4]
print(max(L))
output: 4
Try it!!!
lst=[[2,3],[4,6],[6,4]]
print(max(lst))
min(list) L=[1,-2,4, -4]
print(min(L))
output: - 4
sum(list) L=[1, -2,4, -4]
print(sum(L))
output: -1
sorted(list,reverse=False) L=[15,16,17,2,3,9]
print(sorted(L)) #by default reverse False
output:
[2,3,9,15,16,17]
L=[15,16,17,2,3,9]
print (sorted (L, reverse=True))
output:
[17,16,15,9,3,2]
[Link](items/ elements) lst=[3,6,0]
[Link](9)
print(lst)
output :
[3,6,0,9]
[Link] (index_no, value) Odd=[1,5,7,9]
[Link](1,3)
print(Odd)
Output:
[1,3,5,7,9]
# value 3 inserted at index position 1
[Link] () Even=[2,4,6,8]
[Link]()
print(Even)
output:
[8,6,4,2]
[Link] (item/element) Even=[2,4,6,8]
print([Link](4))
Output:
47 | Page
1 #element 4 at index position 1
[Link] () Num=[2,4,-6,-8,0]
[Link]() #by default reverse is False
print(Num)
Output:
[-8, -6, 0, 2, 4]
Num= [2,4, -6, -8,0]
[Link](reverse= True)
print (Num)
Output:
[4, 2, 0, -6, -8]
Use the “reverse” argument to sort in descending order
[Link] (element) data= [10,30,20,30,90,30]
print([Link](200))
output:
0 # element /value 200 not in the list data
data=[10,30,20,30,90,30]
print([Link](30))
Output:
3 # element /value 30 three times in the list data
[Link] (index) data=[10,30,20,40,50]
print([Link]()) # pop() without index position
print(data)
Output:
50 # pop () returns the popped value
[10,30,20,40]
# data list printed after popped its last element
data= [10,30,20,40,50]
print([Link](2)) #pop() function with index position
print(data)
Output:
20 # pop () returns the popped value
[10,30,40,50]
# data list printed after popped its element of particular
index position.
[Link] (item/element) data=[10,30,20,25,30,40]
[Link](30) #element 30 at index position 1, 4
print(data)
output:
[10, 20, 25, 30, 40]
# remove the first occurrence of a specified value from the
list
[Link] () data=[10,30]
[Link]()
print(data)
output:
[]
# empty list will be displayed after implanting clear method
48 | Page
Multiple Choice Questions
1. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after execution of [Link] (1)?
a) [3, 4, 5, 20, 5, 25, 1, 3] b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [3, 5, 20, 5, 25, 1, 3] d) [1, 3, 4, 5, 20, 5, 25]
2. Suppose a list mylist is [10,23,45,3,34,50], what is mylist after execution of
[Link](3)
a) [10, 23, 3, 34, 50] b) [10, 23, 45, 34, 50]
c) [10, 23, 3, 34, 50] d) No output
3. Consider the following code and predict the output
mylist = [2,3,8,9,3]
[Link]([2,4])
print(mylist)
a) [2, 3, 8, 9, 3, 2, 4, [2, 4]] b) [[2, 4], 2, 3, 8, 9, 3, 2, 4]
c) [2, 3, 8, 9, 3, ,2, 4, 2, 4] d) [2, 3, 8, 9, 3, [2, 4]]
4. Consider a list mylist with n elements, in [Link]() what is the default index
a) 1 b) 0
c) -1 d) 4
5. What is the output when we execute?
print(list(“hello”))
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] b) [‘hello’]
c) will not create a list d) [‘h,e,l,l,o’]
6. Which of the following commands will create a list?
a) listl = list( ) b) listl = [ ]
c) listl = list([1, 2, 3]) d) all of these
Answer (Multiple Choice Questions)
1. c) [3, 5, 20, 5, 25, 1, 3]
2. b) [10, 23, 45, 34, 50]
3. d) [2, 3, 8, 9, 3, [2, 4]]
4. c) -1
5. a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
6. d) all of these
49 | Page
Answer (Assertion and Reasoning Questions)
1 Answer: a) Both A and R are true, and R is the correct explanation of A.
2 Answer: c) A is true, but R is false.
51 | Page
Case Based Question with Answer
1 An e-commerce electronic store tracks its quarterly inventory and sales
performance using Python List, which stores the unique codes of the electronic
items. The initial data setup is as follows:
items = ["E101", "E102", "E103"]
Questions:
a) Write a Python statement using list operations to display the updated list in
descending order.
b) Write a Python statement using list operations to add a new item code
"E104" to the end of the items list.
Answer:
Python code Output
(a) [Link](reverse= True) ["E103", "E102", "E101"]
(b) [Link]("E104") ["E101", "E102", "E103", "E104"]
2 The librarian of a school is maintaining a list of newly issued book IDs using
Python lists. She wants to perform different operations on the list such as adding
new book IDs, removing returned books, counting repeated IDs, and arranging the
list properly.
book_ids = [101, 104, 108, 104, 112]
Based on the above case study, answer the following questions:
i. Write the Python statement to add book ID 115 at the end of the list.
ii. Which Python statement should be used to insert book ID 102 at index
position 1?
iii. Write the Python statement to remove book ID 108 from the list.
iv. Write the statement using list method to count how many times book ID
104 appears in the list?
v. Write the Python statement to arrange all elements of the list in ascending
order.
Answers:
i. book_ids.append(115)
ii. book_ids.insert(1, 102)
iii. book_ids.remove(108)
iv. book_ids.count(104)
v. book_ids.sort()
52 | Page
DICTIONARY IN PYTHON
Mind Map:
The data type dictionary falls under mapping. It is a mapping between a set of keys and a set of
values. The key-value pair is called an item. A key is separated from its value by a colon (:) and
consecutive items are separated by commas. Items in dictionaries are unordered,
A dictionary is an unordered sequence of key-value pairs.
Key and value in a key-value pair in a dictionary are separated by a colon. Further, the key:
value pairs in a dictionary are separated by commas and are enclosed between curly
parentheses.
o The keys of the dictionaries are immutable types such as Integers or Strings etc.
o Indices in a dictionary can be of any immutable type and are called keys.
o The values of a dictionary in Python are mutable.
• Creating Dictionaries
A Dictionary can be created in three different ways:
1. Empty Dictionary using empty { }
D = { } # Empty Dictionary
2. Dictionary using literal notation
D = {"Name": "Mohan", "Class": "XI", "City": "Gurdaspur"}
print(D)
3. Dictionary using dict() function
Dict() function is used to create a new dictionary with no items. For example,
Months = dict() # Creates an empty dictionary
53 | Page
print(Month) # Prints an empty dictionary
We can use Square Brackets [ ] with keys for accessing and initializing dictionary values.
For Example:
Months[0] = ‘January’
Months[1] = ‘February’
Months[2] = ‘March’
print(Months)
output: {0 : 'January', 1: 'February' , 2 : 'March'}
Months = dict(Jan = 31, Feb = 28, March = 31)
# Creating dictionary by giving values in dict() function
print(Months)
output: {'Jan': 31, 'Feb': 28, 'March': 31}
• Accessing Elements of a Dictionary
Elements of Dictionary may be accessed by writing the Dictionary name and key within
square brackets ([ ] ) as given below:
D = {0 : "Sunday", 1 : "Monday", 2: "Tuesday"}
print(D[1])
output: Monday
***Attempting to access a key that does not exist, causes an error.
• Traversing a Dictionary:
Dictionary items can be accessed using a for loop.
output:
Apple
Boy
Cat
• Adding an Element in a Dictionary
We can add new element (key : value pair) to a dictionary using assignment, but the key
being added must not exist in dictionary and must be unique.
d["D"]="Dog" # if a new key is given, new item is added
print(d)
output: {'A': 'Apple', 'B': 'Boy', 'C': 'Cat', 'D': 'Dog'}
A new key ‘D’ added in to the dictionary d
• Updating / Modifying an element in Dictionary
54 | Page
• Dictionary Methods and Built-in Functions
Function Syntax Description
dict() dict() Creates a dictionary from a sequence of key-
value pairs
len() len (dictionary) function: It is used to find the length of the
dictionary, i.e., the count of the key : value pair.
keys() [Link]() Returns a list of keys in the dictionary
values() [Link]() Returns a list of values in the dictionary
items() [Link]() Returns a list of tuples(key – value) pair
update() [Link](iterable) appends the key-value pair of the dictionary
passed as the argument to the key-value pair of
the given dictionary
del del Dict_name Deletes the item with the given key or to delete
del dictionary[key] the dictionary from the memory.
clear() [Link]() Deletes or clear all the items of the dictionary
Dictionary functions and methods with examples:
Function Examples output
dict() d=dict() {}
print(d)
dates=dict([['Jan',31], {'Jan': 31, 'Feb': 28, 'March': 31}
['Feb',28], ['March',31]])
print(dates)
len (dictionary) dates={'Jan': 31, 'Feb': 28, 3
'March': 31}
print(len(dates))
Method Examples output
[Link]() dates={'Jan': 31, 'Feb': 28, dict_keys(['Jan', 'Feb', 'March'])
'March': 31} Returns a list containing the
print([Link]()) dictionary's keys
[Link]( dates={'Jan': 31, 'Feb': 28, dict_values([31, 28, 31])
) 'March': 31} Returns a list of all the values in the
print([Link]()) dictionary
[Link]() dates={'Jan': 31, 'Feb': 28, dict_items([('Jan', 31), ('Feb', 28),
'March': 31} ('March', 31)])
print([Link]()) returns a list containing a tuple for
each key value pair
[Link] dates={'Jan': 31, 'Feb': 28, {'Jan': 31, 'Feb': 29, 'March': 31}
(iterable) 'March': 31}
[Link]({'Feb':29})
print(dates)
dates={'Jan': 31, 'Feb': 28, {'Jan': 31, 'Feb': 28, 'March': 31, 'April':
'March': 31} 30}
[Link]({'April':30})
55 | Page
print(dates) # ‘April’ Key not exist in dates so
new key ‘April’ added in to the
dictionary
del Dict_name d={1:"One",2:"Two"} Removes entire dictionary
del d #print statement will cause an
print(d) error because ‘d’ dictionary no
longer exists.
del dates= {'Jan': 31, 'Feb': 28, Before removal
dictionary[key] 'March': 31} {'Jan': 31, 'Feb': 28, 'March': 31}
print ("Before removal") After removal
print(dates) {'Jan': 31, 'Feb': 28}
del dates["March"]
print ("After removal") #will delete particular key from a
print(dates) dictionary
dictionary. clear() d={"A":"An","Is":"Are"} {}
[Link]() Removes all the elements from the
print(d) dictionary
Note: if single key:value pair is to remove from a dictionary then pop() and popitem()
method of dictionary can be used.
o pop() method removes and returns a specific item based on a key.
Syntax: [Link](key)
o popitem() method removes and returns the last inserted key-value pair.
Syntax: [Link]()
• Checking existence of a key in a dictionary
To check if a key is present in the dictionary or not we can use the in operator – if the given key
is present in the dictionary, it returns True, otherwise it returns False.
e.g.: Consider the dictionary:
dates= {'Jan': 31, 'Feb': 28, 'March': 31}
'Feb' in dates # returns True
'FEB' in dates # returns False
'FEB' not in dates # returns True
57 | Page
Short Questions with Answer
1. Rita is a student of class XI. Help her to create a dictionary to store details of 10
employees given by the user. Each element consists of empcode as key, name and
salary as values.
Answer:
emp={}
for i in range(10):
l=[]
empcode=int(input("enter emplyee code"))
name=input("enter name")
salary=int(input("enter salary"))
[Link](name)
[Link](salary)
emp[empcode]=l
print(emp)
2. Consider the following dictionary and print the name and salary of employees in
“computer” department.
{ "anil":["computer",10000],
"anju":["History",5000],
"somu":["computer",11000],
"sam":["English",8000] }
Answer:
data={"anil":["computer",10000], "anju":["History",5000],
"somu":["computer",11000], "sam":["English",8000] }
for key, value in [Link]():
if value[0]=="computer":
print(key , value[1])
Unsolved Questions (Test your understanding)
1. The dictionary empdat contains employee records with the following values
{1 :[ "Raj " ,85000], 2: ["Sathya ", 20000], 3: ["Meenu ",89000]}
Write a Python program to display only the records where the employee’s salary exceeds
75000.
2. The dictionary students stores students name and their marks:
students = {
"A101": ["Ravi", 88],
"A102": ["Divya", 76],
"A103": ["Kiran", 95],
"A104": ["Neha", 65]}
Write a Python program to display the name and marks of students who scored more
than 80
3. Write python code to create dictionary to store the following details of 10 products
{Productno: [Product name, price, quantity]}
4. Write the Python statement for the following tasks using built-in functions/methods
only:
To remove the item whose key is "NISHA" from a dictionary named Students.
58 | Page
Case Based Question with Answer
1 An e-commerce electronic store tracks its quarterly inventory and sales performance
using Python Dictionary, which maps each item code to its current stock count and unit
price in INR as [stock, price]. The initial data setup is as follows:
# Dictionary mapping item code to [current_stock, unit_price]
inventory = {"E101": [120, 15000], "E102": [85, 45000], "E103": [200, 3500]}
Questions:
a) The store wants to check the price of item "E102". Write the expression to
extract the unit price (45000) from the inventory dictionary.
b) Write the expression to change the unit price of “E103” to 5000 from the
inventory dictionary.
Answer:
Python code Output
(a) print (inventory["E102"][1]) 45000
(b) inventory["E103"][1] =5000 {"E101": [120, 15000], "E102":
[85, 45000], "E103": [200, 5000]}
print (inventory["E102"][1])
2 A school is maintaining student records using Python dictionaries. Each student’s Roll
Number is stored as the key and the student’s name is stored as the value. The computer
teacher performs different dictionary operations to manage and update the records.
i) Write the Python statement to add a new student with Roll Number 104 and
name "Neha".
ii) Write the Python statement to update the name of Roll Number 102 to "Ritika".
iii) Which dictionary method is used to display all the keys of the dictionary? Write
the statement for the given dictionary.
iv) a) Write the Python statement to delete the record of Roll Number 103 from the
dictionary.
b) Which dictionary method is used to display both keys and values
together?Write the statement for the given dictionary.
v) a) Write the Python statement to find the total number of elements present in
the dictionary.
b) Write the Python statement to remove all elements from the dictionary.
Answers:
i) student[104] = "Neha"
ii) student[102] = "Ritika"
iii) [Link]()
iv) a) del student[103]
b) [Link]()
v) a) len(student)
b) [Link]()
59 | Page
INTRODUCTION TO NUMPY
• NumPy (Numerical Python) is an open-source python library for data analysis, specially
used for scientific analysis of data with Python. NumPy provides different functions for fast
mathematical computation on arrays, matrices and on multi-dimensional arrays.
To make array using NumPy in Python, need to install a NumPy. NumPy library can be installed
using Python packages like pip.
• To install NumPy in Python, use the pip package on command line and choose the
absolute path of location, where python is installed.
pip install numpy
• NumPy is a library in Python which can be imported in a program by using import command
as
import numpy as np
• Array: Group or collection of similar type of elements.
Eg. Scores of players in a cricket match, Marks of students in a class
• NumPy Array: A grid contains value of same type (homogeneous elements) and uses Zero
based indexing, like lists in Python. NumPy Array also known as ndarray
• Difference between List and Array:
o Arrays only hold data of same data type, while list can hold the data of mixed data types
(like int, float etc)
60 | Page
o Using of Arrays to store data is more memory efficient and help to perform fast
calculation and operations.
o List is a part of core python , Array/ndarray is a part of NumPy Library
• NumPy Arrays are grid-like structures similar to lists in Python but optimized for numerical
operations. NumPy array can be created by converting a regular Python list into an array using
the [Link]() function. This function returns ndarray object. Once the NumPy array is
defined, the space it occupies in memory is fixed and cannot be change.
• Ndarray is one of the most important classes in the NumPy python library. It is basically a
multidimensional or n-dimensional array of fixed size with homogeneous elements (i.e., the
data type of all the elements in the array is the same). A multidimensional array looks
something like this:
• Axes: Axes are defined for arrays with more than one dimension. A 2-dimensional array has
two corresponding axes: the first running vertically downwards across rows(axis 0), and the
second running horizontally across columns (axis 1). Many operations can take place along
one of these axes.
• Rank: The no. of axes in a ndarray is called its rank.
• Creation of NumPy array using List
Example: Python Code
• Types of Arrays:
o 1-D Array: A single row of elements.
o 2-D Array: A matrix with rows and columns
1) 1D NumPy array creation -> Using List:
61 | Page
A list of lists i.e. nested list will create a 2D Numpy array, similarly, you can also create N-
dimensional arrays.
3 Datatype <ndarrayname>.dtype
(dtype): Type of data stored in the
array
4 ItemSize: <ndarrayname>.itemsize
Size of each element of
ndarray in bytes
5 ndim <ndarrayname>.ndim
It returns an integer
representing the number
of dimensions.
62 | Page
>>> a2=[Link]((4,))
>>> a2
array([0., 0., 0., 0.])
[Link]() This function creates an >>> a3=[Link]((2,3))
array filled with ones. It
>>> a3
requires the shape of the
array([[1., 1., 1.],
array as a parameter. [1., 1., 1.]])
>>> a4=[Link]((2,))
>>> a4
array([1., 1.])
[Link]() It creates an array of evenly >>> ar=[Link](5,10)
spaced values within a given >>> ar
interval. It is similar to array([5, 6, 7, 8, 9])
Python's built-in range() >>> ar2=[Link](5)
function but returns a >>> ar2
NumPy array instead of a list. array([0, 1, 2, 3, 4])
[Link]([start,
]stop, [step,] dtype = None) >>>ar3=[Link](5.5,
10.5,2,dtype='float64')
>>> ar3
array([5.5, 7.5, 9.5])
[Link]() Return a new array with the >>>ar1=[Link]((2,2),5,dtype='int')
same shape and type as a >>> ar1
given array filled with a array([[5, 5],
fill_value. Parameters [5, 5]])
[Link](shape, >>>ar2=[Link]((4,),1.5, dtype='float')
fill_value, dtype = None) >>> ar2
array([1.5, 1.5, 1.5, 1.5])
Multiple Choice Question and Fill in the Blanks
1 What does NumPy stand for?
(a) Number Platform (b) Numerical Python
(c) Numeric Python (d) Number Picture
2 Array object in NumPy is called ____________
(a) number array (b) Narray (c)numpy Array (d)ndarray
3 NumPy is open source in python (True/ False)
4 Follow the below code :
arr = [Link]([[1, 2, 3,4], [4, 5, 6,7]])
Find out the dimensions it has.
(a) 1 (b) 2 (c) 3 (d) 4
5 Fill the blanks in the below python code and underline it.
import numpy as _______
Array=np.____________([1,2,3,5,6])
print(Array)
6 Which attribute of NumPy array is used to find out the number of dimensions?
(a) ndimn (b) ndim (c) ndimensions (d)ndarray
7 When this python code will execute, then which output will come?
import numpy as np
63 | Page
L1=[1,2]
L2=[3,4]
arr = [Link]([L1, L2])
print(arr[1, 0])
(a) 1 (b) 2 (c) 3 (d) 4
8 from the below python code display the value of first element of array and display
number 35 from an array
import numpy as np
Array=[Link]([3,6,9,12,15,18,36,35,38])
print(Array[ ],Array[ ])
(a) [1],[7] (b) [1],[8] (c) [0],[8] (d)[0],[7]
9 Find the output of the below code:
import numpy as np
Array=[Link]([3,6,3,3,15,18,36,35,38])
print (Array [ :4])
(a) [3 6 3 3] (b) [3,6,3,3,15] (c) [3,6,3,3] (d)[3,15,18,36,35,38]
10 Which of the following is correct way to import the Numpy module in your program?
(a) import numpy (b) import numpy as np
(c) from numpy import * (d) All of the above
11 What will be the output of following code?
import numpy as np
A=[Link]([24,46,57,14,68,34,89,92])
print(A[7:3:-1])
print(A[2:6])
a) [92 89 34 68] b) [92 34 89 68]
[57 14 68 34] [14 57 68 34]
c) [92 68 34 89] d) [92 34 68 89]
[14 68 57 34] [34 14 68 57]
12 Find out the Correct Statement:
(a) Python List occupy less space than a NumPy array.
(b) NumPy array can contain elements of non-homogenous type.
(c) We cannot change the size of NumPy array after the store in memory
(d) All of the above.
Answer (Multiple Choice Question and Fill in the Blanks)
1 (b) Numerical Python
2 (d) ndarray
3 True
4 (b) 2
5
6 (b)ndim
7 (c) 3 Explanation: arr value will be
64 | Page
Explanation: print (Array [ :4]) This statement starts printing element from index
position 0 and will print upto index position 4-1=3 as its increment by 1 (default
increment).
10 (d) All of the above
11 (a)
Answer:
5 Write down some of the advantages of using NumPy arrays over Python lists?
Answer:
NumPy arrays offer several advantages, including: faster performance for numerical
operations due to vectorization, more efficient memory usage, and a wide range of
mathematical functions and operations. Array also helpful in Optimize the data that
help CPU to perform operation accurately and effectively.
NumPy is designed for data analysis and manipulation, offering a wide range of
functions for sorting, searching, and statistical analysis.
6 Given a list L=[1,2,3,4] and an ndarray N having elements [1 2 3 4] . What will be the
result produced by the following statements?
(a) L*2 (b) N*3 (c) L+L (d) N+N
Ans:
(a) [1,2,3,4,1,2,3,4]
(b) [3 6 9 12]
(c) [1,2,3,4,1,2,3,4]
(d) [2 4 6 8]
66 | Page
Case Based Question with Answer
1 Consider the following data:
2.5 19 0
3.4 18 7
10.5 19.2 5
(a) Use nested Python lists to create a 2-D array called array1 having 3 rows and
3 columns .
(b) Write python code and find the size of the array1.
(c) Write python code to find the datatype that store the elements in to the
memory .
(d) Write python code to find out the shape of the nested list as per the list
elements in array 1.
Answer: (a)
Python code Output
(a) import numpy as np [[ 2.5 19. 0. ]
array1=[Link]([[2.5,19,0],[3.4,18,7],[10.5,19.2,5]]) [ 3.4 18. 7. ]
print(array1) [10.5 19.2 5. ]]
(b) print([Link]) 9
(c) print([Link]) float64
(d) print([Link]) (3, 3)
2 An e-commerce electronic store tracks its quarterly inventory and sales
performance using Python NumPy Array, which Stores a 2D matrix of sales
quantities, where rows represent the items and columns represent sales over
three consecutive months (Jan, Feb, March). The initial data setup is as follows:
sales_matrix:
Jan Feb March
E101 40 35 50
E102 15 20 12
E103 70 85 90
# 2D NumPy array for Jan, Feb, March sales quantity and Rows represent E101,
E102, E103 respectively
Questions:
a) Write a Python code snippet to calculate and print the total sales quantity
achieved in each month using the sales_matrix NumPy array.
b) Write a Python code snippet to calculate and print the total sales quantity
achieved by each item in three-month period using the sales_matrix NumPy
array.
c) Write the NumPy slicing statement to extract the sales data of the first two
items (E101 and E102) for the last two months (February and March).
67 | Page
Answer:
Python code Output
(a) total_sales_per_item = [125 140 152] #(axis=0)
sales_matrix.sum()
print(total_sales_per_item)
(b) total_sales_per_item = [125 47 245] #(axis=1)
sales_matrix.sum(axis=1)
print(total_sales_per_item)
(c) sub_sales = sales_matrix[0:2, 1:3] [[35 50] [20 12]]
print(sub_sales)
3 A data analyst is working on student marks using NumPy in Python. She first
stores the marks in a Python list and then converts the list into a NumPy array
for faster processing and mathematical operations.
marks = [78, 85, 90, 67, 88]
68 | Page
UNIT 3: DATABASE CONCEPTS AND SQL
Database Concepts
Mind Map
Database Concepts
• Database
A database is an organized collection of data that can be easily accessed, managed, and
updated.
A database helps us to store our data in the permanent memory.
• DBMS
A database management system (DBMS) or database system in short, is a software that can be
used to create and manage databases.
DBMS lets users to create a database, store, manage, update/modify and retrieve data from
that database by users.
Some examples of DBMS are MySQL, Oracle, PostgreSQL, SQL Server, Microsoft Access,
MongoDB.
• RDBMS
RDBMS stands for Relational DBMS.
Different types of DBMS are available and their classification is done based on the underlying
data model.
There are three Data Models: Hierarchical, Network, and Relational.
A data model describes the structure of the database, including types of data, relationship
between the data and rules(constraints) on data.
69 | Page
The most commonly used data model is Relational Data Model.
• Advantages of a database
1. Reduced Data Redundancy
Data is stored in one place and it is shared and thus avoids duplication.
2. Data Consistency
Centralized data updates ensure all users see the same, up-to-date information.
3. Data Integrity
Rules (otherwise known as constraints) ensure valid and accurate data (e.g., age of a
person is non-negative).
4. Improved Data Security
User access can be controlled (e.g., some users can only read, others can update).
5. Data Sharing
Multiple users and applications can access the data simultaneously without conflict.
6. Backup and Recovery
Automatic tools help recover data in case of failure or crashes.
TERMINOLOGY
Domain It is a set of values from which an attribute can take a value in each
row. Usually, a data type is used to specify domain for an attribute.
Tuple Each row of data in a relation (table) is called a tuple.
Attributes Each column of a relation (table) is called an attribute.
Cardinality The number of tuples in a relation is called the Cardinality of the
relation.
Degree The number of attributes in a relation is called the Degree of the
relation.
Database Schema Database Schema is the design of a database. It is the skeleton of the
database that represents the structure (table names and their
fields/columns), the type of data each column can hold, constraints on
the data to be stored (if any), and the relationships among the tables.
Database schema is also called the visual or logical architecture as it
tells us how the data are organised in a database.
Data Constraint Sometimes we put certain restrictions or limitations on the type of
data that can be inserted in one or more columns of a table. This is done
by specifying one or more constraints on that column(s) while creating
the tables.
Meta Data The database schema along with various constraints on the data is
stored by DBMS in a database catalog or dictionary, called meta-data.
A meta-data is data about the data.
Query A query is a request to a database for obtaining information in a
desired way. Query can be made to get data from one table or from a
combination of tables.
Database Engine Database engine is the underlying component or set of programs used
by a DBMS to create database and handle various queries for data
retrieval and manipulation.
70 | Page
Example:
Consider the student table given below:
StudentID Name Age Grade Mobile
101 Aman 14 A 1111145689
102 Ajay 15 B 1111131212
Name of relation: Student
Domain: In the above relation, the attribute StudentID takes integer values and hence its domain
is a set of integer values.
Degree: Degree of this table is 5 as it has 5 attributes (columns)
Name of attributes: StudentID, Name, Age, Grade, Mobile
Cardinality: Cardinality of this table is 2 as this table contains 2 tuples(rows/records) of data
Keys of a relation
Candidate A relation can have one or more attributes that takes distinct values. Any of
Keys these attributes can be used to uniquely identify the tuples in the relation.
Such attributes are called candidate keys
Primary Key Out of one or more candidate keys, the attribute chosen by the database
designer to uniquely identify the tuples in a relation is called the primary
key of that relation.
If no single attribute in a relation is able to uniquely distinguish the tuples,
then more than one attribute is taken together as primary key. Such primary
key consisting of more than one attribute is called Composite Primary key
Alternate Key From the candidate keys, the attributes which are not chosen as primary key
are called Alternate key
Foreign Key A foreign key is used to represent the relationship between two relations. A
foreign key is an attribute whose value is derived from the primary key of
another relation.
For example- in below table following attributes(columns) RNO, UID, REGNO are candidate keys,
suppose we have chosen RNO as primary Key. Then the other two attributes (column) UID,
REGNO will become alternate key.
71 | Page
In the above table
1. There are 5 tuples (rows/ records), hence the CARDINALITY is 5
2. There are 6 Attributes and hence DEGREE is 6
3. RNO, UID AND REGNO are unique for each student and hence are eligible to become
Primary Key. They are CANDIDATE KEYS.
4. RNO is chosen as PRIMARY KEY.
5. So UID & REGNO becomes ALTERNATE KEYS.
Example of Foreign Key: -
• It is a column or a set of columns in one table that refers to the primary key in another
table.
• It establishes and enforces a link between the data in two tables
In Patient table, the primary key of Doctor table is present, which helps us to link these two
tables. Hence DID in patient table is the Foreign Key.
Note:
The table whose primary key is present in another table, is known as parent table. Here in the
above example DOCTOR table is the parent table
The table in which, foreign key is present is known as the Child table. In the above example
PATIENT is the child table.
PID is the primary key of patient table.
Three Important Properties of a Relation
In relational data model, following three properties are observed with respect to a relation
which makes a relation different from a data file or a simple table.
Property 1: imposes following rules on an attribute of the relation:
⮚ Each attribute in a relation has a unique name.
⮚ Sequence of attributes in a relation is immaterial.
Property 2: governs following rules on a tuple of a relation.
⮚ Each tuple in a relation is distinct.
⮚ Sequence of tuples in a relation is immaterial.
Property 3: imposes following rules on the state of a relation.
⮚ All data values in an attribute must be of same data type
⮚ Each data value associated with an attribute must be atomic
⮚ No attribute can have many data values in one tuple.
⮚ A special value “NULL” is used to represent values that are unavailable or
not applicable or not known at the moment.
72 | Page
Structured Query Language
Database management systems there are special kind of programming languages called query
language that can be used to access data from the database.
The Structured Query Language (SQL) is the most popular query language used by major
relational database management systems such as MySQL, ORACLE, SQL Server, etc.
Features and Advantages of SQL
⮚ SQL (Structured Query Language) was invented by Donald D. Chamberlin and
Raymond F. Boyce in the early 1970s at IBM.
⮚ SQL uses simple, English-like syntax
⮚ SQL is supported by all major RDBMS platforms, making it portable across systems with
little to no change.
⮚ SQL is not case sensitive
⮚ SQL statements ends with semi colon ( ; )
73 | Page
Data Definition Language (DDL):
The structure of a relation consists of the number of attributes, their data types, keys and
constraints that we keep on the values of attributes.
The commands used for creating, modifying or deleting the structure of a relation are
called DDL commands
Example: CREATE TABLE, ALTER TABLE, DROP TABLE.
Data Manipulation Language (DML):
The data of a relation(table) is contained in the rows/records.
The commands used to create, modify or delete rows/records in a relation are called DML
commands.
Example: INSERT INTO, UPDATE, DELETE FROM
Data Query Language (DQL):
Data Query Language (DQL) is a subset of SQL used only for querying data from a
database. It focuses on retrieving information without changing the data.
Example: SELECT
Datatypes in MySQL
The various datatypes of MySQL are
1. INT OR INTEGER:
A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned
range is from 0 to 4294967295.
2. FLOAT:
A floating-point number. Syntax: FLOAT (SIZE, D)
The total number of digits is specified in size. The number of digits after the decimal
point is specified in the d parameter.
Example: FLOAT (10,2) means total size 10 out of that 2 digits are in the decimal
part.
3. DATE:
Takes date in the form of ‘YYYY-MM-DD’. DATE displayed in a format like YYYY-MM-
DD, which contains 10 characters, but that is the display format, not necessarily
the storage size. The size of DATE datatype in MySQL is typically uses 3 bytes for
storage.
4. CHAR:
It is FIXED length string (can contain letters, numbers, and special characters).
The size can be from 0 to 255. Default is 1.
5. VARCHAR:
It is Variable length Character (can contain letters, numbers, and special
characters). The size can be from 0 to 65535.
Note:
1. MySQL commands are case insensitive.
2. All the commands in MySQL should be terminated by; (semicolon)
74 | Page
Create Command
This command is used to create a database/table /view.
Syntax:
Create database <databasename>;
Note:
Once a database is created, we have to use it. To use a database, the command is
USE <databasename>;
Example:
mysql> create database SCHOOL;
mysql>use SCHOOL;
CREATING A TABLE:
SYNTAX:
CREATE TABLE <TABLENAME> (FIELD1 DATATYPE(SIZE), FIELD2 DATATYPE
(SIZE)…………….);
Example:
CREATE TABLE STUDENT (RNO INT (5), NAME VARCHAR (20),CLASS CHAR (3), MARKS INT
(3));
DESC command
To see the structure of a table we use the command DESC (describe)
DESC <table_name>;
DESC STUDENT;
75 | Page
2 There are 5 candidate keys and one primary key in a table. How many
alternate keys are there in that table?
a) 3 b) 4 c) 5 d) 6
3 A non-key attribute, whose values are derived from primary key of some
other table.
a) Alternate key b) Foreign key c) Primary key d) Super Key
4 Pick the odd one out.
a) Update b) Delete c) Create d) Insert
5 Which of the following is not an example of DBMS?
a) MySQL b) Microsoft Access c) IBM DB2 d) Google
6 The default date format in MySQL is:
a) DD/MM/YYYY b) YYYY-MM-DD
c) MM-DD-YYYY d) YYYY/MM/DD
7 SQL stands for
a) Standard Query Language b) Structured Query Language
c) Standard Question Language d) Simplified Query Language
8 The attributes of a relation which are unique in their values and which are
eligible to become primary key are called
a) Alternate Key b) Foreign Key c) Candidate Key d) Eligible Key
9 Which of the following best describes a primary key?
a) A key that can accept null values
b) A key that uniquely identifies each record in a table
c) A duplicate value identifier d) A key used to join two tables
10 How many candidate keys can a table have?
a) Only one b) Zero c) One or more d) Exactly two
11 A foreign key in one table refers to:
a) A primary key in the same table b) A duplicate value in another table
c) A primary key in another table d) A unique constraint in any table
12 Which of the following is a DDL command?
a) SELECT b) UPDATE c) CREATE d) INSERT
13 Which statement is used to modify the structure of an existing table?
a) CHANGE b) ALTER c) UPDATE d) MODIFY
14 Which of the following is a DML command?
a) CREATE b) SELECT c) DROP d) DELETE
15 The SELECT statement in SQL is classified under:
a) DML b) DDL c) DCL d) DQL
16 What is the purpose of DQL in SQL?
a) Query and retrieve data b) Control access to data
c) Define data structure d) Delete data
17 DBMS stands for
a) Data Borrowing and Movement Software b) Database Management System
c) Digital Base Mapping System d) Database Manipulation Software
76 | Page
3 (b) Foreign key
4 (c) Create
5 (d) Google
6 (b) ‘YYYY-MM-DD’
7 (b) Structured Query Language
8 (c)Candidate Key
9 (b)A key that uniquely identifies each record in a table
10 (c)One or more
11 (c) A primary key in another table
12 (c) CREATE
13 (b)ALTER
14 (d) DELETE
15 (d)DQL
16 (a) Query and retrieve data
17 b) Database Management System
77 | Page
Assertion and Reasoning Questions
Choose correct option for given Assertion (A) and Reasoning (R)
a) Both A and R are true and R is the correct explanation of A.
b) Both A and R are true but R is not the correct explanation of A.
c) A is true but R is false. d) A is false but R is true.
1 Assertion (A): Each table must have one primary key.
Reason (R): Primary key is a set of one or more attributes that uniquely identifies
a tuple in a relation.
2 Assertion (A): The number of columns in a relation is called the degree of the
relation.
Reason (R): The number of tuples in a relation is called the cardinality of the
relation
3 Assertion (A): Database management system is an application software which
arranges data in a well-organized manner in the form of tables.
Reason (R): DBMS acts as an interface between the database stored in the
computer memory and the user.
4 Assertion (A): SQL has efficient mechanisms to retrieve data stored in multiple
tables in a MySQL database.
Reason (R): The SQL statement CREATE is used to retrieve data from the tables
in a database and is also called query statement.
5 Assertion (A): Data redundancy may lead to data inconsistency.
Reason (R): When redundant data or the multiple copies of data mismatch, it
makes the data inconsistent.
6 Assertion (A): A DBMS helps in maintaining data integrity and reduces
redundancy.
Reason (R): A DBMS stores data in multiple independent files without any
relationships.
7 Assertion (A): An RDBMS organizes data into tables with rows and columns.
Reason (R): Tables in RDBMS use relationships through keys to ensure data is
logically connected.
8 Assertion (A): A table can have multiple candidate keys.
Reason (R): There may be many attributes in a table which contain unique values.
9 Assertion (A): The SELECT statement is used to modify data in a table.
Reason (R): SELECT is part of the Data Query Language (DQL).
10 Assertion(A): A foreign key can have duplicate values.
Reason (R) : A foreign key establishes a relationship between two tables and
does not require uniqueness.
78 | Page
7 (a) Both A and R are true and R is the correct explanation of A.
8 (a) Both A and R are true and R is the correct explanation of A.
9 (d) A is false but R is true.
10 (a) Both A and R are true and R is the correct explanation of A.
DDL stands for Data Definition DML stands for Data Manipulation
Language Language
DDL commands are used to modify DML commands are used to modify the
the structure of a relation data inside a relation
Eg: Create Table, Alter table, Drop Eg: Insert into, Update, Delete
table
13. What do you mean by cardinality and degree of a relation?
Answer: The number of tuple of a relation is called cardinality and the number of
attributes of a relation is called degree of the relation
14. Explain what is metadata?
Answer: Data about data is called metadata. It contains the structure (table names
and their fields/columns), the type of data each column can hold, constraints on the
data to be stored (if any), and the relationships among the tables.
15. Give any 2 features of MySQL.
Answer: MySQL is an RDBMS and is easy to use and Manage
It is an open-source software which is secure, reliable and can handle large volume of
data.
80 | Page
16. A database has two tables:
Students (StudentID, Name, ClassID) and Classes (ClassID, ClassName)
You need to relate students to their respective classes.
Which key should you use in the Students table to refer to the Classes table?
Answer: ClassID
a. Which column in the STUDENT table is most suitable to be chosen as the Primary Key?
Why?
b. Which among the attributes have least chance to become a candidate key?
c. While trying to add a new row: 102, “Rekha Gupta”, 11, 16, xyz@[Link] the DBMS is
giving an error “duplicate entry”. What may be the reason?
d. Swayam wants to add details of new students but value of admission no (Admnno) is not
available, he has studied that if value is not available for an attribute NULL can be inserted.
But when he tried to insert new row with NULL value of Admnno, he gets an error. What
would be the reason for that?
Answer:
a. Admnno as it will not have any duplicate values.
b. Class and Age attribute cannot become candidate keys as both are having duplicate values.
c. A tuple with Admnno 102 already exist in the table and Admnno must have been chosen as
the Primary Key.
d. Primary key applied on Admnno Column. No new record can be inserted in any table, if value
of Primary Key column is not given.
81 | Page
Data Definition Language (DDL)
Mind Map
82 | Page
Data Manipulation Language (DML)
Mind Map
83 | Page
Data Query Language (DQL)
Mind Map
84 | Page
Table: sportsclub
● Selecting Columns: SELECT statement can be used in various ways and combinations to
retrieve subset of columns from one or more tables.
85 | Page
● Selecting specific rows using SELECT command -Where clause:
• WHERE clause in SELECT statement is used to filter the data. It selects the specific rows
from a table based on the given condition.
* Syntax:
SELECT <column1, column2, …>
FROM <table_name>
WHERE <condition>;
SQL requires single quotes or double quotes around text values. However, numeric fields
should not be enclosed in quotes.
⮚ Comparison Operators:
In the above example, we have used equal to (=) operator in the WHERE clause for exact
match conditions. We can also use other relational/comparison operators (<, <=, >, >=, ! =, <
>) to specify conditions other than exact match.
86 | Page
Operator Query Command Output
⮚ Logical operators:
In a WHERE clause, logical operators like AND, OR, and NOT are used to combine multiple
conditions and create more complex filters for data retrieval. These operators help to define
the criteria for which rows are included in the result set.
87 | Page
OR Display details of SELECT * FROM
Rows are games that either sportsclub
selected if have fees more than WHERE
any one or 20,000 or have Fees > 20000 OR
all
more than 3 clubs noofclubs >3;
condition
from a table
is true.
sportsclub.
NOT Display GCode, SELECT GCode,
Negate a Game Name and GameName,
condition. Starting Date of all StartingDate
It returns games except Chess FROM sportsclub
rows
from a table WHERE NOT
where the
sportsclub. GameName=
condition
is false. ‘Chess’;
⮚ Between operator:
This clause facilitates us to give a range of values. So, if you want to impose a condition in
which you wish to include a range of values, we use the Between clause.
Note: both values are inclusive in the range you give in the "Between" clause
⮚ IN -Membership Operator:
The IN operator is used to filter data for a specified set of values. It can also be used to
replace multiple OR conditions.
Operator Query Command Output
IN – List Show Gcode and SELECT *
condition Fees of all the FROM
games where the Sportsclub WHERE
Game Name is GameName IN
either 'Carom', (‘Carom’, Chess’,
'Chess', or 'Lawn ‘Lawn Tennis’);
Tennis' from a
table sports club
88 | Page
⮚ IS operator- Handling NULL Values:
SQL Supports a special value called NULL to represent a missing or unknown value. For
example, the village column in a table called address will have no value for cities. Hence, NULL
is used to represent such unknown values. It is important to note that NULL is different from
0 (zero). Also, any arithmetic operation performed with NULL value gives NULL. For example:
5 + NULL = NULL because NULL is unknown hence the result is also unknown. In order to
check for NULL value in a column, we use IS NULL.
Many a times we come across situations where we don't want to query by matching exact text
or value. Rather, we are interested to find matching of only a few characters or values in
column values. For example, to find out names starting with ‘T' or to find out pin codes
starting with ‘60'. This is called substring pattern matching. We cannot match such patterns
using = operator as we are not looking for exact match. SQL provides LIKE operator that can
be used with WHERE clause to search for a specified pattern in a column.
The LIKE operator makes use of the following two wild card characters:
(i) % (percentage) (ii) (underscore)
89 | Page
(ii) Displays (ii) (ii)
details of all Select * from
those games sportsclub where
whose game Gamename like
name consists ‘__r__’;
of exactly 5
letters and 3rd
character is ‘r’
from a table
sports club
Example: Combination of both % (multi character pattern matching operator) and _ (single
character pattern matching operator)
Query: Displays names of all employees containing 'a' as the second character.
mysql> SELECT EName FROM EMPLOYEE WHERE Ename LIKE '_a%';
Data Manipulation Language (DML):
The SQL commands that deals with the manipulation of data present in the database belong
to DML or Data Manipulation Language and this includes most of the SQL statements. It is the
component of the SQL statement that controls access to data and to the database.
List of DML commands:
• INSERT: It is used to insert data into a RELATION(TABLE).
• UPDATE: It is used to update existing data in a RELATION (TABLE)
• DELETE: It is used to delete records from a database RELATION(TABLE).
90 | Page
one or more (ii) Change the name (ii) UPDATE
columns of of Judo club to ‘Judo specific rows-
existing and Taekwondo’. UPDATE
records in a <TABLE_NAME>
table. SET<columnname
= value> WHERE
<condition>;
DELETE - The (i) Delete all the rows (i) Syntax to
DELETE from sportsclub. DELETE all rows:
statement is
used to delete DELETE FROM
one or more <TABLE_NAME>; * Data of sportsclub tables gets
record(s) deleted
from a table
(ii) Delete all games (ii) DELETE
having noofclubs <4 specific rows:
DELETE FROM
<TABLE_NAME>
WHERE
<Condition>;
• DDL Commands in MySQL
DDL (Data Definition Language) commands are used to define and manage database structures
like tables, databases, indexes, etc.
Command Purpose
CREATE Creates database or table
ALTER Modifies table structure
DROP Deletes database or table
RENAME Renames a table
1. ADD COLUMN
Syntax: ALTER TABLE table_name ADD column_name datatype;
Eg: ALTER TABLE student ADD age INT;
3. MODIFY COLUMN
Used to change datatype or size of a column.
Syntax: ALTER TABLE table_name MODIFY column_name new_datatype;
Eg: ALTER TABLE student MODIFY name VARCHAR (50);
5. DROP COLUMN
Syntax: ALTER TABLE table_name DROP COLUMN column_name;
Eg: ALTER TABLE student DROP COLUMN age;
6. RENAME TABLE
Syntax: ALTER TABLE old_table_name RENAME TO new_table_name;
Eg: ALTER TABLE student RENAME TO students;
92 | Page
Multiple Choice Questions (DQL)
1. Which of the following is a DQL command?
a) INSERT b) UPDATE c) SELECT d) DELETE
2. The SELECT statement is used to:
a) Insert new records b) Delete records
c) Modify existing records d) Retrieve data from one or more tables
3. Which clause is used with SELECT to filter rows based on a condition?
a) WHERE b) GROUP BY c) ORDER BY d) HAVING
4. What is the main use of the WHERE clause in SQL?
a) To define a new table b) To sort records
c) To filter records based on a condition d) To group records
5. Which operator is used with the WHERE clause to check for a range?
a) BETWEEN b) IN c) LIKE d) AS
6. Which SQL statement will return all customers with names starting second character
with 'M’ and last character is M?
a) SELECT * FROM Customers WHERE CustomerName LIKE 'M%M';
b) SELECT * FROM Customers WHERE CustomerName LIKE '_M';
c) SELECT * FROM Customers WHERE CustomerName LIKE '__M%M';
d) SELECT * FROM Customers WHERE CustomerName LIKE 'M__%M';
7. What does the LIKE operator do in the WHERE clause?
a) To insert values b) Matches values using patterns
c) Checks for NULL values d) Compares numeric ranges
8. What is the result of this query?
SELECT * FROM customers WHERE city = 'Delhi' OR city = 'Mumbai';
a) Customers from any city b) Only customers from Delhi
c) Customers from Delhi or Mumbai d) No result
9. What will the following SQL query return?
SELECT * FROM orders WHERE status IS NULL;
a) All orders with status set to 'null' b) All orders where status is undefined
c) All orders where status is empty string d) Syntax error
10. Which SQL statement finds employees whose age is between 25 and 35 (inclusive)?
a) SELECT * FROM employees WHERE age = 25 AND 35;
b) SELECT * FROM employees WHERE age BETWEEN 25 AND 35;
c) SELECT * FROM employees WHERE age > 25 AND < 35;
d) SELECT * FROM employees WHERE age IN RANGE (25, 35);
Answers (Multiple Choice Questions) DQL
1. c) SELECT
2. d) Retrieve data from one or more tables
3. a) WHERE
4. c) To filter records based on a condition
5. a) BETWEEN
6. c) SELECT * FROM Customers WHERE CustomerName LIKE '__M%M';
7. b) Matches values using patterns
8. c) Customers from Delhi or Mumbai
9. b) All orders where status is undefined
10. b) SELECT * FROM employees WHERE age BETWEEN 25 AND 35;
93 | Page
Multiple Choice Questions (DML)
1. Which of the following is NOT a DML command?
a) INSERT b) SELECT c) UPDATE d) DELETE
2. Which SQL command is used to add new rows to a table?
a) ADD b) INSERT c) APPEND d) INCLUDE
3. The UPDATE statement is used to:
a) Add new data b) Delete existing data
c) Modify existing data d) Retrieve data
4. Which keyword is used in UPDATE statement to specify which records should be
updated?
a) SET b) WHERE c) FROM d) SELECT
5. To remove records from a table, which command is used?
a) ERASE b) REMOVE c) DROP d) DELETE
6. Which statement will update the salary of employees by 10% in an EMPLOYEE
table?
a) UPDATE EMPLOYEE SET salary = salary + 10;
b) UPDATE EMPLOYEE ADD salary = (Salary * 0.1) + Salary;
c) UPDATE EMPLOYEE SET salary = (Salary * 0.1) + Salary;
d) MODIFY EMPLOYEE SET salary = salary + 10;
7. What will happen if you execute DELETE FROM table_name; without a WHERE
clause?
a) Syntax error b) Deletes a random row
c) Deletes all rows d) Deletes only the first row
8. Which of the following statements is used to insert multiple rows in one query?
a) INSERT ALL INTO…. b) INSERT MULTIPLE INTO ...
c) INSERT INTO table_name VALUES (), (), (); d) MULTI INSERT INTO ...
9. Which of these statements is true about the DELETE statement?
a) It removes the entire table permanently.
b) It can be used with a WHERE clause to remove selected rows.
c) It requires the use of SET
d) It always deletes just one row.
10. What is the result of the following SQL query?
DELETE FROM students WHERE marks < 40;
a) Deletes students with exactly 40 marks
b) Deletes students with more than 40 marks
c) Deletes students with less than 40 marks
d) Syntax error
94 | Page
7. c) Deletes all rows
8. c) INSERT INTO table_name VALUES (), (), ();
9. b) It can be used with a WHERE clause to remove selected rows.
10. c) Deletes students with less than 40 marks
Assertion and Reasoning Questions
Choose correct option for given Assertion (A) and Reasoning (R)
a) Both A and R are true, and R is the correct explanation of A.
b) Both A and R are true, but R is not the correct explanation of A.
c) A is true, but R is false.
d) A is false, but R is true.
1. Assertion (A): The SELECT statement can modify data in a table.
Reason (R): SELECT is a part of DQL and is used for retrieving data.
2. Assertion (A): In SQL, INSERT INTO is a Data Definition Language (DDL) Command.
Reason (R): DDL commands are used to create, modify, or remove database
structures, such as tables.
3. Assertion (A): The INSERT, UPDATE, and DELETE commands are part of DML.
Reason (R): These commands manipulate the data stored in database tables.
4. Assertion: The SQL WHERE clause is used for sorting the result set of a query.
Reason(R): The WHERE clause specifies conditions to filter rows in a query.
5. Assertion: The IS NULL operator in SQL checks if a column has a NULL value.
Reason(R): The IS NULL operator checks if a column contains a specific value.
6. Assertion (A): The DELETE command can be used to remove all rows from a table.
Reason (R): The DELETE statement requires a WHERE clause to execute.
7. Assertion (A): Both BETWEEN and IN operators can choose from a range of values.
Reason (R): The value ranges and a list of values are interpreted in different ways in
SQL.
8. Assertion (A): The UPDATE command in SQL can modify existing records in a table.
Reason (R): The INSERT command is used to add new rows to a table.
9. Assertion (A): The LIKE operator is used in SQL to filter records based on pattern
matching.
Reason (R): The LIKE operator supports wildcards such as % for multiple characters
and _ for a single character.
10. Assertion (A): DML commands can affect the structure of the database schema.
Reason (R): Commands like INSERT, UPDATE, and DELETE do not change the
database structure.
Answer (Assertion and Reasoning Questions)
1. D) A is false, but R is true.
Explanation: SELECT only retrieves data and does not modify it.
2. D) A is false, but R is true.
Explanation: INSERT INTO is a DML command.
3. a) Both A and R are true, and R is the correct explanation of A.
4. D) A is false, but R is true.
Explanation: Assertion is false because the WHERE clause is not used for sorting.
Reason is true - the WHERE clause is indeed used to filter rows based on a
condition
95 | Page
5. c) A is true and R is False
Explanation: Assertion is True: The IS NULL operator checks if a column does not
have a value, i.e., it’s null, meaning "unknown" or "missing".
Reason is false: IS NULL does not check for a specific value—it checks for the
absence of any value at all.
6. c) A is true and R is False
Explanation: Assertion is True: You can delete all rows using DELETE FROM
table_name;
Reason is false: But a WHERE clause is optional — it’s used to delete specific
rows, not mandatory.
7. a) Both A and R are true, and R is the correct explanation of A.
8. b) Both A and R are true, but R is not the correct explanation of A.
9. a) Both A and R are true, and R is the correct explanation of A.
10. d) A is False, R is true
96 | Page
Ans. DELETE FROM STUDENT;
It is the correct query because * is not part of the syntax of
DELETE Command.
6. You have a database table named "Students" with columns "StudentID,"
"FirstName," "LastName," and "Age." Write an SQL query to delete all students below
the age of 18.
Ans. DELETE FROM Students WHERE Age < 18;
7. Write a query to display details of all those employees from EMPLOYEE table whose
name contains 7 characters, 3rd character is ‘M’ and 5th character is ‘K’.
Ans. Select * from EMPLOYEE where Ename LIKE ‘_ _M_K_ _’;
8. Match the following operators
Column A Column B
(a) range matching operator (i) <>
(b) multi character pattern matching operator (ii) NOT
(c) logical operator (iii)_(underscore)
(d) list matching operator (iv) %
(e) Single character pattern matching operator (v) Between
(f) relational operators (vi)IN
Ans.
Column A Column B
(a) range matching operator (v) Between
(b) multi character pattern matching operator (iv) %
(c) logical operator (ii) NOT
(d) list matching operator (vi)IN
(e) Single character pattern matching operator (iii)_(underscore)
(f) relational operators (i) <>
9. Explain the purpose of the SQL SELECT statement and provide an example of how it
is used to retrieve specific data from a database table.
Ans. The SQL SELECT statement is used to retrieve specific data from a database
table without altering it.
Example: SELECT FirstName, LastName FROM Employees;
10. Differentiate between Alter and Update command.
Ans.
Alter Command Update Command
(i) It is a DDL command. (i) It is a DML command
(ii) It is used to change the columns of the (ii) It is used to modify some or all
existing table such as: Adding a new records of the table specified by a
column, deleting a column, Changing condition.
the data type of the column, renaming
a column.
It is also used to add or delete the
constraints on an existing table.
97 | Page
Long type Questions with Answer:
SNo. Questions
1. Write output for (i) to (iv) MySQL queries on Customer table:
Table: CUSTOMER
ACCOUNTNO CNAME AG GENDE BALANCE ACCOUNTCOD
E R E
101 S k yadav 62 M 80000 7777
102 Viba mishra 52 F 90000 9999
103 Didar singh 32 M 75000 7777
104 M sharma 35 M 79000 Null
105 Simi arora 30 F 97000 8888
106 Dayal soni 26 M 68000 9999
(i) SELECT ACCOUNTNO, CNAME, BALANCE
FROM CUSTOMER WHERE CNAME LIKE ‘%N%’;
(ii) SELECT * FROM CUSTOMER
WHERE AGE>50 AND BALANCE>80000;
(iii) SELECT ACCOUNTNO, CNAME FROM CUTOMER
WHERE ACCOUNTCODE NOT IN (7777,9999);
(iv) SELECT * FROM CUSTOMER WHERE ACCOUNTCODE IS NULL;
Answer:
2. Observe the following table Watches and answer the questions from (i) to (iv):
Table: Watches
WATCHID WATCH_NAME PRICE TYPE QTY_STORE
W001 High Time 10000 Unisex 100
W002 Life Time 15000 Ladies 150
W003 Wave 20000 Gents 200
W004 High Fashion 7000 Unisex 250
W005 Golden Time 25000 Gents 100
(i) Write SQL query to change the Qty_Store of Golden Time watches to 300.
(ii) To display all the details of those watches whose name ends with ‘Time‘
(iii) Write a query to add the following record in Watches table
(‘W006’,’Rolex’,25000,’Gents’,200)
(iv) Write the query to delete all the records from the table, but table structure
should remain in the database.
98 | Page
Answer:
(i) Update Watches Set Qty_Store=300 Where Watch_Name= “Golden Time”;
(ii) Select * from Watches where Watch_Name like “%Time”;
(iii) Insert into Watches values (‘W006’,’Rolex’,25000,’Gents’,200);
(iv) Delete from Watches;
3. Write queries for (i) to (iv) which are based on the following table TRAVEL.
Table: TRAVEL
CNO CNAME TRAVELDATE KM VCODE NOP
101 K. Niwal 2015-12-13 200 V01 32
103 Fredrick Sym 2016-03-21 120 V03 45
105 Hitesh Jain 2016-04-23 450 V02 42
102 Ravi Anish 2016-01-13 80 V02 40
107 John Malina 2015-02-10 65 V04 2
104 Sahanubhuti 2016-01-28 90 V05 4
(i) To display CNO, CNAME, TRAVELDATE from the table TRAVEL.
(ii) To display the CNAME of all customers from the table TRAVEL who are
travelling by vehicle with code V01 or V02
(iii) To display the CNO and CNAME of those customers from the table TRAVEL
who travelled BETWEEN '2015-05-01' AND '2015-12-31' ‘.
(iv) To display all the details from table TRAVEL for the customers, who do not have
travel distance 120 KM.
Answer:
(i) Select CNO, CNAME, TRAVELDATE from TRAVEL;
(ii) Select CNAME from TRAVEL where VCODE= ‘V01’ or VCODE=’V02’;
(iii) Select CNO, CNAME from TRAVEL where TRAVELDATE BETWEEN
'2015-05-01' AND '2015-12-31';
(iv) Select * From TRAVEL where NOT KM=120;
4. Execute Query based on below Statements (i) to (iv) for table: SALES
Ecode Ename Address dojoin Amount Area
100 Amit Delhi 2017-09-29 5000.90 East
101 Sushant Gurgaon 2025-01-01 7000.75 East
102 Priya Noida 2024-04-25 3450.45 West
103 Mohit Delhi 2018-11-03 6000.50 North
104 Priyanshi Delhi 2019-12-15 8000.62 North
(i) Write a SQL query to display details of all salesmen whose date of joining is after
31st March 2024.
(ii) Display details of all employees whose name starts with ‘S’ and ends
with ‘t’.
(iii) Display Area, Employee name and PFamount calculated as Amount *0.01
of East or West area employees.
(iv) Write a SQL query to delete the record of Ecode as 102.
Answer:
(i) Select * From Sales where dojoin > ‘2024-03-31’;
(ii) Select * From sales where Ename like ‘S%t’;
(iii) Select Area, Ename, Amount*0.01 as PFamount from Sales where Area IN
(‘East’, ‘West’);
(iv) Delete from Watches where Ecode=102;
99 | Page
5. Study the following table DOCTOR and answer the following questions: -
TABLE: DOCTOR
ID NAME DEPT GENDER EXPERIENCE
101 John ENT M 12
104 Smith ORTHOPEDIC M 5
107 George CARDIOLOGY M 10
114 Lara SKIN F 3
109 K George MEDICINE F 9
105 Johnson ORTHOPEDIC M 10
117 Lucy ENT F 3
(i) Write SQL Query to display the details of all those Doctors whose name either
starts with ‘J’ or starts with ‘S’.
(ii) Write SQL Query to display the details of all female doctors having experience
more than 5 years.
(iii) Write the SQL Query to delete the records of Male doctors of ENT dept.
(iv) Write the SQL Query to update the experience of all doctors by 1.
Answer:
(i) SELECT * FROM Doctor WHERE Name LIKE 'J%' OR Name LIKE 'S%';
(ii) Select * from Doctor Where Gender=’F’ and Experience>5;
(iii) Delete from Doctor Where Gender=’M’ and department=’ENT’;
(iv) Update Doctor Set Experience=Experience+1;
100 | Page
Unit 4: Introduction to the Emerging Trends
What is it?
AI is a branch of computer science that enables machines to mimic human intelligence. This
means they can perform tasks like thinking, learning, problem-solving, and decision-making.
Key Features:
● Learns from experience
● Solves problems
● Makes decisions
Real-life Examples:
● Google Assistant answers your questions.
● Self-driving cars make driving decisions.
● Face recognition on smartphones.
101 | Page
2. Machine Learning (ML)
What is it?
ML is a subset of AI. It means teaching computers to learn from data and make predictions or
decisions without being explicitly told what to do every time.
How it works:
● Provide data → Computer analyzes it → Learns patterns → Makes predictions
Examples:
● YouTube recommends videos based on your watch history.
● Email filters move spam messages to the spam folder.
Why is it useful?
● It helps machines interact with humans using speech or text.
Examples:
● Google Translate
● Chatbots on websites
● Voice typing on smartphones
102 | Page
Virtual Reality (VR):
What is it?
VR creates a completely digital environment. You wear a headset and feel like you're inside a
different world.
Example:
Using a VR headset to walk through a virtual museum or play a 3D game.
5. Robotics
What is it?
Robotics is the field of designing and building robots—machines that can do tasks
automatically or with minimal human help.
Examples:
● Robot arms in factories
● Drones used for delivery or photography
● Cleaning robots at home
Characteristics (5 V’s):
103 | Page
7. Internet of Things (IoT)
What is it?
IoT connects everyday objects to the internet, allowing them to collect and exchange data.
Examples:
● Smartwatches that track your steps and heartbeat
● Smart lights that can be controlled via phone
● A fridge that tells you when you're out of milk
8. Sensors
What are they?
Sensors detect physical changes in the environment (like temperature, motion, light) and send
that information to a computer or device.
Examples:
● Temperature sensor in AC
● Motion sensor in security lights
104 | Page
● Fingerprint scanner on smartphones
9. Smart Cities
What is a Smart City?
A smart city uses technology to manage its resources efficiently and improve the quality of life
of its residents.
Features:
● Smart traffic management
● Smart energy use (like automatic street lights)
● Clean and efficient waste management
Examples:
● Cameras that monitor traffic and help reduce congestion
● Apps that tell you when your bus will arrive
105 | Page
● Securely storing property or medical records
106 | Page
15 Motion sensors are commonly used in:
a) Text editing software b) Social media platform
c) Food packaging d) Smart lighting systems
16 Which device commonly uses a fingerprint sensor?
a) Television b) Smartphone
c) Refrigerator d) Fan
17 Smart traffic lights use data to:
a) Change based on fixed time b) Operate manually by policemen
c) Optimize traffic flow dynamically d) Work only during the day
18 Which of the following is a feature of a smart city?
a) Smart traffic management b) Manual traffic lights
c) Paper maps d) Public payphones
19 What does Cloud Computing allow users to do?
a) Clean their computers b) Access computing services over the internet
c) Build physical servers d) Paint digital images
20 IaaS is used when organizations need:
a) Cloud-based software only b) Infrastructure like servers and networking
c) Web development platforms d) Voice-based control system
21 Grid Computing combines multiple computers to:
a) Share internet only b) Print documents faster
c) Work together on a task d) Reduce electricity use
22 Which of the following best describes Grid Computing?
a) One powerful computer b) Cloud-based storage
c) A software development tool
d)A network of computers solving problems together
23 Blockchain stores data in:
a) Boxes b) Sheets
c) Linked blocks d) File
24 Which of the following is built using Blockchain technology?
a) WhatsApp b) Bitcoin
c) Antivirus software d) MS Word
107 | Page
9 (b) Autonomously performing tasks
10 (c) Self-driving vacuum cleaner
11 (d) Visibility
12 (c) Different types of data (text, images, etc.)
13 (a) Physical devices like TVs, lights, and cars
14 (b) Managing home appliances remotely
15 (d) Smart Lighting Systems
16 (b) Smartphone
17 (c) Optimize traffic flow dynamically
18 (a) Smart traffic management
19 (b) Access computing services over the internet
20 (b) Infrastructure like servers and networking
21 (c) Work together on a task
22 (d) A network of computers solving problems together
23 (c) Linked blocks
24 (b) Bitcoin
1 Assertion (A): Artificial Intelligence helps machines make decisions like humans.
Reason (R): AI systems can learn from data and past experiences.
3 Assertion (A): NLP allows computers to understand human speech and text.
Reason (R): NLP translates machine code into human language.
6 Assertion (A): Big Data can be processed using traditional tools like Excel.
Reason (R): Big Data has high volume, velocity, and variety.
108 | Page
7 Assertion (A): IoT allows devices to communicate and share data.
Reason (R): IoT devices are connected via the internet and often use sensors.
9 Assertion (A): Smart cities aim to improve quality of life using technology.
Reason (R): Smart cities ignore sustainability and focus only on digital tools.
10 Assertion (A): Cloud computing allows access to software and data from anywhere.
Reason (R): Cloud services are stored on remote servers connected via the internet
109 | Page
3 Riya uses a learning app that suggests personalized topics for revision based
on her past performance. The app also gives real-time answers and tracks her
progress.
a) Identify the technology behind the app and how it mimics human
intelligence.
b) Mention two benefits of using such AI-based tools in education.
Answer:(a) The technology is Artificial Intelligence (AI), which enables the
app to analyze past data and make smart decisions, similar to how a teacher
might suggest topics.
Answer:(b) (i) Personalized learning experience and (ii) Instant doubt
resolution
4 Medical students use VR headsets to practice surgery in virtual operation
rooms that simulate real scenarios.
a) Explain how VR creates an immersive experience.
b) List two benefits of using VR for professional training in the medical field.
Answer: (a) VR simulates a 3D environment, making users feel as if they are
in the real surgical room.
Answer: (b) (i) Risk-free learning and (ii) Better hands-on practice.
5 What is meant by SaaS in cloud computing? Give one example.
Answer: SaaS stands for Software as a Service. It allows users to access
software over the internet. Example: Google Docs.
6 How does Blockchain ensure the security of data?
Answer: Blockchain uses cryptographic links between blocks, making it
tamper-proof and ensuring that data cannot be changed without altering all
subsequent blocks.
7 A farm uses soil sensors that send data to the farmer's phone and
automatically switch irrigation pumps on or off.
a) Explain how IoT works in this farming setup.
b) State two advantages of IoT in agriculture.
Answer: (a) Sensors collect data and communicate via the internet to control
pumps automatically.
Answer: (b) (i) Saves water and (ii) Increases crop yield.
8 A shopping website recommends clothes and gadgets based on what users
have previously browsed or purchased.
a) Explain how the website “learns” from user behavior.
b) State two ways Machine Learning improves user experience in online
shopping.
Answer: (a) The website uses Machine Learning (ML) to detect patterns in
user activity and uses algorithms to make future recommendations.
Answer: (b) (i) Saves time by showing relevant products and
(ii) enhances user satisfaction
9 A mobile app allows users to see how furniture will look in their room through
a phone camera.
a) Is this AR or VR?
b) Mention one advantage of this technology.
110 | Page
Answer: (a) Augmented Reality (AR).
Answer: (b) It helps users visualize products before purchasing.
111 | Page
3. IaaS (Infrastructure as a Service): Provides virtual hardware. Example:
Amazon Web Services (AWS)
112 | Page
i) Name the technology in which machines are designed to perform tasks that
normally require human intelligence.
ii) What are the devices called that collect data such as temperature, traffic
movement, or pollution levels in IoT systems?
iii) Identify the technology used to provide users with a computer-generated
immersive environment.
iv) Name the branch of Artificial Intelligence that enables computers to
understand and process human language.
v) Which technology allows data and applications to be stored and accessed
over the Internet instead of a personal computer?
Answer:
i) Artificial Intelligence (AI)
ii) Sensors
iii) Virtual Reality (VR)
iv) Natural Language Processing (NLP)
v) Cloud Computing
4 A smart city project is being developed to improve the lifestyle of people using
modern technologies. The city administration uses sensors to collect traffic data,
cloud computing services to store information, Artificial Intelligence to analyze
data patterns, and robots for automatic cleaning services. Citizens can also
experience important historical places using Virtual Reality (VR) technology.
(I) Which technology is used in the smart city to collect traffic data through
devices?
(II) Which technology uses distributed digital records connected in the form of
blocks?
(III) Name the computing technology in which multiple computers work together
to solve a large problem.
(IV) Machines capable of performing tasks automatically with minimum human
intervention are known as:
(V) Which of the following is an example of immersive experience technology?
a) Blockchain b) Virtual Reality c) Grid Computing d) Big Data
Answer:
(I) Internet of Things (IoT)
(II) Blockchain Technology
(III) Grid Computing
(IV) Robots / Robotics
(V) (b) Virtual Reality
113 | Page
KENDRIYA VIDYALAYA SANGATHAN
SESSION ENDING EXAM (2026-2027)
SAMPLE QUESTION PAPER (SOLVED)
Max. Marks: 70 Time: 3 Hours
General Instructions:
● Please check this question paper contains 37 questions.
● All questions are compulsory. However, internal choices have been provided in some
questions. Attempt only one of the choices in such questions
● The paper is divided into 5 Sections- A, B, C, D and E.
● Section A consists of 21 questions (1 to 21). Each question carries 1 Mark.
● Section B consists of 7 questions (22 to 28). Each question carries 2 Marks.
● Section C consists of 4 questions (29 to 32). Each question carries 3 Marks.
● Section D consists of 2 case study type questions (33 to 34). Each question carries 4
Marks.
● Section E consists of 3 questions (35 to 37). Each question carries 5 Marks.
● All programming questions are to be answered using Python Language only.
● In case of MCQ, text of the correct answer should also be written.
114 | Page
4 What will happen if the following query gets executed for Stock table. 1
DELETE FROM Stock;
(A) It deletes all rows from the table and also removes the table
structure from the database.
(B) It deletes all rows from the table but keeps the table structure intact.
(C) It removes the table from the database permanently.
(D) It throws an error because no WHERE clause is specified.
5 Which of the following is not a valid dictionary? 1
(A) {}
(B) {True: "Yes", False: "No", None: "Maybe"}
(C) {(10, 20, 30): "Tuple", 40: "Integer"}
(D) {‘a’: Apple, ‘b’: Banana, ‘c’: Cherry}
115 | Page
11 What is the output of this code? 1
x=5
while x > 0:
x -= 1
if x == 3:
continue
(A) 5 4 3 2 1 0
(B) 4 2 1 0
(C) 4 3 1 0
(D) Infinite loop
12 Match the following SQL clauses with their descriptions:
1
SQL Description
P DROP 1 Modifies a column
Q DELETE 2 Removes table and structure
R ALTER 3 Modifies a row
S UPDATE 4 Erase table data
116 | Page
16 What defines best to Ubuntu:
1
(A) Programming language (B) Web browser
(C) Operating System (D) Word Processing Tool
17 What is not true regarding Primary Key with respect to relational 1
database.
(A) Is made of a single column (B) Must have unique values
(C) Null values are not allowed (D) All the given statements are true
18
State whether the following statement is True or False: 1
In DBMS, all alternate keys are primary keys.
19 A table has a certain number of rows and columns. If a row is deleted and a
1
column is added, what happens to the cardinality and degree of the table?
(A) Cardinality increases, degree decreases
(B) Cardinality decreases, degree increases
(C) Cardinality increases, degree remains the same
(D) Cardinality remains the same, degree decreases
Q-20 and Q-21 are Assertion (A) and Reason (R) Type questions. Choose the correct
option as:
(A) Both Assertion (A) and Reason (R) are true, and Reason (R) is the correct
explanation of Assertion (A)
(B) Both Assertion (A) and Reason (R) are true, but Reason (R) is not the correct
explanation of Assertion (A)
(C) (C)Assertion (A) is True, but Reason (R) is False
(D) (D)Assertion (A) is False, but Reason (R) is True
21 Assertion (A): In SQL, the WHERE clause, when used with >=, AND, and <=,
functions similarly to the BETWEEN operator.
1
Reason (R): In SQL, the BETWEEN operator specifies a range of values that a
column value must fall within, including both endpoints.
117 | Page
23 Shreshtha wrote the following code to modify List1 based on a condition.
The code should append the number 8 to List1 if its length is greater than 2. 2
Otherwise, it should repeat List1 thrice. However, the code contains errors.
Identify and correct these errors by rewriting the corrected code and
underlining the changes made.
Shreshtha’s Code:
List1 = [1, 2, 3]
if [Link]()>2:
List1 = List1 + [8]
else:
List1 == List1 * 3
print(List1)
24 Given the following Trainer table, identify the fields, domain, tuple, and 2
relation with proper labelling:
Code Name Age Gender
1 S Kunal 35 M
2 Soma Majumdar 37 F
25 Given the dictionary my_d = {'p': 1, 'q': 2, 'r': 3}, write Python code to:
26 What are the main advantages of using Structured Query Language (SQL) in
database management? Give two examples of DBMS apart from SQL. 2
OR
What is the syntax to see all the Databases, access a Database, see all the
tables in a given database and to see the structure of a table.
27 How do the pop() and remove() methods differ in Python lists? Illustrate
with an example. 2
OR
What is the difference between the sort() method and the sorted() function
in Python? Provide an example that shows their working.
118 | Page
Q No. Section-C (4 x 3 = 12 Marks) Marks
Write SQL queries for the following questions using the Enrolment table :
1. Retrieve the names and classes of students who are in Class 4 section
A.
2. Retrieve the names of students enrolled on or after 2025-05-01.
3. Update the Section of the student with RollNo 1003 to "B".
31 Write a Python program to count the number of uppercase and lowercase 3
letters in a given string.
Example: Input: eContent 2026-27
Output: Uppercase: 1, Lowercase: 7
OR
Write a program to print the Table of a given number.
Example:
Input: 5
Output:
5X1=5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
119 | Page
32 Sales Table 3
TotalAmou
SaleID ProductName SalesPerson Region SaleDate
nt
Rajesh
201 Industrial Gear North Zone 2025-11-20 25000
Kumar
202 Steel Beams Meera Jain East Zone 2025-11-22 15000
Sanjay
203 Safety Helmets West Zone 2025-11-25 NULL
Verma
204 LED Lights Priya Mishra South Zone 2025-11-28 5000
205 Paint Supplies Anil Kumar North Zone 2025-12-01 12000
Given above is the Sales table of a company. Please write the SQL
commands for the below queries:
1. Write a query to find the details of all sales person whose name
ends with "Kumar".
2. Write a query to display the Sales details of the product whose
amount is null.
3. Write a query to display the Sales details of product having region
name of exactly 9 characters (East Zone and West Zone) and where
amount is greater than 5000.
Q No. Section-D (2 x 4 = 8 Marks) Marks
33 Write a Python program that takes a list of numbers as input and calculates
how many times each number appears in the list. The program should 4
create a dictionary where each unique number from the list is a key, and its
value is the count of how many times it occurs in the list.
For example, if the list is [4, 5, 6, 4, 5, 4], the program should output {4: 3,
5: 2, 6: 1}.
34 Here is the structure of a table Stock with a sample data. Write SQL queries for
the questions that follow:
Stock_ID Stock_Name Stock_Type Quantity Price 4
1 Laptop Electronics 15 50000
1. Create a table named Stock with columns for Stock_ID, Stock_Name,
Stock_Type, Quantity, and Price with proper datatype and primary key.
2. Modify the Stock table to add a new column Supplier_Name of type
VARCHAR(50).
3. Delete the Price column from the Stock table.
4. Which of the columns must be the primary key. Justify your answer.
Q No. Section-E (3 x 5 = 12 Marks) Marks
35 i. Describe the main components of a computer system along with the
diagram. Explain how they are interconnected to perform a task.
3+2=5
ii. Classify the following devices as input, output, or input-output devices:
Touchscreen, Microphone, Speaker, Graphics Tablet, External Storage
Device
120 | Page
36 Given the following while loop: 5
i = 10
while i >= 0:
print(i)
i -= 2
Convert the above while loop into an equivalent for loop.
Convert the below for loop into an equivalent while loop.
L=[10,20,30,40,50]
for i in range(len(L)):
print(L[i])
OR
Write a Python program to calculate the income tax based on the following
tax slabs:
● If the income is less than or equal to ₹2,50,000, no tax is applicable.
● If the income is between ₹2,50,001 and ₹5,00,000, tax is 5% of the
income exceeding ₹2,50,000.
● If the income is between ₹5,00,001 and ₹10,00,000, tax is 10% of the
income exceeding ₹5,00,000 plus ₹2,500.
● If the income is greater than ₹10,00,000, tax is 20% of the income
exceeding ₹10,00,000 plus ₹12,500.
Your program should ask the user to input their annual income and then
calculate and print the income tax based on the above conditions.
37 Consider the following table Events, that is to be organized in a school. Write 5
SQL queries for the questions that follows:
Prg_I Participant
Prg_Name Date Location Incharge
D s
Annual Drama
801 2024-02-28 Auditorium 80 Arjun Patel
Night
Dance Dr. S. R.
802 2024-03-22 Main Hall 60
Performance Verma
School
803 Musical Concert 2024-04-12 100 Anjali Das
Grounds
Poetry
804 2024-05-07 Classrooms 50 Neha Gupta
Recitation
Folk Dance
805 2024-06-20 Open Ground 70 Rajesh Jain
Festival
i. Insert a new event into the table with Prg_ID as 806, Prg_Name as
"Science Exhibition," Date as 15 July 2024 in proper format,"
Location as "Science Block," Participants as 120, and Incharge as
"Dr. Kavita Singh."
ii. Increase the number of participants for "Dance Performance" by
10.
iii. Remove the record for "Poetry Recitation" from the table.
iv. Change the location of "Folk Dance Festival" to "Cultural Stage".
v. List all details of programs scheduled between March 1, 2024, and
June 1, 2024.
121 | Page
KENDRIYA VIDYALAYA SANGATHAN
SESSION ENDING EXAM (2026-2027)
CLASS- XI (INFORMATICS PRACTICES –065)
MARKING SCHEME
Q. No Section A (21 x 1 = 21 Marks) Marks
1. Q1: B. 1-40 1
Solution: The domain for the attribute Roll_Number must include
numbers assigned to all students, i.e., 1 to 40.
(1 mark for correct answer)
2. Q2: D. All of the above statements 1
Solution: All the listed statements output "Raipur" correctly when
executed. (1 mark for correct answer)
3. Q3: C. 1 1
Solution:
Nums = [3, 4, 5, 1, 2]
print([Link]([Link]())) # Output: 5
The second [Link]() removes the last element (2) and returns it.
The first [Link](2) removes and returns the element at index 2,
which is 5.
(1 mark for correct answer)
4. Q4: B. It deletes all rows from the table but keeps the table 1
structure intact.
Solution: The DELETE statement removes rows while preserving the
table structure unless DROP or TRUNCATE is used.
(1 mark for correct answer)
5. Q5: D. {‘a’: Apple, ‘b’: Banana, ‘c’: Cherry} 1
Solution: values of the dictionary should be enclosed in ‘ ‘ or “ ” or ‘’’
‘’’’ quotes to make them valid strings.
(1 mark for correct answer)
6. Q6: C. [Link](d2) 1
Solution: update() add key-value pairs from one dictionary to
another.
(1 mark for correct answer)
7. Q7: C. 4048 KB 1
Solution: 1 MB equals 1024 KB in digital storage.
(1 mark for correct answer)
8. Q8: A. Name Error 1
Solution: The variable L is not defined, resulting in a Name Error.
(1 mark for correct answer)
9. Q9: C. [Link](2, 8) 1
Solution: The insert() function takes the index (2) and the element
(6) to insert at 3rd position.
(1 mark for correct answer)
122 | Page
10. Q10: C. 1 – Primary key, 2 – Candidate key, 3 – Super key 1
Solution: The correct labels match the definitions of keys in a
relational database.
(1 mark for correct answer)
11. Q11: B. 4 2 1 0 1
Solution: The loop skips x == 3 due to continue and prints the
remaining values.
(1 mark for correct answer)
12. Q12: B. P-2, Q-4, R-1, S-3 1
Solution: Correct matching of SQL clauses with their purposes.
(1 mark for correct answer)
13. Q13: B. HDD, SSD, RAM, Cache 1
Solution: Cache has the fastest data transfer speed, followed by RAM,
SSD, and HDD.
(1 mark for correct answer)
14. Q14: A. FOSS provides access to the source code, while freeware 1
does not.
Solution: Freeware is free but does not provide modifiable source
code, unlike FOSS.
(1 mark for correct answer)
15. Q15: D. Abacus 1
Solution: Abacus was the earliest mechanical device for calculations.
(1 mark for correct answer)
16. Q16: C. Operating System 1
Solution: Ubuntu is a popular Linux-based operating system.
(1 mark for correct answer)
17. Q17: D. All the given statements are true 1
Solution: The statements about the Primary Key are all valid in
relational databases.
(1 mark for correct answer)
18. Q18: False 1
Solution: all Alternate keys are not primary keys.
(1 mark for correct answer)
19. Q19: B. Cardinality decreases, degree increases 1
Solution: Deleting a row decreases cardinality, and adding a column
increases the degree.
(1 mark for correct answer)
20. Q20: C. Assertion (A) is True, but Reason (R) is False 1
Solution: Null represents missing data and is not equivalent to zero.
(1 mark for correct answer)
21. Q21: A. Both Assertion (A) and Reason (R) are true, and Reason 1
(R) is the correct explanation of Assertion (A)
Solution: The BETWEEN operator includes the specified range, like
the conditions combined.
(1 mark for correct answer)
123 | Page
Section B (7 x 2 = 14 Marks)
22. (A) IoT: Internet of Things (IoT) refers to a network of physical 2
interconnected objects that communicate and share data with
minimal human intervention.
Two Primary components of IoT systems are:
Sensors/Devices, Connectivity
OR
(B) Big Data: Big Data signifies large datasets that traditional data-
processing tools cannot manage.
Characteristics: Volume, Velocity, Variety, Veracity, and Value.
(1 mark for explanation + 1 mark for diagram/characteristics)
23. Solution: 2
Corrected Code:
List1 = [1, 2, 3]
if len(List1) > 2: # Corrected to 'len(List1)'
List1 = [Link](8) # Corrected function
else:
List1 = List1 * 3 # Corrected indentation and '='
print(List1)
(1/2 marks for each correction)
24. Solution: 2
Field: Columns or attributes (e.g., Code, Name, Age, Gender).
Domain: Possible values of a column (e.g., Age: 35, 37).
Tuple: A single row in the table (e.g., [1, S Kunal, 35, M]).
Relation: The entire table (Trainer Table).
(1/2 marks for each correct answers)
25. Solution: 2
(A) Delete and clear operations:
my_d = {'p': 1, 'q': 2, 'r': 3}
del my_d['q']
my_d.clear()
(2 marks for correct code)
OR
(B) Traverse dictionary:
for key, value in [Link]():
print(key, ":", value)
(2 marks for correct code, any other correct alternate solution)
26. Solution: 2
Advantages of SQL: Easy to learn, manage, and query large databases.
Examples of DBMS: Microsoft Access, Oracle Database, MongoDB etc.
(1 mark for advantages + 1 mark for examples)
OR
SHOW DATABASES, USE db_nm, SHOW TABLES, DESC Table_Name
(1/2 marks for each correct answers)
124 | Page
27. Solution: 2
(A) pop() vs remove():
Mylist = [1, 2, 3, 4]
[Link](2) # Removes and returns the item at index 2
[Link](4) # Removes the first occurrence of 4
OR
(B) sort() vs sorted():
Mylist = [3, 1, 2]
[Link]() # Modifies list1
print(sorted(Mylist, reverse=True))#Returns a new sorted list
(2 marks for correct explanation and examples)
28. Solution: 2
Y=127
(2 marks for correct answer)
Section C (4 x 3 = 12 Marks)
29. Solution: 3
PaaS: Platform as a Service (e.g., Online Compiler)
SaaS: Software as a Service (e.g., Dropbox)
IaaS: Infrastructure as a Service (e.g., Virtual Machines)
Justification: SaaS delivers software, PaaS provides platforms, and
IaaS offers infrastructure.
(1 mark for full forms + 1 mark for matching and 1 mark for
justification)
30. Solution (SQL Queries): 3
(i) Names and classes of students in Class 6, Section A:
SELECT Name, Class FROM Enrolment WHERE Class = 4 AND Section
= 'A';
(ii) Students enrolled after 2023-05-01:
SELECT Name FROM Enrolment WHERE EnrDate >= '2025-05-01';
(iii) Update Section for RollNo 1003:
UPDATE Enrolment SET Section = 'B' WHERE RollNo = 1003;
(1 mark each)
31. Solution : 3
(A) Count Uppercase and Lowercase:
s = "eContent 2026-27"
upper, lower = 0, 0
for char in s:
if [Link]():
upper += 1
elif [Link]():
lower += 1
print("Uppercase:", upper, "Lowercase:", lower)
OR
(B) Multiplication Table:
n = int(input(“Enter a number”))
for i in range(1, 11):
print(n, “X”, i, “=”, n*i)
(3 marks for correct program)
125 | Page
32. (i) Find salespersons with names ending in "Kumar": 3
SELECT * FROM Sales WHERE SalesPerson LIKE '%Kumar';
(ii) Display product with null amount:
SELECT * FROM Sales WHERE TotalAmount IS NULL;
(iii) Products in regions with 9-character names and amount > 5000:
SELECT * FROM Sales WHERE Region LIKE '_________' AND
TotalAmount > 5000; (8 underscores)
(1 mark each)
Section D (2 x 4 = 8 Marks)
33. Solution: 4
Python program to count occurrences in a list:
nums = [4, 5, 6, 4, 5, 4]
freq = {}
for num in nums:
freq[num] = [Link](num, 0) + 1
print(freq)
Output: {4: 3, 5: 2, 6: 1}
(4 marks for this program or any other correct logic)
34. Solution: 4
(i) Create Stock table:
CREATE TABLE Stock (
Stock_ID INT PRIMARY KEY,
Stock_Name VARCHAR(50),
Stock_Type VARCHAR(30),
Quantity INT,
Price FLOAT
);
(ii) Add new column:
ALTER TABLE Stock ADD Supplier_Name VARCHAR(50);
(iii) Delete Price column:
ALTER TABLE Stock DROP COLUMN Price;
(iv) Primary Key:
Stock_ID must be the primary key as it uniquely identifies each
record.
(1 mark each)
Section E (3 x 5 = 15 Marks)
35. Solution: 5
Components of a Computer System: CPU, Memory, Input, Output
devices, and Storage.
Classification of devices:
Input: Microphone, Graphics Tablet, Touchscreen
Output: Speaker, External Storage Device
126 | Page
36. Solution: 5
(A)
Convert while loop to for loop:
for i in range(10, -1, -2):
print(i)
Convert for loop to while loop:
L = [10, 20, 30, 40, 50]
i=0
while i < len(L):
print(L[i])
i += 1
(2.5 marks for correct conversion for each)
OR
(B) Income Tax Calculation:
python
Copy code
income = int(input("Enter your income: "))
if income <= 250000:
tax = 0
elif income <= 500000:
tax = (income - 250000) * 0.05
elif income <= 1000000:
tax = (income - 500000) * 0.1 + 2500
else:
tax = (income - 1000000) * 0.2 + 12500
print("Tax:", tax)
(5 marks for correct logic and implementation)
37. (i) Insert new event: 5
INSERT INTO Events VALUES (806, 'Science Exhibition', '2024-07-
15', 'Science Block', 120, 'Dr. Kavita Singh');
(ii) Update participants for "Dance Performance":
UPDATE Events SET Participants = Participants + 10 WHERE
Prg_Name = 'Dance Performance';
(iii) Delete record for "Poetry Recitation":
DELETE FROM Events WHERE Prg_Name = 'Poetry Recitation';
(iv) Update location for "Folk Dance Festival":
UPDATE Events SET Location = 'Cultural Stage' WHERE Prg_Name =
'Folk Dance Festival';
(v) List programs scheduled between March 1, 2024, and June 1,
2024:
SELECT * FROM Events WHERE Date BETWEEN '2024-03-01' AND
'2024-06-01';
(1 mark each)
127 | Page
KENDRIYA VIDYALAYA SANGATHAN
UNSOLVED QUESTION PAPER - 01
CLASS XI - INFORMATICS PRACTICES (065)
Time allowed: 3 Hours Maximum Marks:70
128 | Page
13 The FROM clause in SQL is used to- 1
(A) specify what table we are selecting the data
(B) specify the columns that we want to be displayed
(C) specify search condition
(D) remove repeating values from being displayed
14 Which SQL statement is used to change the data in a table of a database? 1
(A) SAVE (B) UPDATE (C) SAVE AS (D) MODIFY
15 The SQL query to find the details of all the cities whose humidity is in the range 1
of 63 to 79 (including both 63 and 79) is-
(A) SELECT * FROM weather WHERE humidity IN (63 to 79)
(B) SELECT * FROM weather WHERE humidity NOT IN (63 AND 79)
(C) SELECT * FROM weather WHERE humidity BETWEEN 63 AND 79
(D) SELECT * FROM weather WHERE humidity NOT BETWEEN 63 AND 79
16 The SQL ALTER statement is used to- 1
(A) change the table data. (B) change the table structure.
(C) delete rows from the table. (D) add rows to the table.
17 The command to eliminate a table from a database is- 1
(A) DROP TABLE CUSTOMER; (B) DELETE TABLE CUSTOMER;
(C) REMOVE TABLE CUSTOMER; (D) UPDATE TABLE CUSTOMER;
18 Which of the following query is correct for using comparison operators in 1
SQL?
A. SELECT name, course_name FROM student WHERE age>50 and <80;
B. SELECT name, course_name FROM student WHERE age>50 and age <80;
C. SELECT name, course_name FROM student WHERE age>50 and WHERE
age<80;
D. None of these
19 CREATE TABLE employee (name VARCHAR(10), id INTEGER); 1
What type of statement is this?
(A) DML (B) DDL (C) View (D) Integrity constraint
Q-20,21 are Assertion (A) and Reason (R) Type questions. Choose the
correct option as:
(A) Both Assertion (A) and Reason (R) are true, and Reason (R) is the
correct explanation of Assertion (A)
(B) Both Assertion (A) and Reason (R) are true, but Reason (R) is not
the correct explanation of Assertion (A)
(C) Assertion (A) is True, but Reason (R) is False
(D) Assertion (A) is False, but Reason (R) is True
20 Assertion (A): List and Dictionary are mutable data types in python. 1
Reason (R): In both list and dictionary we can add, delete and update the
elements in place
21 Assertion (A): In SQL, INSERT INTO is a Data Definition Language (DDL) 1
Command.
129 | Page
Reason (R): DDL commands are used to create, modify, or remove database
structures, such as tables.
OR
130 | Page
Price Decimal(5,2)
28 (A) Explain Blockchain 2
OR
Explain Grid Computing
(B)
QNo Section-C (4 x 3 = 12 Marks) Marks
29 Draw and explain the block diagram of a computer. 2+1=
3
and write the name of Two Input and Output devices.
30 (A) Phuntsok has started his coding lessons in Python. Help him to 3
write a program to accept the sales made in a shop and calculate
the percentage of discount as per the following table:
[Link] Sales Discount
1 < 1000 No discount
2 Between 1000 5%
and 5000
3 More than 5000 10%
Display the discount percentage as well as the final
discounted price to be paid.
OR
Percentage Result
(B) More than 75 percent First Class
60 to 75 percent Second Class
40 to 60 percent Pass Class
Less than 40 percent Fail
Sonam, a software trainee has been assigned a task to write a
program that accepts the percentage of a student and then gives
the result of the student as per the following table. Help her in
accomplishing this task
(a) Suggest the Primary key for the table giving appropriate reasons.
(b) Write the SQL command to insert the following data in the table:
131 | Page
Salesid - E009, Name-Sukumar, City-Nagpur, Commission-10
(c) Is the command used in part (b) a DDL or a DML command
32 (A) What is Big Data? Explain any four features of Big Data. 3
OR
(B) What is Cloud Computing? Explain any two services offered on
the cloud.
Q No. Section-D (2 x 4 = 8 Marks) Marks
33 Write a program to accept the name of an item and its price repeatedly from 4
the user and use it to create a dictionary. The key is the item name and the value
is the price of the item. Ask the user for an item name and then find its price
34 (A) Consider the following table BOOK and answer the questions 4
that follow:
Table: BOOK
BCODE TITLE AUTHOR PRICE
MIDNIGHT’S SALMAN
B001 500
CHILDREN RUSHDIE
THE GOD OF
B002 ARUNDHATI 450
SMALL THINGS
ROY
VIKRAM
B003 A SUITABLE BOY 600
SETH
THE WHITE ARAVIND
B004 399
TIGER ADIGA
TRAIN TO
B005 KHUSHWAN 350
PAKISTAN
T SINGH
Table: MEDICINE
MID MED_NAME SUPP_CITY STOCK DEL_DATE
M01 PARACETAMOL MUMBAI 200 2023-06-15
M02 AMOXICILLIN KOLKATA 50 2022-03-21
M03 COUGH SYRUP BENGALURU 120 2023-02-10
M04 INSULIN CHENNAI 135 2023-01-25
M05 IBUPROFEN HMEDABAD 30 2022-04-05
132 | Page
Write SQL queries to-
(a) Display the Medicine names and the supplier cities of all
medicines
(b) Display the medicine names from Mumbai and Chennai cities.
(c) Display the medicine names delivered in 2022
(d) To remove the medicine ‘INSULIN’ from the table.
133 | Page
(A) Display the details of movies released after 2010.
(B) Display titles and the ratings of all the movies.
(C) Display the movie name and the year of release of movies having
ratings in the range of 7.1 to 8.9 (inclusive of both)
(D) Add a new column named 'Revenue' which will store the revenue
earned by that movie till date.
(E) Remove all movies released prior to 2005 from the table.
37 (A) 5
Write a program that will manage the inventory of a shop. The
program should create a dictionary consisting of five products
from user input in which the key is the product name and the
value is the quantity presently in stock. The user must input
the product name and the quantity separately, the program
must add it dynamically to the dictionary.
The program should then ask from the user a list containing
five numbers. The list of numbers are the quantities that are to
be reduced from the stock. The program should reduce the
quantities from the dictionary and then display the updated
dictionary OR
134 | Page
KENDRIYA VIDYALAYA SANGATHAN
UNSOLVED QUESTION PAPER - 02
CLASS XI - INFORMATICS PRACTICES (065)
Time allowed: 3 Hours Maximum Marks:70
135 | Page
11 Fill in the Blank 1
A candidate key that is not a primary key is called -------------------
(A) Super Key (B) Alternate Key
(C) Foreign Key (D) Secondary Key
12 In IoT , T stands for 1
(A) Technology (B) Traffic (C) Things (D) Technique
13 Identify the odd one from the following : 1
(A) Oracle (B) MySQL (C) MS Access (D) P y t h o n
14 Which among the following is an example for customized software 1
(A) Photoshop (B) MS Excel
(C) Windows (D) Hospital Management Software
15 Which one of the following attribute can be taken as a primary key? 1
(A) Name (B) Designation (C) EmpId (D) Department
16 Which one of these is not an area of AI? 1
(A) Face/Image Recognition (B) Voice Recognition
(C) Robotics (D) Web Designing
17 SELECT * statement displays all -------------------- of a table. 1
(A) Rows (B) Attributes (C) Tuples (D) Domain values
18 1
Identify the data type of T:
T = {1:’Anu’,2:’Bineesh’,3:’Chitra’}
(A) List (B) Tuple (C) Dictionary (D) String
19 Which of the following identifier names are invalid and why? 1
(A) Serialno1 (B) TotalMarks (C) _Percentage (D) True
Q-20 and Q-21 are Assertion (A) and Reason (R) Type questions. Choose the
correct option as:
(A) Both Assertion (A) and Reason (R) are true, and Reason (R) is the
correct explanation of Assertion (A)
(B) Both Assertion (A) and Reason (R) are true, but Reason (R) is not the
correct explanation of Assertion (A)
(C) Assertion (A) is True, but Reason (R) is False
(D) Assertion (A) is False, but Reason (R) is True
Reason (R): DDL commands are used to create, modify, or remove database
structures, such as tables.
136 | Page
Q No Section-B (7 x 2 = 14 Marks) Marks
22 (A) (i)Arrange the memory units in ascending order of storage size 2
MB, KB, TB, GB, Byte
(ii)List out any 2 Output Devices
OR
(B) Differentiate RAM and ROM (Mention any 2 points)
23 Consider the Table ‘‘Infant’’ shown below :
2
137 | Page
B) Predict the output:
List1=[13,18,11,16,13,18,13]
print([Link](13))
print([Link](18))
List1[2]=10
[Link](10)
[Link]([Link](10))
print(List1)
31 (i) Rewrite the following code in python after removing all the syntax
errors. Underline each correction done in the code.
num1, num2 = 10 5
if num1 % num2 = 0
num1+= 20
num2+= 30
Else: 2+1=3
print(Not Divisible )
(ii) Write SQL Query to insert the following data in the Items Table
101, Galaxy S30 Ultra, Samsung, Black, 85000, 10
(iii) Aman has created a table “Inventory” and forgot to add a
column “GST” of data type integer. Write SQL command to add
the column in the table.
(iv) Smita is working on SQL query , but she is getting error in her
query. Help her in removing error and writing correct query
select * from Product where price=NULL;
138 | Page
34 Write the output of the queries (i) to (iv) based on the table given below: 4
I. Select BRAND_NAME, FLAVOUR from CHIPS where PRICE < > 10;
II. Select * from CHIPS where FLAVOUR=”TOMATO” and PRICE > 20;
III. Select BRAND_NAME from CHIPS where price > 15 and QUANTITY <
15;
IV. Select price , price *1.5 from CHIPS where FLAVOUR = “PUDINA”;
Q No Section-E (3 x 5 = 15 Marks) Marks
35 Write python code to create a dictionary of Products with product name 5
as key and price as value .Product name and price must be accepted from
the user .
The program should then search for particular product by inputting product
name and display price of the same on the screen
For Example the expected output in the following format.
Product = {‘Pen’ : 20, ‘Book’: 50 , ‘Pencil’ : 10 }
Enter the Product Name : Book
Product Details Found : ‘Book’: 50
OR
Consider the given dictionary,
D={1:’monday’, 2:’Tuesday’, 3:’Wednesday’,4:’Thursday’}
(i) What will be the output of following code:
print([Link]())
(ii) What will be the output of D[2]
(iii) Write python code to add a new value ‘Friday ‘with key 5.
(iv) Write python code to remove the value ‘Wednesday’ from the
dictionary.
(v) Which among the following statements will the number of key
value pairs in D ?
(A) [Link]() (B) count(D) (C) len(D) (D) [Link]()
36 Mr. Manav, a database administrator in “Global Educational and Training 5
Institute” has created following table named “Training” for the upcoming
training schedule:
Table : Training:
Training_Id TName Topic City Fee
140 | Page
KENDRIYA VIDYALAYA SANGATHAN
UNSOLVED QUESTION PAPER - 03
CLASS XI - INFORMATICS PRACTICES (065)
a) list(range(-2,-8,-2))
b) list(range(0,-8,-2))
c) list(range(-2,-10,-2))
d) list(range(0,-10,-2))
141 | Page
13 Comments are executed by interpreter. State True or False 1
14 A company interested in cloud computing is looking for a provider who offers 1
a set of basic services such as virtual server provisioning and on-demand
storage that can be combined into a platform for deploying and running
customized applications. What type of cloud computing model fits these
requirements?
a) Platform as a Service
b) Software as a Service
c) Infrastructure as a Service
15 The COUNT(*) function provides the total number of __________ within a 1
relation (table) in a relational database.
(A) Columns (B) Unique values (C)Not-null values (D)Rows
16 Identify the SQL command used to delete a relation (table) from a relational 1
database.
(A) DROP TABLE (B) REMOVE TABLE
(C) DELETE TABLE (D)ERASE TABLE
17 Which is not one of the features of IoT devices? 1
a) Remotely controllable b) Programmable
c) Can turn themselves off if necessary d) None of the above
18 From the below python code, what should come in print command as index 1
value so that first element of array and 35 value is displayed from the array
import numpy as np
Array=[Link]([3,6,9,12,15,18,36,35,38])
print(Array[ ],Array[ ])
(a) [1],[7] (b) [1],[8] (c) [0],[8] (d)[0],[7]
19 “Imagine what if our bulbs, fans and refrigerator also become a part of LAN or 1
Internet. Think about of the advantages and tasks that can be accomplished if
all these devices with smart connectivity features are able to communicate
amongst themselves and we are also able to communicate with them using
computers or smart phones.”
In your opinion, which feature are we talking about in the above context?
(i) AR (ii) VR (iii) WoT (iv) IoT
(A) Both A and R are true and R is the correct explanation for A
(B) Both A and R are true and R is not the correct explanation for A
(C) A is True but R is False
(D) A is false but R is True
142 | Page
SECTION B (7 x 2 = 14 Marks)
22 Deleting digitally stored data means changing the details of data at bit level, 2
which can be very time consuming. Therefore, when any data is simply
deleted, its address entry is marked as free, and that much space is shown
as empty to the user, without actually deleting the data.
In case data gets deleted accidentally or corrupted, there arises a need to
recover the data. Recovery of the data is possible only if the
contents/memory space marked as deleted have not been overwritten by
some other data.
i) Can you recover the data once deleted? Justify
ii) Give any one security threat involved when we throw away
electronic gadgets that are non-functional.
Or
Write down the type of memory needed to do the following:
i) To execute the program
ii) To store the instructions which cannot be overwritten
23 How to create an Array of list in python using NumPy? Explain with 2
suitable example.
24 What are DDL and DML? Give one command of each. 2
143 | Page
SECTION C(4 x 3 = 12 Marks)
29 Write the most appropriate list functions to perform the following: 3
i) To delete a value from the list
30 (i) Himank has written the following statement in Python, but it 1+2
is showing an error: =3
X = 0o81
According to you what could be the problem?
(ii) “Our heritage monuments are our assets. They are a reflection
of our rich and glorious past and an inspiration for our future.
UNESCO has identified some of Indian Heritage sites as World
Heritage Sites.”
Identify at least two parameters from the above text that can be used as key
value pair to set up a dictionary. Form a dictionary to create at least 5
records of World Heritage Sites.
31 (i) Write an SQL statement to create a table named STUDENTS, with the 3
following specifications:
Column Name Data Type
StudentID Numeric
FirstName Varchar(20)
LastName Varchar(20)
DateOfBirth Date
Percentage Float(10,2)
ii. (ii) Write SQL Query to insert the following data in the Students Table
1, Supriya, Singh, 2010-08-18, 75.5
32 Consider the table “Accessories” given below and write suitable output of 3
the following:
144 | Page
(i) SELECT DISTINCT NAME FROM ACCESSORIES WHERE PRICE>5000;
(ii) SELECT AVG(PRICE), MAX(PRICE) FROM ACCESSORIES WHERE
PRICE>=10000;
(iii) SELECT NAME, PRICE*.05 DISCOUNT FROM ACCESSORIES WHERE ID IN
(„S02‟,‟S03‟)
SECTION D (2X4=8 Marks)
33 i) What will be the output of following code: 1+1
dict1 = {“Rollno”:20, “Marks”:65} +2
dict2 = {“Rollno”:20, “Marks”:65} =4
print(dict1 == dict2)
ii) Name different types of comments in Python.
iii) Predict the output of the following:
quota = [“sports”, “ pwd”, “ews”, “gen”]
Marks= [58,70,45,69]
for k in range(len(quota)):
if quota[k]==”sports”:
Marks[k]+=2
if quota[k]==”ews”:
Marks[k]+=5
34 i) Suppose there is a computer with RAM but no secondary storage. Why 1+1
we are not able to install software on that computer? +2=
ii) Why cache memory is considered crucial for microprocessor 4
performance?
iii) Suman has discarded old, broken and malfunctioning Hard Disk
without taking care to delete data. Is it harmful in respect of security
concern? Justify your answer.
SECTION E (3 X 5=15 Marks)
35 Consider the table ‘Transact’ given below and write suitable SQL queries 5
of the following:
TABLE: TRANSACT
TRNO ANO AMOUNT TYPE DOT
T001 101 2500 Withdraw 2017-12-21
T002 103 3000 Deposit 2016-06-01
145 | Page
T003 102 2000 Withdraw 2017-05-12
T004 103 1000 Deposit 2018-10-22
T005 102 12000 Deposit 2017-11-06
(i) To display details of all transactions of TYPE Withdraw from
TRANSACT table
(ii) To display the date of transaction (DOT)along with the
amount from table TRANSACT for Account having ANO as
102
(iii) To display the column values of ANO without repetition.
(iv) To increase the amount by 500 for all transactions of deposit
type in the TRANSACT table.
(v) To delete the row of the transaction with TRNO T004.
36 Consider the table ‘Teacher_Details’ given below and write suitable SQL 5
queries of the following:
Table: Teacher_Details
T_ID T_Name T_DOJ T_Subject Num_of_Periods
1001 Bharti 2018-10-15 Hindi 27
1002 Pratima NULL NULL 32
1003 Savitri 2012-11-13 Science 29
1004 Aashna 2020-02-24 English 28
i) Display the T_Name and Num_of_Periods by increasing
the number of periods each by 1.
ii) Display T_Name of all those teachers whose date of joining
is after 1st Jan 2019.
iii) Display T_ID and T_Name of all those teachers whose number
of periods are in the range of 25 to 30. (both values included)
iv) Display the details of all those teachers who have not assigned
any subject.
v) Display the details of all those teachers whose subject is either
Hindi or Science.
37 a) A data analyst wants to preprocess a list of numbers by replacing all 3+2
positive numbers with 1 and negative numbers with -1. The analyst needs a =5
Python program to accept the list from the user, modify it, and display the
result.
Requirements:
1. Accept a list of numbers from the user.
2. Replace all positive numbers with 1 and negative numbers with -1.
3. Display the modified list.
Solution:
Write a Python program that meets the requirements above.
147 | Page
Web links:
1. Syllabus for Higher Secondary Stage prescribed by NCERT:
[Link]
148 | Page