Study Material IP-XI 2024-25

Download as pdf or txt
Download as pdf or txt
You are on page 1of 103

1

संदेश

विद्यालयी शिक्षा में िैक्षक्षक उत्कृष्टता प्राप्त करना केन्द्रीय विद्यालय


संगठन की सिोच्च िरीयता है । हमारे विद्यार्थी, शिक्षक एिं िैक्षक्षक
नेतत्ृ ि कताा ननरं तर उन्द्ननत हे तु प्रयासरत रहते हैं। राष्रीय शिक्षा
नीनत 2020 के संदर्ा में योग्यता आधाररत अधधगम एिं मूलयांकन
संबन्न्द्धत उद्दे श्यों को प्राप्त करना तर्था सीबीएसई के ददिा ननदे िों का
पालन, ितामान में इस प्रयास को और र्ी चन
ु ौतीपर्
ू ा बनाता है ।
केन्द्रीय विद्यालय संगठन के पांचों आंचलिक लशक्षा एवं प्रलशक्षण
संस्थान द्िारा संकशलत यह‘ विद्यार्थी सहायक सामाग्री ’इसी ददिा में
एक आिश्यक कदम है । यह सहायक सामग्री कक्षा 9 से 12 के
विद्याधर्थायों के शलए सर्ी महत्िपूर्ा विषयों पर तैयार की गयी है ।
केन्द्रीय विद्यालय संगठन की‘ विद्यार्थी सहायक
सामग्री ’अपनी गुर्ित्ता एिं परीक्षा संबंधी सामाग्री-संकलन की
वििेषज्ञता के शलए जानी जाती है और अन्द्य शिक्षर् संस्र्थान र्ी
इसका उपयोग परीक्षा संबंधी पठन सामग्री की तरह करते रहे हैं ।
िुर्-आिा एिं विश्िास है कक यह सहायक सामग्री विद्याधर्थायों की
सहयोगी बनकर सतत मागादिान करते हुए उन्द्हें सफलता के लक्ष्य
तक पहुंचाएगी ।
िुर्ाकांक्षा सदहत ।

ननधि पांडे
आयुक्त, केन्द्रीय ववद्यािय संगठन

2
STUDY MATERIAL

PREPARED BY
JAMMU REGION
Mrs.Swati Bansal(Principal)
PM SHRI KV NO.1 UDHAMPUR

VETTED BY
KVS ZIET CHANDIGARH
Mrs. Anu Rani(PGT CS)
PM SHRI KV OCF CHANDIGARH

3
INDEX OF CONTENTS

S.No. Topic Page No.


Introduction to Computer System:
• Introduction to computer and computing evolution of computing
devices, components of a Computer System and their inter
connections, Input Output devices.
1 • Computer Memory: Units of memory, types of memory primary 8-14
and secondary data deletion, its recovery and related security
concerns.
• Software: purpose and types system and application software,
generic and specific purpose software.
Introduction to Python:
• Basics of Python programming. Python interpreter-interactive and
script mode, the structure of a program.
• Indentation, identifiers. Keywords. Constants, variables types of
operators precedence of operators, data
2 15-25
• Types, mutable and immutable data types,
statements, expressions, evaluation and comments, input and output
statements
• Data type conversion, debugging.
• Control Statements: if-else if-elif-else, while loop, for loop
Introduction to Python Continue:
• Lists: list operations-creating, initializing, traversing and
manipulating lists, list methods and built-in functions-len()
Jist().append().insert(),count(), index(),remove(), pop(), reverse(),
3 sort(), min(),max(),sum() 26-45
• Dictionary: concept of key-value pair, creating, initializing,
traversing, updating and deleting element, dictionary methods and
built-in functions-dict(), len(), keys(), values(), items(), update(),
del(), clear()
Database Concepts:
• Database Concepts: Introduction to database concepts and its need,
4 Database Management System. 46-50
• Relational data model: Concept of domain, tuple, relation, candidate
key, primary key, alternate key
Structured Query Language:
• Advantages of using SQL, DDL, DQL & DML
• Introduction to MySQL, DDL commands & creating database 51-70
5
• Data Query: SELECT, FROM, WHERE with relational operators,
BETWEEN, logical operators, IS NULL, IS NOT NULL
• Data Manipulation: INSERT, DELETE UPDATE
Introduction to Emerging Trends:
• Artificial Intelligence, Machine Learning, Natural Language
Processing Immersive experience (AR, VR), Robotics, Big data and 71-83
6
its characteristics, Internet of Things (IoT), Sensors, Smart cities,
Cloud Computing and Cloud Services (SaaS, laaS, PaaS), Grid
Computing, Block chain technology
7 Solved Papers 84-91
8. Unsolved papers 92-103

4
Informatics Practices (2024-25) CLASS XI Code No. 065
Unit Wise syllabus-
Unit 1: Introduction to Computer System
• Introduction to computer and computing: evolution of computing devices, components of acomputer
system and their interconnections, Input/output devices.
• Computer Memory: Units of memory, types of memory – primary and secondary, datadeletion, its
recovery and related security concerns.
• Software: purpose and types – system and application software, generic and specific purpose
software.

Unit 2: Introduction to Python


• Basics of Python programming, execution modes: - interactive and script mode, the structure of a
program, indentation, identifiers, keywords, constants, variables, types of operator, precedence of
operators, data types, mutable and immutable data types, statements, expression evaluation.
comments, input and output statements, data type conversion, debugging.
• Control Statements: if-else, if-elif-else, while loop, for loop
• Lists: list operations - creating, initializing, traversing and manipulating lists, list methods and built-in
functions – len(),list(),append(),insert(), count(),index(),remove(), pop(), reverse(), sort(),
min(),max(),sum()
• Dictionary: concept of key-value pair, creating, initializing, traversing, updating and deletingelements,
dictionary methods and built-in functions – dict(), len(), keys(), values(), items(),update(), del, clear()

Unit 3: Database concepts and the Structured Query Language


• Database Concepts: Introduction to database concepts and its need, Database Management System.
• 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, logicaloperators, 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.

5
Practical Marks Distribution

S.No. Unit Name Marks


1 Problem solving using Python programming language 11
2 Creating database using MySQL and performing Queries 7

Practical file (minimum of 14 python programs, and 14 SQL


3 7
queries)
4 Viva-Voce 5
Total 30
Suggested Practical List
• 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 a 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.
• Data Management: SQL Commands
18. To create a database
19. To create student table with the student id, class, section, gender, name, dob, andmarks
as attributes where the student id is the primary key.
20. To insert the details of at least 10 students in the above table.
21. To display the entire content of table.
22. To display Rno, Name and Marks of those students who are scoring marks morethan
50.
23. To display Rno, Name, DOB of those students who are born between ‘2005- 01-01’and
‘2005-12-31’.

6
Suggested material
NCERT Informatics Practices - Text book for class - XI (ISBN- 978-93-5292-148-5)

Distribution of Marks and Periods


Unit Unit Name Marks Periods Periods Total
No Theory Practical Period
1 Introduction to computer system 10 10 - 10
2 Introduction to Python 25 35 28 63
3 Database concepts and the 30 23 17 40
Structured Query Language
4 Introduction to Emerging 5 7 - 7
Trends
Practical 30 - - -
Total 100 75 45 120

7
Introduction to Computer System

• Introduction to computer and computing: evolution of computing devices, components of a


Computer System and their inter connections, Input/output devices.

• Computer Memory: Units of memory, types of memory–primary and secondary, data deletion, its
recovery and related security concerns.

• Software: purpose and types – system and application software, generic and specific purpose
software
Computer: An electronic device that takes the input and processes it to provide desired output. Computer
System is consisting of hardware and software that works together to provide the expected computer
experience.
Computer Hardware
Computer hardware refers to the physical components of a computer system, including the central
processing unit (CPU), memory, storage devices, input devices (keyboard, mouse), output devices (monitor,
printer), and other peripherals. It encompasses the tangible, electro-mechanical, and electronic elements that
constitute a computer and enable its functioning.

Integrated Circuit: An Integrated Circuit (IC) is a compact assembly of interconnected electronic


components, such as transistors, resistors, and capacitors, fabricated on a semiconductor substrate. This
miniaturized arrangement enables the creation of complex electronic circuits, forming the basis of modern
microprocessors, memory chips, and various electronic devices.

1. Central Processing Unit: The Central Processing Unit (CPU) is the primary component of a computer
responsible for executing instructions from programs. Acting as the "brain" of the system, it performs
arithmetic and logic operations, manages data, and coordinates the functioning of other hardware
components, crucial for overall computing functionality and speed. It consists of Arithmetic Logic Unit,
Control Unit & Registers
1.1.Arithmetic Logic Unit: The Arithmetic Logic Unit (ALU) is a fundamental component of a
computer's central processing unit (CPU) responsible for performing arithmetic and logical
operations on binary data. It executes tasks like addition, subtraction, AND, OR, and other
operations, crucial for processing and manipulating information within the computer system.

1.2.Control Unit: The Control Unit manages and coordinates the execution of instructions. It decodes
program instructions, directs data flow within the CPU and between other system components, and
controls the overall operation of the processor to execute tasks in a programmed sequence.

1.3.Registers: These are fast running memory blocks used by ALU for storing intermediate results. They
temporarily hold data and instructions that the CPU is actively processing.

2. Input Devices: Computer input devices are hardware components that allow users to provide data and
commands to a computer system. Examples include keyboards for typing, mice for pointing and
clicking, and scanners for converting physical documents into digital form. These devices enable users
to interact with and input information into the computer.
8
3. Output Devices: Computer output devices are hardware components that present or display processed
information from a computer to the user. Examples include monitors for visual output, printers for
producing hard copies of documents, and speakers for audio output. These devices convey the results of
computations and operations performed by the computer.

4. Memory: Computer memory refers to the electronic components that store data and instructions
temporarily or permanently for processing by a computer.
Units: bit is the smallest unit
Nibble- 4 bits Byte- 8 bits
KB-1024 Bytes PB- 1024 GB
MB- 1024 KB EB- 1024 PB
GB- 1024 MB ZB- 1024 EB
TB- 1024 GB YB- 1024 ZB

4.1.Primary Memory: Primary memory, also known as main memory, is of two types-RAM, ROM and
cache.

RAM ROM
Random Access Memory Read Only Memory
It is volatile in nature. It is non-volatile.
Also called the temporary memory It is also known as permanent memory
It is used to execute the programs and hold It has prewritten instructions used at the time
its data. of system startup.

4.2.Secondary Memory: Secondary memory refers to non-volatile storage devices in a computer system,
such as hard drives, solid-state drives, and external storage. Unlike primary memory, it retains data
even when the power is off. Secondary memory is used for long-term storage of files, applications,
and the operating system.

4.3.Cache Memory: Cache Memory is a high-speed volatile computer memory located between the
central processing unit (CPU) and main memory. It stores frequently accessed data and instructions
to expedite retrieval, enhancing overall system performance by reducing the time it takes for the CPU
to access frequently used information during program execution.

Evolution of Computer
1. Abacus (500 BC): Computing is attributed to the invention of ABACUS almost 3000 years ago. It
was a mechanical device capable of doing simple arithmetic calculations only.

2. Pascaline (1642): Blaize Pascal invented a mechanical calculator known as Pascal calculator or
Pascaline to do addition and subtraction of two numbers directly and multiplication and division
through repeated addition or subtraction.

3. Analytical Engine (1834): Charles Babbage invented analytical engine, a mechanical computing
device for inputting, processing, storing and displaying the output, which is considered to form the
basis of modern computers.

4. Tabulating Machine (1890): Herman Hollerith designed a tabulating machine for summarising the
data stored on the punched card. It is considered to be the first step towards programming.
9
5. Turing Machine (1937): The Turing machine concept was a general purpose programmable
machine that was capable to solve any problem by executing the program stored on the punched
cards.

6. ENIAC (1945): Electronic Numerical Integrator And Computer. John Von Neumann introduced the
concept of stored program computer which was capable of storing data as well as program in the
memory. The EDVAC and then the ENIAC computers were developed based on this concept.

7. Transistor (1947): Vacuum tubes were replaced by transistors developed at Bell Labs, using
semiconductor materials.

8. Integrated Circuit (1970): An Integrated Circuit (IC) is a silicon chip which contains entire
electronic circuit on a very small area. The size of computer has drastically reduced because of ICs.

9. Very Large Scale Integration (VLSI) (1980): the processing power of computers increased
exponentially by integrating around 3 million components on a small-sized chip

10. Super Large Scale Integration (SLSI): fabricate high density of transistors and other components
(approx. 106 components) on a single IC

Data Capturing, Storage, and Retrieval


Data Capturing: It involves the process of gathering data from different sources in digital form. Data may
be captured using, keyboard bar code readers.

Data Storage: It is the process of storing the captured data for processing later.

Data Retrieval: It involves fetching data from the storage devices, for its processing as per the user
requirement.

Data Deletion: It is the simple process of deleting a file and placing it into the Recycle Bin or Trash.
Data recovery: It is a process of retrieving deleted, inaccessible, lost, corrupted, damaged, or formatted data
from secondary storage/ removable media.

Data security: It is the process of protecting corporate data and preventing data loss through unauthorized
access.
Software
1. System Software-It is a program designed to run a computer's hardware and applications and manage
its resources, such as its memory, processors, and devices.

1.1.Operating System: The operating system manages other application programs and provides access
and security to the users of the system. Some of the popular operating systems are Windows, Linux,
Macintosh, Ubuntu, Fedora, Android, iOS, etc.
1.2.System Utilities: Used for maintenance and configuration of the computer system, for example disk
defragmentation tool, formatting utility, system restore utility, etc. Another set of utilities are those
which are not shipped with the operating system but are required to improve the performance of the
system, for example, anti-virus software, disk cleaner tool, disk compression software, etc.
1.3.Device Drivers: The purpose of a device driver is to ensure proper functioning of a particular device.

2. Application Software: It is a type of computer program that performs a specific personal, educational,
and business function.

10
2.1.Generic software- Generic software is off-the-shelf software available for use.

It is designed to be used widely by people across different industries, Generic software is a system
designed for general public usage.
Some examples of generic software are:
Word processor – e.g. Word, WordPerfect
Spread sheet – e.g. Excel, Lotus 1-2-3
Database applications – e.g. Access, Approach
Presentation – e.g. PowerPoint, Impress
Electronic Mail & Diary – e.g. Outlook, Notes
Generic software is a system designed for general public usage.

2.2.Specific software-It is software that is created for a specific purpose, organization, or individual.

TIME TO PRACTICE
Objective Question (1 Mark)
1. A computer is a/an ............ device.
a) Mechanical, b) Electrical, c) Electronic, d) Telecommunication
2. The physical components of the computer are known as
a) Software, b) Program, c) Hardware, d) Both a) and c)
3. Which of the following is not related to a personal computer:
a) Processor, b) On-board, c) Motherboard, d) Keyboard
4. Which of the following is not a type of computer:
a) Smart Phone, b) Smart Watch, c) Biometric Attendance machine, d) Tablet PC
5. Which type of PC is available in your school computer laboratory?
a) IBM PC, b) MacBook, c) Chrome Book, d) Tablet PC
6. Full form of ALU is:
a) Abacus Logarithmic Unit, b) Arithmetic Logic Unit, c) Abacus Language Unit, d)
Arithmetic Language Unit
7. Which of the following is a part of ALU?
a) Arithmetic Unit, b) Control Unit, c) Logic Unit, d) Both a) and c)
8. First binary programmable computer based on Von Neumann architecture is:
a) UNIVAC, b) EDVAC, c) ENIAC, d) Mark I
9. Arrange the following in increasing order of no of transistors on a single chip: i) SLSI
ii) IC iii) VLSI iv) LSI
a) i) SLSI ii) IC iii) VLSI iv) LSI,
b) ii) IC iii) VLSI iv) LSI i) SLSI,
c) ii) IC iv) LSI iii) VLSI i) SLSI,
d) iii) VLSI iv) LSI i) SLSI ii) IC.
10. Which of the following is the fastest memory?
a) RAM, b) Cache, c) ROM, d) Hard Disk
11. Binary number system comprises of the digits:
a) 1, 2 b) 0, 1 c) a, b d) i, ii
12. ______ is volatile memory i.e. as long as the power is supplied to the computer, it
retains the data in it
a) RAM, b) CD, c) ROM, d) Hard Disk
13. 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 i) KB iii) MB,
b) ii) GB iv) TB i) KB iii) MB,

11
c) iv) TB iii) MB i) KB ii) GB,
d) iv) TB ii) GB iii) MB i) KB.
14. Which of the following is not an input device?
a) Scanner, b) Speakers, c) Webcam, d) Joystick.
15. ______ is an electronic pathway composed of cables which connects the major parts of
a computer system
a) Motherboard, b) Processor, c) Bus, d) Cache.
16. Which of the following cannot be the reason for data deletion from HDD?
a) Data lost due to shutting down the PC. b) Hacker attacking the system.
c) Bad sector in Hard Disk. d) Accidentally deleting a file.
17. Which of the following is not a data recovery software?
a) Recuva, b) EaseUS, c) Disk Drill, d) Matlab.
18. In which of the scenario do we need to recover data?
a) When disk is full. b) When system performance has become slow.
c) When a photo or video has been accidentally deleted. d) All of the above.
19. Which of the following is an example of Proprietary software?
a) Linux, b) Windows, c) Mozilla Firefox, d) None of the above.
20. Operating System is an example of
a) System software, b) Utility program, c) Application software, d) None of the above.

Very Short Answer (1 Mark)

1. Write the full forms of USB.


2. What is BIOS?
3. Which type of main memory is volatile?
4. Give example of one utility software?
5. What is VLSI?
6. Which machine is considered similar to current computer?
7. Printer is _______________ device.
8. What is FLOSS?
9. Name any one mobile operating system and computer operating system.
10. _____________ introduced the concept of stored program computer which was
capable of storing data as well as program in the memory.

Short Answer (2 Mark)


1. How is OSS different from FOSS?
2. Give three techniques to prevent accidental file deletion.
3. Draw the block diagram of a computer system. Briefly write about the functionality
of each component.
4. List out four differences between RAM and Hard Disk.
5. Give two reasons for data deletion. How can data deletion from unauthorized persons
be prevented?
6. Give two differences between a compiler and interpreter.
7. What is language translator?
8. What are the major components of Modern computers based on Von Neumann
Architecture?
9. What is the difference between RAM and ROM?
10. What do you mean by customised software?

Long answer (3 Mark)


1. Draw the block diagram of computer system and explain each part briefly.
12
2. What is the hardware? What type of software is required to run the hardware devices?
Give one example.
3. Name the memory that is fastest in a computer system? What is the role of such
memory and where is it placed?
4. Differentiate between free and open source software and proprietary software with one
example of each.
5. What is the purpose of using secondary memory? Give some example of secondary
memory device. What is the storage capacity of a CD?

Open ended question (Assertion and Reasoning) 1 Mark


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: It is always good to keep the passwords encrypted while storing.
Reason: 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: Software designed for a school will work only for the school admin.
Reason: Customized software is tailor made software according to user requirements.

Case study and competency-based questions (5 Mark)


1. Mukta purchased a laptop one year back. Now she installed a latest operating system
after which the speed of the laptop has become quite slow. Suggest her the way out to
increase the speed of the laptop by upgrading one of the following devices. Also tell
her about these devices one by one.
a) Hard Disk
b) ROM
c) RAM
d) Processor
e) Network
2. In today scenario, overuse of computer is having some positive or negative impact in
our life. Give your view for following list, if computer is having a positive or negative
impact.
a) Accuracy
b) Speed
c) Health
d) Employment
e) Social Relations
3. While preparing a presentation Anil forgot to save it and power is cut off.
a) Do you think she will get back the entire text she had typed in the letter?
b) If not what is the reason?
c) What would you suggest her to not face the problem again?
d) Can you suggest any device to prevent the above problem?
e) Which is better a writeable DVD or an external hard disk for long term storage?

13
4. Mukesh is a student of fine arts and wants to draw a portrait which he has to send
someone by email.
a) Do you think he should draw it on canvas and scan the image or can he draw it
on a PC? Which one is better if he knows how to draw on a PC?
b) Can a touchscreen make his work easier?
c) If he cannot afford a touchscreen, suggest him a suitable input device for
drawing the portrait.
d) He manages to draw a portrait but is unable to determine what type of printer
should be used. Suggest him a suitable printer along with the reason.
5. Do you think a separate graphics card is essential for drawing in a PC, if yes why it is
required and if not why and when it will be required?
6. Mrs Sunita wants to buy a laptop for her personal work. She is a teacher in Indira
Public School. She has searched on the Internet and she found two laptops with the
same configuration. One with DOS version and another with pre-loaded Windows.
1. Why is the price of the pre-loaded Windows system more than the DOS version?
a) DOS version is not user friendly.
b) DOS version does not support installing other software.
c) In pre-loaded Windows system an OS is already installed and it’s cost is
included.
d) None of the above.
2. Which software she needs to install in the DOS version?
a) Utility software
b) Application software
c) Operating system
d) None of the above.
3. She wants to install software for spreadsheet work. Suggest a suitable software for
her.
a) MS Excel
b) MS Word
c) MS Power Point
d) All the above
4. Which software among the following should she update or install to protect her
system from virus?
a) Windows Media Player
b) Windows Defender
c) MS Office
d) None of the above
5. She wants to use the internet for surfing content. Which among the following would
be the most suitable software for it?
a) Internet Explorer
b) Mozilla Firefox
c) Google Chrome
d) All the above

14
Introduction to Python

• Basics of Python programming. Python interpreter-interactive and script mode, the structure
of a program.
• Indentation, identifiers. Keywords. Constants, variables types of operators precedence of
operators, data
• Types, mutable and immutable data types,
• statements, expressions, evaluation and comments, input and output statements
• Data type conversion, debugging.
• Control Statements: if-else if-elif-else, while loop, for loop

What is Python?

• High-level programming language


• Easy to read and write
• Interpreted language (code runs directly, no need to compile)

Key Features

• Simple syntax similar to English


• Dynamic typing (no need to declare variable types)
• Supports multiple programming paradigms (procedural, object-oriented, functional)
• Extensive standard library and third-party modules
• Large community and support

Installing Python

1. Download from the official website (python.org)


2. Follow the installation instructions for your operating system

Running Python Code (Interactive and Script mode)

1. Interactive mode: Type python in your terminal/command prompt


2. Script mode: Write code in a file with a .py extension and run it using python filename.py

The structure of a Python program

A simple python program to add two numbers

15
Indentation

❖ Indentation refers to adding white spaces before lines of code in a python program.
❖ Indentation in Python is used to create a group of statements that are executed as a block.
Example:

Identifiers
• Names given to various program elements such as variables, functions, classes, etc.
• Rules:
o Must start with a letter (a-z, A-Z) or an underscore (_)
o Followed by letters, digits (0-9), or underscores
o Case-sensitive (e.g. var and Var are different)
o Cannot be a reserved keyword

Keywords

• Reserved words with special meaning in Python


• Cannot be used as identifiers
• Examples: False, class, finally, is, return, None, continue, for, lambda, try, etc.

Constants

• Fixed values that do not change during program execution


• Examples: numbers (5, 3.14), strings ("Hello", 'World')
• In Python, constants are usually defined in all uppercase letters as a convention (e.g., PI = 3.14)

Variables

• Named storage locations in memory used to store data


• Created by assigning a value using the assignment operator (=)
• Examples: x = 5, name = "Alice"
• Variable names should be descriptive and follow identifier rules

Types of Operators

• Arithmetic Operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulus), **


(exponentiation), // (floor division)
• Comparison (Relational) Operators: == (equal to), != (not equal to), > (greater than), < (less than),
>= (greater than or equal to), <= (less than or equal to)
• Assignment Operators: = (assignment), += (add and assign), -= (subtract and assign), *= (multiply
and assign), /= (divide and assign), %= (modulus and assign), **= (exponent and assign), //= (floor
division and assign)
• Logical Operators: and, or, not
• Bitwise Operators: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift)
• Membership Operators: in, not in
• Identity Operators: is, is not
16
Precedence of Operators

• Determines the order in which operators are evaluated in an expression


• Operators with higher precedence are evaluated before those with lower precedence
• Precedence order (from highest to lowest):

1. ** (exponentiation)
2. ~ (bitwise NOT), + (unary plus), - (unary minus)
3. *, /, //, % (multiplication, division, floor division, modulus)
4. +, - (addition, subtraction)
5. >>, << (right shift, left shift)
6. & (bitwise AND)
7. ^ (bitwise XOR)
8. | (bitwise OR)
9. ==, !=, >, >=, <, <= (comparison operators)
10. =, +=, -=, *=, /=, %=, **=, //=, &=, |=, ^=, >>=, <<= (assignment operators)
11. not (logical NOT)
12. and (logical AND)
13. or (logical OR)
• Parentheses () can be used to override precedence and force a specific order of evaluation.

Data Types

• Numeric Types
o int: Integer values (e.g., 1, 42, -7)
o float: Floating-point (decimal) values (e.g., 3.14, -0.001)
o complex: Complex numbers (e.g., 2 + 3j)
• Sequence Types
o str: String of characters (e.g., "hello", 'world')
o list: Ordered, mutable collection (e.g., [1, 2, 3], ['a', 'b', 'c'])
o tuple: Ordered, immutable collection (e.g., (1, 2, 3), ('a', 'b', 'c'))
o range: Sequence of numbers (e.g., range(10), range(1, 5))
• Mapping Type
o dict: Key-value pairs (e.g., {'name': 'Alice', 'age': 25})
• Set Types
o set: Unordered collection of unique elements (e.g., {1, 2, 3}, {'a', 'b', 'c'})
• Boolean Type
o bool: Boolean values True or False
• None Type
o None: Represents the absence of a value (e.g., None)

Mutable and Immutable Data Types

• Mutable Data Types


o Can be changed after creation (e.g., modifying elements, adding or removing elements)
o Examples:
▪ list: my_list = [1, 2, 3] (can add, remove, or change elements)
▪ dict: my_dict = {'key': 'value'} (can add, remove, or change key-value pairs)
▪ set: my_set = {1, 2, 3} (can add or remove elements)
• Immutable Data Types
o Cannot be changed after creation (any modification creates a new object)
o Examples:
▪ int: my_int = 5 (cannot change the value directly)
17
▪ float: my_float = 3.14 (cannot change the value directly)
▪ str: my_str = "hello" (cannot change characters directly)
▪ tuple: my_tuple = (1, 2, 3) (cannot change elements)

Statements

• Instructions executed by the Python interpreter.


• Types of statements:
o Expression statements: Evaluate an expression (e.g., a + b).
o Assignment statements: Assign values to variables (e.g., x = 5).
o Control flow statements: Direct the flow of execution (e.g., if, for, while, break, continue).
o Function definition: Define a function (e.g., def my_function():).

Expressions

• Combinations of variables, operators, and values that yield a result.


• Examples:
o Arithmetic expressions: 2 + 3.
o Logical expressions: a and b.
o String expressions: "Hello" + " " + "World".
• Can be part of a larger statement.

Evaluation

• The process of computing the result of an expression.


• Python evaluates expressions using the rules of precedence and associativity.

Comments

• Used to annotate code and make it more understandable.


• Single-line comments: Begin with # (e.g., # This is a comment).
• Multi-line comments: Enclosed in triple quotes (e.g., '''This is a multi-line comment''').

Input and Output Statements


• Input:
o input(): Reads a line of text input from the user (e.g., name = input("Enter your name: ")).
o Always returns a string.
• Output:
o print(): Outputs text or variables 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 to customize the output (e.g., print("Hello", "World",
sep="-")).

Data Type Conversion


• Converting one data type to another.
• Common functions:
o int(): Converts a value to an integer (e.g., int("42")).
o float(): Converts a value to a float (e.g., float("3.14")).
o str(): Converts a value to a string (e.g., str(42)).
o list(): Converts a value to a list (e.g., list("abc") results in ['a', 'b', 'c']).
o tuple(): Converts a value to a tuple (e.g., tuple([1, 2, 3])).
o set(): Converts a value to a set (e.g., set([1, 2, 2, 3])).

18
o dict(): Converts a value to a dictionary (when applicable, e.g., dict([('a', 1), ('b', 2)])).

Debugging in Python
• Definition:
o The process of finding and fixing errors or bugs in your 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"), print("Value of x:", x)).
o Using Assertions: assert statement to check if a condition is True, and if not, it raises an
AssertionError (e.g., assert x > 0, "x must be positive").

Control Statements in Python


• 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.
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:

• While Loop:
o Repeats a block of code as long as a condition is true.
o Example:

o Can use break to exit the loop prematurely.


o Can use continue to skip to the next iteration.

For Loop

• For Loop:
19
o Iterates over a sequence (e.g., list, tuple, string) or range of numbers.
o Syntax:
o Example:

• For Loop with Break and Continue:


o break: Exit the loop prematurely.
o continue: Skip to the next iteration.
o Example:

TIME TO PRACTICE

MULTIPLE CHOICE QUESTIONS

1. Which of the following is a valid identifier in Python?


A. 2variable
B. variable2
C. variable-2
D. variable 2

2. Which of the following is NOT a keyword in Python?


A. class
B. try
C. value
D. finally

3. What is the result of the expression 4 + 3 * 2 in Python?


A. 10
B. 14
C. 20
D. 16

4. Which data type is mutable in Python?


A. int
B. float
20
C. tuple
D. list

5. What will be the output of the following code? print(2 ** 3 ** 2)


A. 64
B. 512
C. 256
D. 128

6. Which function is used to read input from the user in Python?


A. scanf()
B. input()
C. get()
D. read()

7.What will be the output of the following code? print (type(5.0))


A. <class 'int'>
B. <class 'float'>
C. <class 'double'>
D. <class 'decimal'>

8.Which of the following statements is used to create a constant in Python?


A. constant PI = 3.14
B. PI = 3.14
C. const PI = 3.14
D. define PI = 3.14

9.Which of the following is used to create a comment in Python?


A. // comment
B. /* comment */
C. <!-- comment -->
D. # comment

10.What will be the output of the following code? print('Hello ' + 'World!')
A. Hello World!
B. Hello + World!
C. HelloWorld!
D. Hello +World!

11.Which of the following data types is immutable?


A. list
B. set
C. dict
D. str

12.What is the result of bool(0) in Python?


A. True
B. False
C. None
D. 0

13.Which loop is guaranteed to execute at least once?


A. for
B. while
21
C. do-while
D. None of the above

14.What is the correct syntax for a while loop in Python?


A. while x > 0 { ... }
B. while (x > 0): ...
C. while x > 0: ...
D. while (x > 0) { ... }

15.Which of the following can be used to stop a loop prematurely?


A. stop
B. exit
C. break
D. end

16.What will be the output of the following code? for i in range(5): print(i)
A. 0 1 2 3 4
B. 1 2 3 4 5
C. 0 1 2 3 4 5
D. 1 2 3 4

17.What will be the output of the following code?

for i in range(3):
print(i)

A. 1 2 3
B. 0 1 2
C. 0 1 2 3
D. 1 2 3 4

18.What will be the output of the following code?

for i in range(2, 5):


print(i, end=' ')

A. 2 3 4 5
B. 2 3 4
C. 3 4 5
D. 2 3 4 5 6

19.What will be the output of the following code?

for i in range(1, 10, 3):


print(i, end=', ')

A. 1, 4, 7, 10,
B. 1, 4, 7,
C. 1 4 7
D. 1 4 7 10

20.What will be the output of the following code?

i=1
22
while i < 5:
print(i)
i += 1

A. 12345
B. 1234
C. 123
D. 01234

Very Short Answer Questions


1. What is the extension of Python files?
2. How do you start the Python interpreter in interactive mode?
3. What is the purpose of indentation in Python?
4. Give an example of a valid identifier in Python.
5. How do you assign a value to a variable in Python?
6. Name the arithmetic operators in Python.
7. Which operator has the highest precedence in Python?
8. What data type is returned by the input() function?
9. How do you write a single-line comment in Python?
10. What is the output of print(3 + 4 * 2)?

Short Answer Type Questions


1. What is the difference between interactive mode and script mode in Python?
2. Explain the significance of indentation in Python.
3. What are identifiers in Python and what are the rules for naming them?
4. List five keywords in Python and explain their use.
5. What is a variable in Python and how is it different from a constant?
6. Explain the difference between the == and = operators.
7. What are the different types of operators in Python?
8. Differentiate between mutable and immutable data types with examples.
9. How do you convert a list to a tuple in Python?
10. Write a Python code snippet that demonstrates the use of the if-elif-else statement.

Long Answer Type Questions


1. Discuss the structure of a Python program. Explain the importance of indentation, and provide an
example to illustrate your explanation.
2. Explain the different types of operators available in Python. Discuss the concept of operator
precedence with examples.
3. Describe the concept of mutable and immutable data types in Python. Provide examples of each type
and discuss scenarios where one might be preferred over the other.

23
4. What are control statements in Python? Explain with examples the use of if-else, if-elif-else, while
loop, and for loop.
5. Explain data type conversion in Python. Provide examples of implicit and explicit data type
conversion.

Assertion-Reasoning based questions

1. Assertion (A): Indentation is mandatory in Python to define the block of code.


Reason (R): Python uses curly braces {} to indicate the start and end of a block of code.
o A. Both A and R are true, and R is the correct explanation of A.
o B. Both A and R are true, but R is not the correct explanation of A.
o C. A is true, but R is false.
o D. A is false, but R is true.

2. Assertion (A): The range() function in a for loop generates a sequence of numbers. Reason (R): The
range() function is used to iterate over a sequence of values with a specified start, stop, and step.
o A. Both A and R are true, and R is the correct explanation of A.
o B. Both A and R are true, but R is not the correct explanation of A.
o C. A is true, but R is false.
o D. A is false, but R is true.

3. Assertion (A): Variables in Python must be declared with a specific data type before they can be
used.
Reason (R): Python is a dynamically typed language, which means variables do not need explicit
declaration before use.
o A. Both A and R are true, and R is the correct explanation of A.
o B. Both A and R are true, but R is not the correct explanation of A.
o C. A is true, but R is false.
o D. A is false, but R is true.

4. Assertion (A): In Python, strings are mutable data types.


Reason (R): Mutable data types can be changed after they are created, while immutable data types
cannot be modified.
o A. Both A and R are true, and R is the correct explanation of A.
o B. Both A and R are true, but R is not the correct explanation of A.
o C. A is true, but R is false.
o D. A is false, but R is true.

5. Assertion (A): The print() function in Python is used for outputting text to the console. Reason (R):
The input() function in Python is used to read a string from the user.
o A. Both A and R are true, and R is the correct explanation of A.
o B. Both A and R are true, but R is not the correct explanation of A.
o C. A is true, but R is false.
o D. A is false, but R is true

Case-Study/ Competency based questions

Case Study 1: You are developing a Python script to convert temperatures between Celsius and
Fahrenheit based on user input. The script should handle data type conversion, validate user inputs, and
provide clear instructions for temperature conversion.

24
1. Describe how you would implement data type conversion in the temperature conversion script.
2. Discuss the use of input and output statements to interact with users and handle different scenarios
(e.g., invalid input).

Case Study 2: Imagine you are tasked with writing a Python script for a basic calculator that can
perform addition, subtraction, multiplication, and division. The program should:
3. Prompt the user to enter two numbers.
4. Ask the user to choose an operation (addition, subtraction, multiplication, division).
5. Perform the chosen operation and display the result.

25
Introduction to Python Continue….
• Lists: list operations - creating, initializing, traversing and manipulating lists, list methods and built-
in functions – len(), list(),append(),insert(), count(),index(),remove(), pop(), reverse(), sort(),min(),
max(),sum()
• Dictionary: concept of key-value pair, creating, initializing, traversing, updating and deleting
elements, dictionary methods and built-in functions – dict(), len(), keys(), values(), items(), update(),
del(), clear()

Key Points
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each
element or value that is inside of a list is called an item. Just as strings are defined as characters between
quotes, lists are defined by having values between square brackets[].

List is a sequence of items separated by commas and items are enclosed in square brackets[]. Note that items
may be of different date types.

list1 = [5, 3.4, "New Delhi", "20C", 45]

print(list1)

[5, 3.4, 'New Delhi', '20C', 45]

String Lists

To get started, let’s create a list that contains items of the string data type:

sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone']

print(sea_creatures)

Output

['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone']

Indexing Lists

Each item in a list corresponds to an index number, which is an integer value, starting with the index number
0.

print(sea_creatures[1])

Output

Cuttlefish

List Traversing and Manipulation:

Every element of the list has an unique sequential index(position) starting from 0

List elements can be accessed and manipulated by index.


26
if LST=[3,6,9,12,15] then

LST[1] ---->refers second element, i.e 6

LST[3]=20 ----> modifies the 4th element as 20.

To traverse and display all elements of the list:-

for item in LST:

print (item)

You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment
operator, and you can add to elements in a list with the append() method.

list = ['physics', 'chemistry', 1997, 2000];

print "Value available at index 2 : "

print list[2]

list[2] = 2001;

print "New value available at index 2 : "

print list[2]

Output

Value available at index 2 :

1997

New value available at index 2 :

2001

Add Item to A List : append() method is used to add an Item to a List.

e.g.

list=[1,2]

print('list before append', list)

list.append(3)

print('list after append', list)

Output

('list before append', [1, 2])

('list after append', [1, 2, 3])

27
List Operators:
• Concatenation (+)
Joins two lists.

For example if L1=[1,2,3], L2=[4,5] then L1+L2 ---> [1,2,3,4,5]

• Replication ( * )
Replicates the list given number of time.

For example , L1*3 ----->[1,2,3,1,2,3,1,2,3]

• Membership ( IN / NOT IN)


Checks if an element is present or not.

For example : 2 in L1---> True 2 in L2--->False

• Comparison ( ==, !=, >, <, >=, <= )


Compares two lists element by element

For example:

L1==L2---->False L1!=L2= True L1>L2-----> False

Built in Functions
1. len()

returns the no of size/no of elements. len(L1)---->3 , len(L2)----->2

2. min()

returns minimum element min(L1) ----->1

3. max()

returns maximum element max(L2) ----->5

4. sum()

returns sum of elements sum(L2) ----->9 sum(L1)----->6

List Functions

5. insert()

insert an element at a given index

L2.insert(1,2.5) ------->[4,2.5,5]

6. count()
28
returns the frequency of an element

Val=[2,4,6,4,7,3,4]

Val.count(4)------>3

7. index()

returns the index of an element

Val.index(6)------>2

8. remove()

delete the element with a given value

Val.remove(7) -----> [2,4,6,4,3,4]

9. pop()

delete the element with a given index . If no index is given, last element is deleted

Val.pop(2) -----> Val=[2,4,4,7,3,4]

10. reverse()

Val.reverse( )----->[4,3,7,4,4,2]

arranges the elements of the list in a reverse order

11. sort()

arranges the elements of a list in ascending order.

cars = ['Ford', 'BMW', 'Volvo']

cars.sort() ----> ['BMW', 'Ford', 'Volvo']

12. clear( )

deletes all elements of the list

Num=[1,4,7,9]

Num.clear() -----> Will give empty list

13. extend()

Merge the elements of a list in the current list

L1.extend(L2) ----->[1,2,3,4,5]

L2.extend(L1) ------>[4,5,1,2,3]

29
Dictionary
Dictionary in Python holds data items in key-value pairs and Items are enclosed in curly brackets { }.
Dictionaries permit faster access to data. Every key is separated from its value using a colon (:) sign. The
key value pairs of a dictionary can be accessed using the key. Keys are usually of string type and their values
can be of any data type. In order to access any value in the dictionary, we have to specify its key in square
brackets [ ].

Create a dictionary
dict1 = {'Fruit':'Apple','Climate':'Cold', 'Price(kg)':120}

print(dict1)

{'Fruit': 'Apple', 'Climate': 'Cold','Price(kg)': 120}

#getting value by specifying a key

print(dict1['Price(kg)'])

Output -120

A dictionary in Python is created with key-value pairs, where each key is separated from its value by a colon
(:), the items are separated by commas, and the whole thing is enclosed in curly braces {}. An empty
dictionary without any items is written with just two curly braces, like this: {}
dictionary = {

"key": “value”,
"key2": “value2”,
"key3": “value3”}

Accessing elements of a Dictionary:

• We need a key to access any element of a Dictionary likewise in lists, strings and tuples we used index to
access any element.

• Example:

TeacherCount={'PGT':10, 'TGT':7, 'PRT':5}

TeacherCount['PGT']

Output -10

• Note: Attempting to access a key that doesn’t exist causes an error

Iterating / Traversing through A Dictionary

Following example will show how dictionary items can be accessed through loop.

e.g.

dict = {'Subject': 'Informatics Practices', 'Class': 11}


30
for i in dict:

print(dict[i])

OUTPUT

Informatics Practices

11

Updating/Manipulating Dictionary Elements

We can change the individual element of dictionary. e.g.

dict = {'Subject': 'Informatics Practices', 'Class': 11}

dict['Subject']='computer science'

print(dict)

OUTPUT

{'Class': 11, 'Subject': 'computer science'}

Deleting Dictionary Elements

Before remove key:


{'Anuradha': 22, 'Haritha': 21, 'Arushi': 22, 'Nakul': 20}

Operation Perform: del test_dict['Nakul']

After removing key:

{'Anuradha': 22, 'Haritha': 21, 'Arushi': 22}

pop() method is used to remove a particular item in a dictionary. clear() method is used to remove all
elements from the dictionary e.g.

dict = {'Subject': 'IP', 'Class': 12}

print('before del', dict)

dict.pop('Class')

print('after item delete', dict)

dict.clear()

print('after clear', dict)

Output

('before del', {'Class': 12, 'Subject': 'IP'})

31
('after item delete', {'Subject': 'IP'})

('after clear', {}) Python has a set of built-in methods that you can use on dictionaries.

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the
specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

The 3 main characteristics of a dictionary are :

1. Dictionaries are unordered: The dictionary elements (key-value pairs) are not in ordered form.

2. Dictionary keys are case sensitive: The same key name but with different case are treated as different keys
in Python dictionaries.

3. No duplicate key is allowed: When duplicate keys encountered during assignment, the last assignment
wins.

Multiple ways of Creating Dictionaries:

Method 1: Passing Key-Value Pairs as Literals

The simplest and most common way to initialize a Python dictionary is to pass key-value pairs as literals in
curly braces. For example:

my_dictionary = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

Method 2: Using dict() constructor

32
The built-in dict() constructor creates a Python dictionary. Pass the key-value pairs as the keyword
arguments to populate the dictionary. For example:

my_dictionary = dict(key1='value1', key2='value2', key3='value3')

Method 3: Using Lists

The dict() constructor, together with the zip() function, enables merging two lists into key-value pairs.
Provide the key values in one list and the values in a separate list. Then, combine the two using the zip()
function. For example:

keys = ['key1', 'key2', 'key3']


values = ['value1', 'value2', 'value3']

my_dictionary = dict(zip(keys, values))

Method 4: Using Tuples

An alternative way to pass values into the dict() constructor is to provide the key-value pairs as a list of
tuples. For example:

my_dictionary = dict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

How to Check if a Key Exists in a Dictionary

(i) You can use the in operator to check if a key exists in a dictionary.

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

if 'key1' in my_dict:
print("Key exists in the dictionary.")
else:
print("Key does not exist in the dictionary.")

(ii) Using the dict.get() Method

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

if my_dict.get('key1') is not None:


print("Key exists in the dictionary.")
else:
print("Key does not exist in the dictionary.")

Checking for Existence of a Value:

To check if a key exists in a Python dictionary, there are three main methods that can be used: the in
keyword, the get() method, and the keys() method. The in keyword is the simplest way to check if a key
exists in a dictionary. It returns a boolean value of True if the key is present and False otherwise.

33
person = {'name': 'John', 'age': 30, 'gender': 'male'}

# Using get() method to check if key exists

if person.get('name'):

print('Name:', person['name'])

else:

print('Name not found')

Nested Dictionaries

A dictionary can contain dictionaries, this is called nested dictionaries.

myfamily = {

"child1" : {

"name" : "Mahesh",

"year" : 2004

},

"child2" : {

"name" : "Sarita",

"year" : 2007

}}

Functions and Dictionary Methods:

1. len(Dictionary):

Returns total number of elements present in the dictionary.

Example:

T20Cricketer={'Name':'Virat','Runs':2790,'Age':31}

>>> len(T20Cricketer)

Output -3

2. Dictionary.keys():

Returns a list of keys of the dictionary.

Example:

>>> T20Cricketer.keys()
34
dict_keys(['Name', 'Runs', 'Age'])

3. Dictionary.values():

Returns a list of values of the dictionary.

Example:

>>> T20Cricketer.values()

dict_values(['Virat', 2790, 31])

4. Dictionary.items() :

Returns all of the items of the dictionary as a sequence of (key,value) tuples

Example:

>>> T20Cricketer.items()

dict_items([('Name', 'Virat'), ('Runs', 2794), ('Age', 31)])

TIME TO PRACTICE
Objective Question (1 Mark )

1 Identify the immutable data type:


(a) dictionary (b) int (c) list (d) set

Ans (b)

2 What are the two modes of Python interpreter?


(a Interactive mode (b) script mode (c) Both (d) None of these

Ans C

3 a=5>2
What will be the data type of the variable a?
(a) True (b) int (c) bool (d) None of these

Ans (c) bool

4 1. ____ are used to store the values in keys and pairs.


A. Set
B. Map
C. Dictionary
D. Tuple
Ans C) Dictionary

35
5 4. In the dictionary, which symbol is used to separate keys and pairs?
A. ,
B. ::
C. :
D. ""
Ans C) :

6 From the given syntax, which of the following is the correct syntax to create a
dictionary?
A. Dict=[ 1:"hi",2:"hello"]
B. Dict={ 1:"hi",2:"hello"}
C. Dict={ 1:"hi",2:"hello"}
D. Dict=[ 1:"hi",2:"hello"]
Ans C) Dict={ 1:"hi",2:"hello"}

7 What will be the output of the following code?


D={1:7,2:"everyone"}
print(D[2])
A. 7
B. 1
C. 2
D. everyone
Ans D) everyone

8 Which of the following is correct way of creating a dictionary?

a) Medals={‘Gold’=12,’Silver’=21,’Bronze’=32}

b) Medals={‘Gold’:12,’Silver’:21,’Bronze’:32}

c) Medals=[‘Gold’:12,’Silver’:21,’Bronze’:32]

d) Medals=(‘Gold’:12,’Silver’:21,’Bronze’:32)

Ans b) Medals={‘Gold’:12,’Silver’:21,’Bronze’:32}

9 Identify the immutable data type:


(a) dictionary, (b) int, (c) list, (d) set.

Ans (b)

10 Which of the following commands will create a list?

a) list1 = list()

b) list1 = []

c) list1 = list([1, 2, 3])

36
d) all of the mentioned

Ans d)

11 What is the output when we execute list(“hello”)?


a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

b) [‘hello’]

c) [‘llo’]

d) [‘olleh’]

Ans a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

12 Suppose list1 is [3, 5, 25, 1, 3], what is min(list1)?


a) 3

b) 5

c) 25

d) 1

Ans d) 1

13 Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1]?


a) Error

b) None

c) 25

d) 2

Ans c) 25

14 Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1]?

a) [2, 33, 222, 14]

b) Error

c) 25

d) [25, 14, 222, 33, 2]

Ans a) [2, 33, 222, 14]

15 Suppose list1 is [1, 3, 2], What is list1 * 2?


a) [2, 6, 4]

b) [1, 3, 2, 1, 3]

c) [1, 3, 2, 1, 3, 2]

37
d) [1, 3, 2, 3, 2, 1]

Ans c) [1, 3, 2, 1, 3, 2]

16 To insert 5 to the third position in list1, we use which command?


a) list1.insert(3, 5)

b) list1.insert(2, 5)

c) list1.add(3, 5)

d) list1.append(3, 5)

Ans b) list1.insert(2, 5)

17 To remove string “hello” from list1, we use which command?


a) list1.remove(“hello”)

b) list1.remove(hello)

c) list1.removeAll(“hello”)

d) list1.removeOne(“hello”)

Ans a) list1.remove(“hello”)

18 Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1.count(5)?


a) 0

b) 4

c) 1

d) 2

Ans d) 2

19 Suppose list1 = [0.5 * x for x in range(0, 4)], list1 is:


a) [0, 1, 2, 3]

b) [0, 1, 2, 3, 4]

c) [0.0, 0.5, 1.0, 1.5]

d) [0.0, 0.5, 1.0, 1.5, 2.0]

Ans C

20 What will be the output of the following Python code?


>>>list1 = [11, 2, 23]

>>>list2 = [11, 2, 2]

>>>list1 < list2

a) True

38
b) False

c) Error

d) None

Ans B

21 Suppose list1 is [3, 4, 5, 20, 5], what is list1.index(5)?

a) 0

b) 1

c) 4

d) 2

Ans d) 2

22 Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after


listExample.extend([34, 5])?
a) [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]

b) [1, 3, 3, 4, 5, 5, 20, 25, 34, 5]

c) [25, 20, 5, 5, 4, 3, 3, 1, 34, 5]

d) [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]

Ans A

23 Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.pop(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]

Ans C

24 What will be the output of the following Python code snippet?

d1 = {"john":40, "peter":45}

d2 = {"john":466, "peter":45}

d1 == d2

a) True

b) False

c) None

39
d) Error

Ans B

25 What will be the output of the following Python code snippet?

d = {"john":40, "peter":45}

print(list(d.keys()))

a) [“john”, “peter”]

b) [“john”:40, “peter”:45]

c) (“john”, “peter”)

d) (“john”:40, “peter”:45)

Ans a

Very Short Answer (1 Mark )

1 What is list in python?

2 What is list slicing?

3 What is nested list in python?

4. Give examples some examples of Built-in Functions in Python?

5 What is the concept of key-value pair in Dictionary?

6 What is Iterating in Python Dictionary?

7 Give Some built-in functions of Python Dictionary.

8 What is use of pop () method in Python Dictionary?

9 What is use of clear () method in Python Dictionary?

10 What is the use of update() method in Python Dictionary?

Short Answer Questions (2 Mark )

1 What will be the output of the following code segment?

myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)

2 What will be the output of the following code segment?

myList = [1,2,3,4,5,6,7,8,9,10]

40
del myList[:5]
print(myList)
3 What is list indexing?

4 What is Dictionary?

5 What will be the output of the following code segment?


list1 = [1,2,3,4,5,6,7,8,9,10]
list1[::-2]
6 What will be the output of the following code segment?
list1 = [1,2,3,4,5,6,7,8,9,10]
list1[:3] + list1[3:]
7 Differentiate between append() and extend() methods of list.

8 Consider the following list myList. What will be the elements of myList after each of the
following
operations?
myList = [10,20,30,40]
myList.append([50,60])
9 Consider the following list myList. What will be
the elements of myList after each of the following
operations?
myList = [10,20,30,40]
myList.extend([80,90])

10 What is Concatenation in Python List

Long answer (3 Mark )

1 How you will Update a dictionary, give example?

2 What is Repetition in Python List?

3 What are Membership operators in Python?

4 What is Slicing in List?

5 How you will show Traversing a List?

6 How a Dictionary may be created

7 How Items in a Dictionary may be accessed?

8 What are mutable and immutable data types in python, explain with Python Dictionary?

9 Display the keys(), values() and items() method in dictionary ‘ODD’.

41
10 Write a program to count the number of times a character appears in a given string.

Open ended question (Assertion and Reasoning) 1 Mark

Mark the correct choice as

(A) Both(A) and (R) are true and (R) is a correct explanation of Assertion

(B) Both (A) and (R) are true, but (R) is not the explanation of Assertion

(C) If the assertion is true but Reason is false.

(D) If both Assertion and Reason are false

1 Assertion (A) : List is a mutable data type of Python.

Reason (R) : Change of values is not possible in list elements.

2 Assertion (A): remove( ) method removes all elements from a list

Reason (R): len( ) function is used to find the length of list

3 Assertion (A): Dictionaries are mutable data type.

Reasoning (R): We cannot change the keys of the dictionaries.

4 Assertion (A):Items in dictionaries are unordered. Reasoning

(R):Internally, the key: value pairs of a dictionary are associated with one another with
some internal function (called hash-function). This way of linking is called mapping.

5 Assertion (A): We can add new key, value pairs to a dictionary.

Reasoning (R): Key to be added must not exist in dictionary and must be unique. If

the Key already exist, then it will change the value of existing key and no new entry

will be added to dictionary.

6 Assertion (A): Dictionaries are mutable data type.

Reasoning (R): We can change the values of the dictionaries.

7 Assertion (A): append( ) method is used to add an element at the end of a list

Reason (R): extend ( ) function is used to merge two lists into a single list

8 Assertion (A): Elements of a list are separated by comma.

Reason (R): List is enclosed by a pair of straight brackets.

9 Assertion (A): We can update values of a dictionary by the help of keys.

Reasoning (R):It is not necessary that the key has to present in the dictionary.

10 Assertion (A): clear( ) method removes all elements from a list

Reason (R): sort ( ) function is used sort a list in descending order

42
Case study and competency based questions (5 Mark)

1 A list is a standard data type in Python that can store a sequence of values belonging to
any
type. Lists are enclosed in a pair of square brackets. These are mutable, i.e, elements can
be
changed by the user. Every element of a list has an index. Indexing begins from zero.
Questions:-

I.List defined within a list is called:-

a. nested list b. super list c. sub list d. hidden list

II. In Python, list is of type:-

a. Immutable b. Mutable c. Both a & B d. None of a & b

III. If a list contains n elements, then the index of the last element will be:-

a. 0 b. n c. n+1 d. n-1

IV. Which type of the bracket is used to define a list?

a. ( ) b. { } c. [ ] d. <>

V. List can contain values of these types:-

a. integers b. float c. string d. all of these

2 Aman has created two lists L1=[6,2,3,8] and L2=[1,5,4]


He has been asked by his teacher to write the code for the following tasks:-
I. To predict the output of the code:-
L3=L2.extend(L1)
print(L3)
II. To display smallest number from L3
III. To add 2nd element from L1 and 3rd element from L2
IV. To arrange the elements of L3 in descending order
V. To predict the output : L1[:2]+L2[2:]
3 Rakhi wants to write a program to count the number of vowels from the word 'Alexander'
by converting it into a list. But the program does not run due to errors. Help Rakesh to
identify and rectify the errors so that program can run:-
L=List('Alexander')
count==0
for i in L:
if i within 'aeiouAEIOU'
count=+1
print(count)
4 Rekha has a list of both positive numbers. She has been given a task to separate
positive and negative numbers into two different lists and finally to delete the
43
original list. She has written a code where some statements incomplete. Complete the
incomplete statements by filling in the blanks:-

Numbers=[5,-8,9,-7,5,-4]
Pos, Neg= ____ #Statement 1: To initialize empty lists
for i in range( ): # Statement 2: To write the range to access all elements
if Numbers[i]>=0:
____________ # Statement 3: To add element in POS
else:
_____________ # Statement 4: To add element in another list
____________ #Statement 5: To delete the original list
print (Pos)
print(Neg)
print("Task Completed")
5 Raman has stored record of a student in a list as follows:-
rec=[‘Thomas’,’C-25’,[56,98,99,72,69],78.8]

Suggest him the Python statements to do the following tasks:-


a. To find the percentage
b. To find marks of 5th subject
c. Maximum marks of the student
d. To find total marks
e. To change the name from ‘Thomas’ to ‘ Charles’
6 Predict the output of the following code:-
Moves=[11, 22, 33, 44]
Queen=Moves
Moves[2]+=22
L=len(Moves)
for i in range (L):
print (“Now@”, Queen[L-i-1], “#”, Moves [i])
7 Predict the output of the following code:
Teacher1,Teacher2={'EmpId':3698,'Name':'Robin','Desig':'PGT',
'Sub':'Chemistry'},{'EmpId':9821, 'Name':'Sachin','Desig':'PRT','HomeTown':'Patna'}
print(Teacher1)
print(Teacher2)
Teacher1.update(Teacher2)
print(Teacher1)
print(Teacher2)
8 Predict the output of the following code:
Marks5Subs={'Sawan':[67,74,56,48,87],'Ankit':[34,46,39,21,41],
'Puja':[91,87,73,82,95],'Arnab':[78,98,97,95,99]}
print(max(Marks5Subs['Sawan']))
44
print(min(Marks5Subs['Ankit']))
print(len(Marks5Subs['Arnab']))
print(len(Marks5Subs))
9 Predict the output of the following code:
Age={'Sawan':67,'Ankit':34,'Puja':21,'Arnab':23}
print(list(Age.items()))
del Age['Sawan']
print(Age)
Age.clear()
print(Age)
del Age
print(Age)
10 Write a program to convert a number entered by the user into its corresponding number in words.
for example if the input is 876 then the output should be ‘Eight Seven Six’.

45
Database concepts and the Structured Query Language

• Database Concepts: Introduction to database concepts and its need, Database Management System.
• Relational data model: Concept of domain, tuple, relation, candidate key, primary key, alternate key

DATABASE CONCEPTS
A database is a collection of DATA/INFORMATION that is organized so that it can be easily accessed,
managed and updated.
In Database, Data is organized into rows, columns and tables, and it is indexed to make it easier to find
relevant information. It works like a container which contains the various object like Tables, Queries,
Reports etc.in organized way.

Database Management System (DBMS) is a software for storing and retrieving users' data while
considering appropriate security measures. It consists of a group of programs which manipulate the database.
The DBMS accepts the request for data from an application and instructs the operating system to provide the
specific data. In large systems, a DBMS helps users and other third-party software to store and retrieve data.

DBMS allows users to create their own databases as per their requirement. The term “DBMS” includes the
user of the database and other application programs. It provides an interface between the data and the
software application.

Need for DBMS

• The file management system is a traditional mechanism to store data permanently into secondary
devices but in today digital word TBs of data need to be stored in an organized place which needs
security as well as retrieval in seconds of time
• Traditional file systems have the very lowest level of storage and processing capabilities
which created problems regarding security, integrity, memory storage and duplicate data, data
inconsistency and so on.
• DBMS provides solution for problems faced in above two conditions.
Advantages of Database Management

1. Data retrieval

If you want to retrieve data from the flat file then we must develop application programs in a high-level
language, so that data can be stored and retrieved fastly and securely within the time bound

Ex: SQL – structured query language

2.Data Redundancy (Duplication)


In any storage, we need to make copies of data for backup but in traditional file management systems once
we update data in one location sometimes it fails to get updated in the copy of the data, so that it may create
problems of inconsistency this rate is called duplicate data or redundant data

• The database automatically maintains consistent data through a transaction using certain rules and
procedures

46
• Each transaction internally follows four properties known as acid properties(atomicity, consistency,
durability, isolation)
• The database is capable of eliminating all problems of insertion-deletion updation of data through
levels of the normalization process
3.Data integrity

Data integrity ensure that only required data is stored in the database i.e data is validated before entered
into the database using integrity constraints such as primary key, foreign key, etc

4. Data security

In traditional file management, there is no authentication mechanism at high-end whereas DBMS


provides levels of security authentication which can be done at user level admin level, etc

5. Data indexing

• If you want to retrieve data very fast from the database we are using indexing mechanism whereas
Flat files don’t support indexing and solely depend upon secondary storage devices
• Indexing is a mechanism where data is uniquely identified and stored using some computational
techniques so that data is retrieved very fast.
DATA MODELS :

Data model is a model or presentation which shows how data is organized or stored in the database. A data is
modelled in any of the following ways-

Relational Data Model

In this model data is organized into Relations or Tables (i.e. Rows and Columns). A row in a table represents
a relationship of data to each other and also called a Tuple or Record. A column is called Attribute or Field.

Network Data Model

In this model, data is represented by collection of records and relationship among data is shown by Links.

Hierarchical Data Model

In this model, Records are organized as Trees. Records at top level are called Root record and this may
contains multiple directly linked Children records.

Object Oriented Data Model

In this model, records are represented as a objects. The collection of similar types of object is called class.

Relational Database Concepts:

A relational database is a collective set of multiple data sets organized by tables, records and columns.
Relational database establish a well-defined relationship between database tables. Tables communicate and
share information, which facilitates data search ability, organization and reporting.
A Relational database use Structured Query Language (SQL), which is a standard user application that
provides an easy programming interface for database interaction.

47
Table : STUDENT

Rollno Name dob Marks

1 Raman 12-12-2003 300

2 Arjun 10-10-2000 230

3 Neha 12-12-2002 250

Relation : Table Name is called Relation


e.g Name of Table ‘student’ is called relation

Attribute : Name of Column is called attribute/ field/data item.


e.g rollno, name, dob, marks are attribute

Domain : Set of values of a column is called Domain


e.g in Relation Student the set of values of column Rollno is (1,2,3) and column name is (Raman, Arjun,
Neha)

Tuple : Row of a table is called Tuple.


e.g. in Relation Student (1, Raman, 12-12-2003,300) is Tuple

Degree : No of attributes of a relation.is called degree.


e.g in Relation student degree is 3

Cardinality: No. of tuples of a relation is called cardinality


e.g in Relation student cardinality is 3

Concept of Key :
In a relational database, the key plays an important role. The key is used to identify a record or a tuple of
the table uniquely. Keys are also used to establish and identify the relationships between the tables.

Types of Keys :

Primary Key : One or more combination of keys which uniquely identify each row of the table. Primary
key implements not null and unique constraints of Table.

Example:
Primary key
Table: Student

Rollno Name Dob Marks

1 Neha 12-12-2003 300

2 Namita 10-10-2000 230

48
3 Rohan 12-12-2002 250

4 Nikhil 10-10-2000 400

Candidate Key : Set of keys which can participate as primary key is called candidate key.

Example :
Candidate Key
Table: Student

Rollno Name dob Mobile Marks

1 Neha 12-12-2003 9419916787 300

2 Namita 10-10-2000 9906904567 230

3 Rohan 12-12-2002 8004567898 250

4 Nikhil 10-10-2000 7006234056 400

Alternate Key : The candidate keys which are not chosen as primary key is called alternate key

Example :
Alternate Key
Table: Student

Rollno Name dob Mobile Marks

1 Neha 12-12-2003 9419916787 300

2 Namita 10-10-2000 9906904567 230

3 Rohan 12-12-2002 8004567898 250

4 Nikhil 10-10-2000 7006234056 400

49
Foreign Key : The non key attribute of a table which derive its values from primary key of another table is
called foreign key.

Example :
Primary key
Table: Student

Rollno Name dob Marks

1 Neha 12-12-2003 300

2 Namita 10-10-2000 230

3 Rohan 12-12-2002 250

4 Nikhil 10-10-2000 400

Foreign Key
Table : Marks

Rollno Physics Chemistry

1 34 56

3 45 56

4 67 67

50
Structured Query Language
• Advantages of using SQL, DDL, DQL & DML
• Introduction to MySQL, DDL Commands and Creating database
• Data Query: SELECT, FROM, WHERE with relational operators, BETWEEN, logical operators, IS
NULL, IS NOT NULL
• Data Manipulation: INSERT, DELETE UPDATE

Advantages of using SQL, DDL, DQL & DML


1) Easy data retrieval and manipulation
SQL offers an intuitive and straightforward method for retrieving and manipulating data from databases.
The simplicity of SQL commands such as SELECT, INSERT, UPDATE, and DELETE allows even non-
technical users to access specific data points, add new entries, modify existing records, and remove
unwanted data with ease.

2) Data security
SQL databases provide robust mechanisms to ensure the protection of sensitive information. With
features like encryption options and access controls, SQL databases safeguard data from unauthorised
access. Encryption transforms the data into unreadable formats, making it virtually impossible for
malicious entities to decipher without the appropriate decryption key.
Access controls, on the other hand, grant different levels of permissions to users, ensuring that only
authorised personnel can access certain data.

3) Scalability
SQL databases stand out for their scalability, enabling them to handle massive amounts of data without
compromising performance. Vertical scaling involves upgrading hardware resources such as CPU and
RAM to accommodate increased data requirements.
Horizontal scaling, on the other hand, involves the distribution of data across multiple servers, allowing
for seamless expansion as data demands grow. This scalability ensures that SQL databases can keep up
with the data explosion, making them a reliable choice for organisations experiencing rapid growth.

4) Data integrity
Maintaining data integrity is crucial for any database system. SQL databases excel in this aspect by
enforcing constraints and referential integrity checks. Constraints define rules that data must adhere to,
preventing the entry of invalid or inconsistent data. Referential integrity ensures that relationships between
different tables are maintained correctly, avoiding orphaned or disconnected data.

5) Flexibility in querying
SQL's flexible querying capabilities empower users to perform complex data analysis tasks efficiently.
SQL supports various operations, including joins, sub queries, and conditional statements, allowing users to
retrieve specific information from large datasets. Joins amalgamate data from multiple tables based on
common columns, enabling users to gather comprehensive insights.
Subqueries help break down complex queries into manageable parts, simplifying the overall analysis
process. Conditional statements allow users to extract data based on specific conditions, facilitating tailored
data retrieval.
6) Integration with modern technologies
SQL databases seamlessly integrate with these modern technologies, making them versatile and adaptable.
Cloud-based SQL databases offer the advantage of flexibility and cost-effectiveness, as they allow
businesses to scale resources according to their needs.
Additionally, SQL databases integrate effortlessly with big data frameworks like Apache

7) Wide adoption and community support


SQL's longevity and wide adoption have resulted in a thriving community of developers, enthusiasts, and
51
experts. The vast SQL community provides ample resources, documentation, and support for users at all
levels of expertise. Beginners can find numerous tutorials and guides to get started, while seasoned
professionals can explore advanced techniques and best practices.

8) Cost-effectiveness
SQL databases, especially open-source options like MySQL and PostgreSQL, offer a cost-effective
alternative to proprietary database systems. These open-source solutions provide powerful and feature-rich
database management capabilities without hefty licensing fees.

9) ACID compliance
SQL databases adhere to the ACID (Atomicity, Consistency, Isolation, and Durability) properties, ensuring
that transactions are processed in a reliable and secure manner. Atomicity guarantees that all parts of a
transaction are completed successfully, or none of the parts are executed at all. Consistency ensures that
data remains in a valid state throughout the transaction process. Isolation prevents interference between
concurrent transactions, safeguarding data integrity. Durability makes sure that once a transaction is
committed; its changes persist even in the event of system failures.

10) Business intelligence and reporting


SQL plays a pivotal role in business intelligence and reporting, facilitating data analysis and visualization.
SQL's ability to perform complex aggregations, calculations, and grouping enables users to generate
meaningful reports, with SQL as the backbone of data analysis; businesses can unlock their data’s full
potential and use it to gain a competitive edge in their respective markets. SQL's ability to handle large
datasets and process complex queries efficiently ensures that data-driven insights are readily available to
decision-makers.

My SQL commands

o SQL commands are instructions. It is used to communicate with the database. It is also used to
perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table, modify the table,
set permission for users.

Before executing any MySQL command you need to download and install MySQL .You may use the
following link to download and install MySQL:

https://dev.mysql.com/downloads/installer/

Once you install it, you will find “MySQL Command Line Client” in your system where you can execute all
the commands. The first screen will look like:

MySQL Password Screen

And it will ask for password. Here you have to enter the same password you entered during the installation
of MySQL to open MySQL. Once you give the correct password here it will show you MySQL prompt like:
52
MySQL First Screen
Now once this “mysql>”(read as mysql prompt ) is there, you can start writing and executing MySQL
commands here . Let’s learn MySQL commands one by one in detail.
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1. Data Definition Language (DDL): Data Definition Language actually consists of the SQL
commands that can be used to define the database schema. It simply deals with descriptions of the database
schema and is used to create and modify the structure of database objects in the database.

DDL is a set of SQL commands used to create, modify, and delete database structures but not data.

o DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.
o All the command of DDL are auto-committed that means it permanently save all the changes in the
database.

53
Some DDL commands and their syntax are:
Command Description Syntax

Create database or its objects (table, CREATE TABLE table_name


CREATE index, function, views, store procedure, (column1 data_type, column2
and triggers) data_type, ...);

DROP Delete objects from the database DROP TABLE table_name;

ALTER TABLE table_name ADD


ALTER Alter the structure of the database
COLUMN column_name data_type;

Remove all records from a table,


TRUNCATE including all spaces allocated for the TRUNCATE TABLE table_name;
records are removed

1.1 Create Database


This command is used to create a database. Database creation is a time activity. This is a storage for all the
tables. It is similar to a folder that we create and put all the related files into. This is like building a logical
area for whatever task we perform in MySQL.

Syntax: mysql> create database database name;

Example: mysql>create database mysqldb;

Creating Database

54
1.2 Show Databases
This command is used to display the list of all the databases. It will show you the list of all the databases in
MySQL.

Syntax: mysql> show databases;

Example: mysql>show databases;

Displaying Databases

1.3 Use
This command is used to open a database.

Syntax: mysql> use database_ name;

Example: mysql> use mysqldb;

Opening Database

55
1.4 Show Tables
This command is used to show the tables inside a database.

Syntax: mysql> show tables;

Example: mysql> show tables;

1.5 Create Table


This command is used to create a table structure in SQL. In order to start entering data into it, we need to
first create the structure of the table.

Syntax:

CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example:

Create table employee(

Code integer primary key,

Name varchar(30) NOT NULL,

Desig varchar(40) NOT NULL.

Salary decimal check(salary>10000),

Doj date,

Mob char(10),

Address varchar(50) NOT NULL,

Gender char default 'M’

);

Name Desig Salary Doj Mob Address Gender

Preeti Technician 15000 10/07/2007 9087654523 Ambala F

Anjali Electrician 170000 10/08/2007 9789543489 Chandigarh F

Aman Mechanic 20000 01/05/2004 8976564789 Delhi M

1.6 Alter
This command is used to make changes in the table structure. We use Alter command to make any
modification in table structure. The Alter command is used to rename a column, change the datatype/size of
a column, rename a column, and add/remove a column. Even we can change the name of the table.

To add a column/field/constraint -ADD


56
To remove a column/field – DROP

To rename- RENAME

To change datatype/size – MODIFY

a. To add a new column to a pre-existing table, we use "ADD" clause

Syntax: mysql>alter table table_name add column name datatype(size);

Example: mysql>alter table employee add experience varchar(50);

This will add a new field named experience with varchar datatype and size 50.

b. To delete a pre-existing column from a table we use "DROP" clause.

Syntax: mysql>alter table table name drop column;

Example: mysql>alter table employee drop experience;

This will delete "experience" field from the table.

c. To rename a pre-existing column we use "Rename" clause

Syntax: mysq> alter table employee rename column column name to new column name;

Example: mysql>alter table employee rename column address to city;

This will change the name of the column from address to city.

d. To change the datatype/size of a column, we use “ modify” clause

Syntax: mysql>alter table employee modify column name new datatype(new size);

Example: mysql>alter table employee modify city varchar(50);

This will modify the column with new datatype and new size.

1.7 Drop Command


This command is used to drop/delete a table. This deletes the overall data of the table along with its
structure.

Syntax: mysql>drop table table name;

Example: mysql>drop table employee;

Note that, when using drop command, it deletes all the data/rows/records from the table and its structure.

*Difference between Delete & Drop Command*

The main difference between the delete and drop commands is that the drop command deletes the data as
well as the structure of the table, while the delete command deletes the data only.

57
2. Data Query Language(DQL) : DQL statements are used for performing queries on the data
within schema objects. The purpose of the DQL Command is to get some schema relation based on the
query passed to it. We can define DQL as follows it is a component of SQL statement that allows getting
data from the database and imposing order upon it.

There is only one DQL command in SQL i.e.

Command Description Syntax

It is used to retrieve data from the SELECT column1, column2, ...FROM table_name
SELECT
database WHERE condition;

2.1 Select:
This command is used to display all/selected records from a table. This is used to show the data present in
the table in many ways and as per the requirement. The syntax for the command is:

Syntax: mysql>Select * from table_name;

Example: mysql>Select * from employee;

Selecting specific columns only from the table

mysql>select col1,col2,col3....,col n from table_ name;

Example: mysql>Select code, name, salary from employee;

FROM:
➢ Specifies the table or tables from which you want to retrieve data.
➢ It follows the SELECT clause in the SQL query.
You can query data from one or more tables by listing them after the FROM keyword,

Condition Based Searching


WHERE Clause:

Where clause is used to extract data from the table applying a given condition.

Syntax: mysql>select * from table_name where condition;

For example

1. Select the list of employees whose salary is less than 75000.

mysql>select * from employee where salary<75000;

58
In the above example, we have used < operator in WHERE clause. We can also use other relational
operators (=, <=, >, >=, !=) to specify conditions.

AND/OR:

There may be some conditions where we need to combine two or more conditions. To combine the
conditions, we use either AND or OR.

AND

The conditions attached with AND will give the result true only when all the conditions are satisfied. Only
those rows from the table will be returned that satisfy all the conditions joined using AND operator.

For Example,

1. Show list of female employee who is from Gujrat.

mysql>select * from employee where gender=‘F’ and city =‘Gujrat’;

OR

The conditions attached with OR will give the result true when any condition is true otherwise false. This
will extract all the rows from the table that satisfy any one condition attached.

For Example,

1. Show the list of employees who belongs to either ‘UP' or ‘MP';

mysql>select * from employee where city= ‘UP’ or city= ‘MP’;

Between
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 that both values are inclusive in the range you
give in the "Between" clause.

Syntax: mysql> select * from table name where col name between val1 and val2;

Ques: Display the details of those employees whose salary is between 60000 and 75000.

mysql>select * from employee where salary between 60000 and 75000;

Membership Operator IN :
The IN operator compares a value with a set of values and returns true if the value belongs to that set.

Example : The following query displays details of all the employees who are working either in DeptId D01,
D02 or D04.

The above query can be written using IN operator as shown below:

mysql> SELECT * FROM EMPLOYEE WHERE DeptId IN( ‘ D01’ , ‘D02’ ,‘D04’);

59
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.

Example :The following query displays details of all those employees who have not been given a bonus.
This implies that the bonus column will be blank.

mysql> SELECT *
-> FROM EMPLOYEE
-> WHERE Bonus IS NULL;
Example :The following query displays names of all the employees who have been given a bonus. This
implies that the bonus column will not be blank.

mysql> SELECT Ename


-> FROM EMPLOYEE
-> WHERE Bonus IS NOT NULL;
Substring pattern matching
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:

% (percentage)- used to represent zero, one, or multiple characters

__(underscore)- used to represent a single character

Eg: Consider the employee table given above, retrieve the details of those employees whose name
starts with ‘A’

mysql> SELECT *
-> FROM EMPLOYEE
-> WHERE name LIKE “A%”;
3. DATA MANIPUALTION 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. Basically, DCL statements are grouped with DML statements.

List of DML commands:

INSERT: It is used to insert data into a table.


UPDATE: It is used to update existing data within a table.
DELETE: It is used to delete records from a database table.
3.1 INSERT: This command is used to insert values in the table. We can insert values in the
60
table using following ways.

The syntax is:


mysql>Insert into table name values(vall, val2, val3.... , val n);
Here, the values must be aligned with the same sequence as the table's structure. This means you have to
provide values for all the columns in the table in the same order as they appear in the table.

For Example

mysql>insert into employee values(101,‘Aripit Pandey’,'Manager', 55000, ‘2020-06-10',’12345’ ‘UP’,


‘M’);

3.2 UPDATE: This command is used to update the pre-existing data in the database. Update command is
used if you have to changes in pre-existing data.

Syntax: mysql>update table _name set col_ name = new_ value where condition;

For Example:

1. mysql>update employee set city='delhi';

This will update city of all employees to "delhi" as no condition has been provided and hence this
updation will work for all the rows of the table. So, always be careful when using update command. Without
any specified command, it will update all the data.

2. mysql>update employee set city= 'Mumbai' where code=102;

This will update city of employee code 102 to "Mumbai".

3.3 DELETE : This command is used to delete the data from the database. This provides us the facility to
delete either one record or multiple records from the table.

Syntax: mysql>delete from table_ name where condition;

mysql>delete from employee;

//will delete each and every record of employee table.

mysq>delete from employee where code=108;

TIME TO PRACTICE
Multiple Choice Question

Ques.1 A is a subset of DML that just deals with information retrieval.


(A) Query Language
(B) Structure Language
(C) Both a) and b)
(D) None of the above
Ans. (A) Query Language
Ques.2 A is a language that enables users to access and
manipulate data in a database.

(A) Data Manipulation Language (DML)


61
(B) Data Definition Language (DDL)
(C) Both a) and b)
(D) None of the above
Ans. (A) Data Manipulation Language(DML)
Ques.3 What SQL clause is used to specify the columns you want to retrieve from a
table?
(A) SELECT
(B) FROM
(C) WHERE
(D) INSERT

Ans. (A) SELECT


Ques.4 Which SQL clause specifies the table from which data should be retrieved?
(A) SELECT
(B) FROM
(C) WHERE
(D) UPDATE

Ans. (B)FROM
Ques.5 What SQL operator is used for exact value matching in a WHERE clause?
(A) LIKE
(B) BETWEEN
(C) =
(D) AND

Ans. (C) =
Ques.6 Which SQL operator is used to check if a column value falls within a specified
range?
(A) LIKE
(B) BETWEEN
(C) =
(D) AND

Ans. (B) BETWEEN


Ques.7 What is the purpose of the IS NULL operator in SQL?
(A) It checks if a column contains a specific value.
(B) It checks if a column is empty.
(C) It checks if a column is not empty.
(D) It checks if a column exists.

Ans. (B) It checks if a column is empty


Ques.8 Which logical operator combines multiple conditions in a WHERE
clause with an OR relationship?
(A) AND
(B) OR
(C) NOT
(D) XOR

Ans. (B) OR
Ques.9 What SQL statement is used to add new records to a database table?
(A) INSERT
(B) DELETE
(C) UPDATE

62
(D) ALTER

Ans. (A) INSERT


Ques. 10 Which SQL clause is used to delete records from a database table?
(A) INSERT
(B) DELETE
(C) UPDATE
(D) ALTER

Ans. (B) DELETE


Ques.11 Which SQL clause is used to modify existing records in a database table?
(A) INSERT
(B) DELETE
(C) UPDATE
(D) ALTER

Ans. (C) UPDATE


Ques.12 Which SQL statement is used to remove all records from a table?
(A) TRUNCATE
(B) DROP
(C) DELETE
(D) REMOVE

Ans. (c) DELETE


Ques.13 What does the SQL WHERE clause do?
(A) It specifies which columns to retrieve.
(B) It filters the rows to include based on a condition.
(C) It specifies the table to query.
(D) It sorts the result set.

Ans. (B) It filters the rows to include based on a condition.


Ques.14 What is the purpose of the NOT operator in a SQL WHERE clause?
(A) It negates a condition.
(B) It checks if a column is empty.
(C) It checks if a column exists.
(D) It combines conditions with OR.

Ans. (A) It negates a condition.


Ques.15 Which SQL clause is used to update data in a table with new values?
(A) INSERT
(B) DELETE
(C) UPDATE
(D) ALTER

Ans.(C) UPDATE
Ques.16 What SQL operator is used for pattern matching in a WHERE clause?
(A) LIKE
(B) BETWEEN
(C) =
(D) AND
Ans. (A) LIKE

63
Ques.17 Which SQL operator checks if a column value is not equal to a specified
value in a WHERE clause?
(A) LIKE
(B) BETWEEN
(C) <>
(D) AND
Ans. (C) <>
Ques.18 Which SQL statement is used to retrieve data from a database?
(A) UPDATE
(B) DELETE
(C) INSERT
(D) SELECT

Ans. (D) SELECT


Ques.19 Which command should be used to change the datatype of a column in an SQL
table?
A) CREATE
B) ALTER
C) DROP
D) TRUNCATE

Ans. (B) ALTER


Ques.20 ___________removes all rows from a table without logging the individual row
deletions.
A)DELETE
B)REMOVE
C)DROP
D) TRUNCATE

Ans. (D) TRUNCATE

Very Short Answer Type Questions (10)

Ques. 1 Write the full form of DDL and DML.


Ans. DDL- Data Definition Language
DML- Data Manipulation Language
Ques.2 What is a NULL Value?
Ans. A NULL value is a value in a field which is blank , with empty or no value ;
not even zero is entered.
Ques.3 Find the error in the following query and rewrite it:
DELETE * FROM STUDENT;
Ans. DELETE FROM STUDENT; is the correct query, * is not part of the syntax.
Ques.4 Categorize the following SQL commands into DDL and DML :
CREATE, UPDATE, INSERT, DROP
Ans. DDL Commands: CREATE, DROP
DML Commands: INSERT, UPDATE

Ques.5 Correct the error in the following query.


Select * from RECORD where Rname = %math%;
Ans. Select * from RECORD where Rname like %math%;
Ques.6 Explain the purpose of the SQL SELECT statement and provide an example of
64
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. Example: SELECT FirstName, LastName FROM Employees;
Ques.7 How can you eliminate duplicate records in a table with SELECT query?
Ans. The DISTINCT clause is used with SELECT statement to hide duplicate
records in a table. For example, to display unique cities from table suppliers, the
statement will be: SELECT DISTINCT City FROM Suppliers;
Ques. 8 Write a command that deletes all details for customer SOHAN from table
customer.
Ans. DELETE from Customer Where Customer_ name LIKE 'SOHAN';
OR
DELETE FROM Customer WHERE Customer _name = ‘SOHAN';
Ques.9 Which command is uded to view the list of tables in a database?
Ans. SHOW TABLES:
Ques.10 In SQL , what is the use of IS NULL OPERATOR?
Ans. To check if the coloumn has null value/no value.

Short Answer Type Questions (10)


Ques.1 Describe the primary function of the SQL INSERT statement and provide an
example of how it is used to add new records to a database table.
Ans. The primary function of the SQL INSERT statement is to add new records
to a database table.
Example: INSERT INTO Employees (FirstName, LastName) VALUES ('Jane',
'Doe');
Ques.2 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;
Ques.3 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. Example: SELECT FirstName, LastName FROM Employees;
Ques.4 What are DDL and DML statements?
Ans. DDL statements are used for creating or deleting tables. DML tables are
used for manipulating values of records in a table.
Ques.5 Explain the difference between DELETE and TRUNCATE commands.
Ans. The DELETE command is used by professionals to remove particular rows
from a table based on a condition, allowing you to selectively delete records.
TRUNCATE, on the other hand, removes all rows from a table without specifying
conditions. TRUNCATE is faster and uses fewer system resources than DELETE
but does not log individual row deletions.
Ques. 6 Describe the SELECT statement.
Ans. The SELECT statement serves the purpose of fetching data from one or
multiple tables, enabling you to specify the desired columns to retrieve, apply
filters through the WHERE clause.
Ques. 7 Differentiate between Alter and Update command.

65
Ans. Alter Command:
(i) It is used to change the columns of the existing table such as:
* Adding a new column
*Deleting a column
* Changing the data type of the column
* Renaming a column
It is also used to add or delete the constraints on an existing table.
(ii) It is a DDL command.

Update Command:
(i) It is used to modify some or all records of the table specified by a condition.
(ii) It is a DML command.

Ques.8 How can you add a new column or a constraint in a table?

Ans. If you want to add a new column to an existing table, ALTER Command is
used. For example, to add a column bonus in a table emp, the statement will be
given as:
ALTER TABLE emp
ADD bonus Integer;
Ques.9 Write a query to display details of all those employees from EMPLOYEE table
whose name starts with ‘K’.
Ans. Select * from EMPLOYEE where Ename LIKE ‘K%’;
Ques. 10 Write a query to display details of all those employees from EMPLOYEE table
whose name ends with ‘a’.
Ans. Select * from EMPLOYEE where Ename LIKE ‘%a’;

LONG ANSWER TYPE QUESTIONS (5)

Ques1 Consider the following table EMPLOYEE.

Write SQL commands for (i) to (vi):


(i) To display the details of all employees.
(ii) To display NAME and DESIGN of those employees whose SALGRADE is
either S02 or S03.
(iii) To display details of the employees whose DOJ is between '09-02-2006’ and '08-
08-2009'.
(iv) To add a new row with the following content:
(109, 'Harish Roy', ‘HEAD-IT', 'S02', '9-09-2007", ‘21-04-1983', 32000, 12000)
(v) To display the details of all employees whose Salary is greater than 30000.
(vi) To display list of all unique SGrade

Ans. (i) SELECT * FROM Employee;


66
(ii) SELECT Name, Design FROM Employee WHERE sgrade="S02" OR
sgrade="S03";
(iii) SELECT * FROM Employee WHERE DOJ BETWEEN '2006-02-09' AND '
2009-08-08';
(iv) INSERT INTO Employee VALUES (109, 'Harish Roy', 'HEAD-IT', 'S02',
2007-09-09, '1983-04-21', 32000, 12000) ;
(v) SELECT * FROM Employee WHERE Salary>30000;
(vi) SELECT DISTINCT SGrade FROM Employee ;
Ques2 Write the SQL commands for (a) to (e) on the basis of table SPORTS:

a) Display the names of the students who have grade 'C' in either Game1 or Game2
or both.
(b) Display the details of students getting grade 'A' in Cricket.
(c) Display the names of the students who have same game for both Game1 and
Game2.
(d) Display the games taken up by the students whose name is 'Arpit'.
(e) Adda new column named 'Marks'.

Ans. (a) SELECT Name FROM SPORTS WHERE Gradel='C' OR Grade 2= ‘C’;
(b) SELECT * FROM SPORTS WHERE Grade1="A";
(c) SELECT Name FROM SPORTS WHERE Game1 = Game2;
(d) SELECT Game1, Game2 FROM SPORTS WHERE Name = "Arpit";
(e) ALTER TABLE SPORTS ADD (Marks int (4) );
Ques3 Write SQL commands to perform the following tasks:
(a) Create a database 'Hospital'.
(b) Open database ‘Hospital'.
(c) Create a table 'Doctor' with the following structure:

(d)Display the structure of the table 'Doctor.


(e) Add one more column Date_ of_ Joining with Date data type.
(f) Insert the following record in a table:
D01, Dr. Vaibhav Singh, ENT, 99XXXX, Paschim Vihar, 7800, 2010-10-12 .
67
(g) Change the data type of column Doc Name from Varchar(30) to Varchar(50).
(h) Rename the column MobileNo to ContactNo.
(i) Delete the column Address.
(j) Delete the table 'Doctor'.

Ans. (a) CREATE DATABASE Hospital;


(b) USE Hospital;
(c) CREATE TABLE DOCTOR (
Doc ID char (4) PRIMARY KEY,
Doc Name varchar (30),
Doc Speciality varchar (30),
MobileNo varchar (30) ,
Address varchar (30),
Salary integer) ;
(d) DESC Doctor;
(e) ALTER TABLE Doctor ADD Date _of_joining Date;
(f) INSERT INTO Doctor VALUES ('D01' , 'Dr. Vaibhav Singh', ENT', 99xxxx,
'Paschim Vihar', 7800, '2010-10-12 ') ;
(g)ALTER TABLE Doctor MODIFY Doc_ Name Varchar (50) ;
(h) ALTER TABLE Doctor CHANGE MobileNo ContactNo Varchar (10) ;
(i) ALTER TABLE Doctor DROP Address;
(j) DROP Table Doctor;
Ques.4 Explain IN, BETWEEN and LIKE operators in SQL with examples.
Ans. IN: The IN operator compares a value with a set of values and returns true if
the value belongs to that set.
Example : The following query displays details of all the employees who are working
either in DeptId D01, D02 or D04.
The above query can be written using IN operator as shown below:
mysql> SELECT * FROM EMPLOYEE WHERE DeptId IN( ‘ D01’ , ‘D02’
,‘D04’);
BETWEEN: This clause lets us the facility 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 that both values are inclusive in the range you give in the
"Between" clause.
Syntax: mysql> select * from table name where col name between val1 and val2;
Ques: Display the details of those employees whose salary is between 60000 and
75000.
mysql>select * from employee where salary between 60000 and 75000;
LIKE: The LIKE operator is used to search for a specified pattern in a column. This
operator is used with the columns of type CHAR and VARCHAR. The LIKE
operator searches the column to find if a part of this column matches the string
specified in the parentheses after the LIKE operator in the command.
The SQL LIKE condition allows you to use wildcard characters to perform pattern
matching. SQL provides two wildcard characters that are used to compare the strings
with LIKE operator:
(a) Percent (%): Matches any string
(b) Underscore(_):Matches any one character
Syntax for LIKE: SELECT <column _name(s)>
FROM <table_name>
WHERE <column_name> LIKE <pattern>;
Ques.5 Write the output of the following commands:

68
(i)SELECT MATCH_ID FROM MATCH DETAILS WHERE TEAM2_ SCORE
BETWEEN 40 AND 60;
(ii) SELECT TEAM1_SCORE+1 FROM MATCH DETAILS WHERE
TEAM1_ID=1;
(iii) SELECT TEAM1_ID, TEAM2_ID FROM MATCH DETAILS WHERE
TEAM1_SCORE<70 AND TEAM2_SCORE<70;
(iv) SELECT MATCH ID FROM MATCH _DETAILS WHERE MATCH _DATE
LIKE"%-19";

Ans.

Assertion and Reasoning Questions (5)

In the following questions, a statement of Assertion (A) is followed by statement of


Reason (R). Mark the correct choice as:
(a) Both A and R are true and R is the correct explanation of A.
(b) Both A and R are true and R is not the correct explanation of A.
(c) A is true but R is false (or partly true)
(d) A is false (or partly true) but R is true.
(e) Both A and R are false or not fully true.

Ques.1 Assertion: The SQL SELECT statement is used to update records in a database.
Reason: The SELECT statement allows you to retrieve data from a database table.

Ans. (C) The assertion is true, but the reason is false.


Ques.2 Assertion: The SQL WHERE clause is used for sorting the result set of a query.
Reason: The WHERE clause specifies conditions to filter rows in a query.
Ans. (C) The assertion is true, but the reason is false.
Ques.3 Assertion: The IS NULL operator in SQL checks if a column has a value.
Reason: The IS NULL operator checks if a column contains a specific value.
69
Ans. (C) The assertion is true, but the reason is false.
Ques.4 Assertion: The SQL DELETE statement is used to add new records to a
database table.
Reason: The DELETE statement removes records from a database table.
Ans. (B) Both the assertion and reason are true, but the reason does not explain the
assertion.
Ques.5 Assertion: The SQL BETWEEN operator is used for exact value matching
in a WHERE clause.
Reason: The BETWEEN operator checks if a column value falls within a specified
range.
Ans. (A) Both the assertion and reason are true, and the reason correctly explains the
assertion.

Competency Based Questions

Ques.1 Which statement is used to select a database and make it current?


Ques.2 Salma created a relation “Books” with 3 rows and 6 columns, she added one row and
deleted one column. What is its degree and cardinality?
Ques.3 Which keyword is used to eliminate redundant data?
Ques.4 Write SQL command to create the table “Employee” with following structure :
column name data type
empcode char(6) primary key
empname varchar(20) not null
designation varchar(20)
date_of_joining date
salary integer
Ques.5 Raman wants to see the structure of “student” tables in database “school”. Help him
to write steps of commands in SQL.

Ques.6 An educational institution EducationPoint is considering to maintain their inventory


using
SQL to store the data. As a database administer, Ajay has decided that :
• Name of the database - edupoint
• Name of the table - STUDENT
• The attributes of student are as follows: studentID – numeric
studName – character of size 30
sCode – character of size 10
marks – numeric
Table: STUDENT
studentID studName sCode marks
1002 Rama ABC 90
1004 Anurag XYZ 70
1009 Raj PQR 85
1008 Aruna PQR 80
1020 Anish ABC 79
1024 Diksha XYZ 84
1031 Sahil ABC 88

(a) Identify the attribute best suitable to be declared as a primary key


70
(b) Write the degree and cardinality of the table STUDENT
(c) Insert the following data into the attributes studentID, studName and SCode
respectively in the given table SUDENT.
studentID = 1033, studName = “Aryan” and Scode = ABC

Introduction to 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, laaS, PaaS), Grid Computing, Block chain technology

Artificial Intelligence
AI is the ability of a machine or computer system to copy human intelligence process, learn experiences and
adapt to new information, perform humanlike activities.

Using these technologies, computers can be trained to accomplish specific tasks by processing large
amounts of data and recognizing patterns in the data.

Or we can say that Artificial intelligence (AI) refers to the simulation of human intelligence in machines that
are programmed to think like humans and mimic their actions.

An Al based program and technology should be capable of:

● It should be able to mimic human thought process and behaviour e.g., learning from

Mistakes, catching up with new ideas, learning new things from new exposure, past

experiences (this ability is called heuristics.) etc.

● It should act in a human-like way intelligent, rational, ethical, i.e., it should take right decisions in ethical
ways.

Applications of AI

● Handwriting Recognition
● Gaming
● Intelligent Robots
● Natural Language Processing etc.
Common examples are:

• Humanoid Robot-Sophia
• Siri or Alexa –the personal assistant
• Google’s NEST -is a line of smart home products including smart speakers, smart
displays, streaming devices, thermostats, smoke detector set c.
• Self-Driving cars like Tesla.
• Online games like Alien: Isolation
• spam filters
• voice to text features
• automated responders and online customer support
71
Machine Learning
• Machine learning is an application of artificial intelligence (AI) that provides systems the ability to
automatically learn and improve from experience without being explicitly programmed.
• Machine learning focuses on the development of computer programs that can access data and use it
learn for themselves.
• The process of learning begins with observations or data, such as examples, direct experience, or
instruction, in order to look for patterns in data and make better decisions in the future based on the
examples that we provide. The primary aim is to allow the computers learn automatically without
human intervention or assistance and adjust actions accordingly.
• It comprises algorithms that use data to learn on their own and make predictions.
• These algorithms, called models, are first trained, and tested using a training data and testing data,
respectively.
• After successive trainings, once these models are able to give results to an accept able level of
accuracy, they are used to make predictions about new and unknown data.

Natural Language Processing


• Natural Language Processing is the technology used to aid computers to understand the human’s
natural language.
• It’s not an easy task teaching machines to understand how we communicate. Now you can say,
“Alexa, play this song,” and a device start playing that music.
• The complete interaction was made possible by NLP, along with other AI elements such as machine
learning and deep learning. NLP makes it possible for computers to read text, hear speech, interpret
it, measure sentiment and determine which parts are important.
• Natural Language Processing is the driving force behind the following common applications:

a) Language translation applications such as Google Translate


b) Word Processors such as Microsoft Word and Grammatically that employ NLP to check grammatical
accuracy of texts.
c) Interactive Voice Response (IVR) applications used in call centers to respond to certain users’
requests.
d) Personal assistant applications such as OK Google, Siri and Alexa.

IMMERSIVE EXPERIENCE (AR, VR)


72
• An immersive experience is the perception of being in one place when you are actually in
another. It is essentially the suspension of reality, even if just for a few moments. People always
want the most immersive experience possible, especially when it comes to entertainment.
• Immersive experiences have been used in the field of training, such as driving simulators , flight
simulator and so on.

• Immersive experience can be achieved using virtual reality and augmented reality.
Augmented reality (AR):

• The superimposition of computer-generated perceptual information over the existing physical


surroundings is called as Augmented Reality (AR).
• It adds digital elements to a live view often by using the camera on a smartphone.
• Examples of augmented reality experiences include Snapchat lenses and the game Pokémon Go.

Imagine you want to buy a piece of furniture – a chair, for example. Augmented reality
technology can help you check how different chairs will look in your room and pick the one that
fits best.

Virtual reality (VR):

• It implies a complete immersion experience that shuts out the physical world.
• VirtualReality(VR) is a three-dimensional, computer generated situation that simulates the real
world.
• Theusercaninteractwithandexplorethatenvironmentbygettingimmersed in it while interacting with the
objects and other actions of the user.
• It is achieved with the help of VR Headsets.
• In order to make the experience of VR more realistic, it promotes other sensory information like
sound, smell, motion, temperature, etc.
• Application of Immersive experience:-
a) Retail and e-commerce
b) Art
c) Entertainment and
73
d) Videogames and
e) Interactive storytelling
f) Military
g) Education

Robotics
● A robot is basically a machine capable of carrying out one or more tasks automatically with accuracy and
precision.

● A robot is programmable.

● Used for doing repetitive industrial tasks that are boring or stressful for humans or were labor-intensive.

● Sensors are one of the prime components of a robot.

● Robot can be of many types, such as wheeled robots, legged robots, manipulators, and humanoids.

● Robots that resemble humans are known as humanoids.

● Robots are being used in industries, medical science, bionics, scientific research, military, etc.

● Some examples are:

• NASA’s Mars Exploration Rover (MER) mission is a robotic space mission to study about the planet
Mars.
• Sophia is a humanoid that uses artificial intelligence, visual data processing, facial recognition and
also imitates human gestures and facial expressions.

74
Big Data and its characteristics
• The term Big Data refers to a huge volume of data that cannot be stored processed by any traditional
data storage or processing units.
• Big Data is generated at a very large scale and it is being used by many multinational companies to
process and analyse in order to uncover insights and improve the business of many organizations.

Characteristics:

1. Volume: It refers to the unimaginable amounts of information generated every second from social
media, cell phones, cars, credit cards, M2M sensors, images, video, and whatnot.
2. Variety: Variety of Big Data refers to structured, unstructured, and semi structured data that is
gathered from multiple sources.
3. Value: It is actually the amount of valuable, reliable and trustworthy data that needs to be stored,
processed, and analyzed to find insights.
4. Velocity: provide data on demand and at a faster pace.
5. Veracity or Variability: It refers to the inconsistency which can be shown by the data many times,
thus hampering the process to handle and manage the data effectively.

Internet of Things (IoT)


The internet of things, or IoT, is a system of interrelated computing devices, mechanical and digital
machines, objects, people that are provided with unique identifiers (UIDs) and the ability to transfer data
over a network without requiring human-to-human or human-to-computer interaction.

IoT makes once "dumb" devices "smarter" by giving them the ability to send data over the internet, allowing
the device to communicate with people and other IoT-enabled things.

The connected "smart home" is a good example of IoT in action. Internet-enabled thermostats, doorbells,
smoke detectors and security alarms create a connected hub where data is shared between physical devices
and users can remotely control the "things" in that hub (i.e., adjusting temperature settings, unlocking doors,
etc.) via a mobile app or website.

75
For example, if a microwave oven, an air conditioner, door lock, CCTV camera or other such devices are
enabled to connect to the Internet, we can access and remotely control the mon-thego using our smart phone.

SENSORS:
• A smart sensor is a device that takes input from the physical environment and uses built-in
computing resources to perform predefined functions up on detection of specific input and then
process data before passing it on.
• Sensors are very commonly used for monitoring and observing elements in real world applications.
• Example: What happens when you hold your mobile vertically or horizontally? The display also
changes to vertical or horizontal with respect to the way we hold our mobile. This is possible with the
help of two sensors, namely accelerometer and gyroscope (gyro). The accelerometer sensor in the
mobile phones detects the orientation of the phone. The gyroscope sensors tracks rotation or twist of
your hand and add to the information supplied by the accelerometer.

Smart Cities

● The challenges like management of resources like and water, waste, air pollution, health and sanitation,
traffic congestions, public safety, and security etc. are forcing many city planners around the world to look
for smarter ways to manage the man make cities sustainable and liveable.

● Theideaofsmartcitymakesuseofcomputerandcommunicationtechnologyalong with IoT, WoT(Web of


Things) to manage and distribute resources efficiently.

76
● Example: The smart building uses sensors to detect earthquake tremors and then warn nearby buildings so
that they can prepare themselves accordingly.

Cloud Computing
● Computer-based services delivered over the Internet or the cloud, which can be accessed anywhere using
any smart device.

● The services comprises of software, hardware(servers),databases, storage, etc.

● These resources are provided by companies called cloud service providers and usually charge on pay per
use basis, like the way we pay for electricity usage.

● Cloud computing offers cost-effective, on-demand resources. A user can avail need-based resources from
the cloud at a very reasonable cost.

Cloud Services
Different computing services delivered through cloud are Infrastructure as a Service (IaaS), Platform as a
Service (PaaS), and Software as a Service(SaaS).

• Infrastructure as a Service(IaaS):The IaaS providers can offer different kinds of computing


infrastructure, such as servers, virtual machines (VM), storage and backup facility, network
components, operating systems or any other hardware or software.
• Platform as a Service (PaaS): Through this service, a user can install and execute an application
without worrying about the underlying infrastructure and their setup. That is, PaaS provides a
platform or environment to develop, test, and deliver software applications.
• Software as a Service(SaaS):SaaS provides on demand access to application software, usually
requiring a licensing or subscription by the user. While using Google doc, MicrosoftOffice365, Drop
Box, etc., to edit a document online, we use SaaS from cloud. A user is not concerned about
installation or configuration of the software application if the required software is accessible.

Grid Computing
● A grid is a computer network of geographically dispersed and heterogeneous computational resources.

● Unlike cloud, whose primary focus is to provide services, a grid is more application specific and
creates a sense of a virtual supercomputer with an enormous processing power and storage.

● The constituent resources are called nodes.

77
● These different nodes temporarily come together to solve a single large task and to reach ac ommon
goal.

● Grid can be of two types—

o Data grid, used to manage large and distributed data having the required multi-user access.

o CPU or Processor grid, where processing is moved from one PC to another as needed or a large task is
divided into subtasks and allotted to various nodes for parallel processing.

● The Globus toolkit is a software toolkit used for building grids, and it is as open source.

● It includes software for security, resource management, data management, communication, fault
detection, etc.

Blockchains
● Traditionally, we perform digital transactions by storing data in a centralized database and the
transactions performed are updated one by one on the database. That is how the ticket booking websites
or banks operate. However, since all the data is stored on a central location, there are chances of data
being hacked or lost.

● The block chain technology works on the concept of decentralized and shared database where each
computer has a copy of the database. A block can be thought as a secured chunk of data or valid
transaction

● Each block has some data called its header, which is visible to every other node, while only the owner
has access to the private data of the block. Such blocks form a chain called block chain.

● We can define block chain as a system that allows a group of connected computers to maintain a single
updated and secure ledger. Each computer or node that participates in the block chain receives a full
copy of the database.

● It maintains an ‘append only’ open ledger which is updated only after all the nodes within the network
authenticate the transaction. Safety and security of the transactions are ensured because all the members
in the network keep a copy of the block chain and so it is not possible for a single member of the

78
network to make changes or alter data. Popular application of block chains technology is in digital
currency.

Time to Practice
Multiple Choice Question

1. Virtual Reality have been used in the field of_________?


a) Military training
b) Psychology
c) Medical procedure
d) All of the above
2. The superimposition of computer-generated perceptual information over the existing physical
surroundings is called as _______________?
a) Immersive experiences
b) AR
c) VR
d) Robot
3. NASA’s Mars exploration ___________ mission is a robotic space mission to study about the planet
mars.
a) Rover
b) Sophia
c) Drone
d) None of the above
4. ____________ is a humanoid that uses AI , visual data processing, facial recognition and also
imitates human gestures and facial expressions.
a) Rover
b) Sophia
c) Drone
d) None of the above
5. Network of interconnected items with integrated sensors that can gather and transmit data in real time
is known as the __________?
a) Internet of things
b) Big data
c) Grid computing
d) None of the above
6. What are the different challenges in big data?
a) Integration
b) Storage
c) Analysis
d) All of the above
7. _____________ refers to the trustworthiness of the data because processing such incorrect data can
give wrong results or mislead the interpretations.
a) Volume
b) Velocity
c) Variety
d) Veracity
8. The ____________ sensor in the mobile phone detects the orientation of the phone.
a) Accelerometer
b) Gyroscope
79
c) Both a and b
d) None of the above
9. Where is AI used?
a) Training soldiers in combat using battlefield simulations
b) In self-driving cars that do not require a driver.
c) To allow access to buildings.
d) To create prototypes of cars or any other object.
10. Where is virtual reality used?
a) Training soldiers in combat using battlefield simulations
b) In 3-d films.
c) To allow access to buildings.
d) To create prototypes of cars or any other object.
11. Which of the following is not a feature of IoT devices?
a) Remotely controllable
b) Security
c) Can turn themselves off, if necessary.
d) Wearables.
12. Which of the following is a positive impact of AI in self-driving cars.
a) An immersive video experience for the viewer using special glasses.
b) Data is completely secure and cannot be tampered with.
c) Only authorized people can travel in car.
d) Safer transport as there are fewer road accidents.
13. Where is computer-assisted translation used in everyday life?
a) Training TV hosts.
b) Spell checkers used in word processing software.
c) Dictation tests.
d) Recording weather conditions.
14. What hardware is typically used for VR?
a) A powerful computer , headset with a screen to see, headphones to hear and sometimes
gloves.
b) Keyboard, mouse, printer and plotter
c) Smartphone, mic and tablet.
d) Plotters, mouse, speakers and tablet.
15. ____________ helps the user to install and execute an application without worrying about the
underlying infrastructure.
a) IaaS
b) PaaS
c) SaaS
d) None of the above
16. ___________ used to manage large and distributed data having required multiuser access.
a) Data grid
b) CPU grid
c) Both a and b
d) None of the above
17. The most popular application of blockchains technology is in ____________
a) Open office
b) Digital currency
c) GIMP
d) None of the above
18. ___________ allows us to visualize, feel and react by stimulating our senses.
80
a) Immersive experiences
b) AR
c) VR
d) None of the above
19. Example of ai?
a) Cortana
b) GoogleNow
c) Alexa
d) All of the above
20. ____________ deals with the interaction between human and computer using human spoken
languages such as hindi, English etc.
a) Data science
b) NLP
c) Nero science
d) None of the above
Very Short Answer Questions

1. List some of the cloud based services that you are using at present?

2. What is Artificial Intelligence?

3. What is a strong example of AI?

4. What is Machine Learning?

5. Explain NLP.

6. What is VR?

7. Write any 2 examples of AR?

8. Expand the following terms:

a) WoT
b) IoT
9. Explain grid computing.

10.Explain Block chain technology.

Short Answers Questions

1. Write short note on :


a) Cloud computing
b) Big data and its characteristics
2. How is IoT and WoT related?

3. Differentiate between cloud computing and grid computing with suitable examples.

4. Explain the use of sensors with example.

5. Differentiate between cloud computing and grid computing with suitable examples.

81
6. Which is not one of the features of loT devices?

7. MicrosoftOffice365 is an example of which type of cloud service model?

8. Justify the following statement-

‘Storage of data is cost effective and time saving in cloud computing.’

9. How IoT and WoT are related?

10. Explain the following along with their applications.

a) Artificial Intelligence b) Machine Learning

Long Answers- Questions

1. Write the significance of AI in today’s world?

2. Home Automation is a salient feature of IoT. Explain?

3. What is on-demand service? How it is provided in cloud computing?

4. Write examples of the following:

a) Government provided cloud computing platform

b) Large scale private cloud service providers and the services they provide

5. A company interested in cloud computing is looking for a provider who offers 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 customised applications. What type of cloud computing model fits these
requirements and why?

ASSERTION-REASONING QUESTIONS:

1. Assertion (A): The branch of AI that deals and works with natural languages, is NLP. Reasoning (R):
NLP helps computers understand, interpret and manipulate human languages and even generate
human-language responses.
2. Assertion (A): Blockchain technology is a decentralized, digitized, public ledger of online
transactions occurring among a network of peers.
Reasoning (R): Images of transaction’s paper receipts, compiled together is the new blockchain.
3. Assertion (A): NLP deals with interaction between human and computer systems using common and
frequently spoken languages like Hindi, English etc.
Reasoning (R): Spell-check feature is an implementation of NLP.
4. Assertion (A): It is difficult to store huge data using cloud computing.
Reasoning (R): Storage of data is cost effective and time-saving in cloud computing.
5. Assertion (A): Immersive experiences allow user to visualize , feel and react by stimulating their
senses.
Reasoning (R): Immersive experiences have been used in the field of medicine and communications.

82
CASE BASED/ COMPETENCY BASED QUESTIONS:

1. Five friends plan to try a startup. However, they have a limited budget and limited computer
infrastructure. How can they avail the benefits of cloud services to launch their startup?
2. Government provides various scholarships to students of different classes. Prepare a report on how
blockchain technology can be used to promote accountability, transparency, and efficiency in
distribution of scholarships?
3. If Government plans to make a smart school by applying IoT concepts, how can each of the
following be implemented in order to transform a school into IoT enabled smart school?
a) e-textbooks
b) Smart boards
c) Online tests
d) Wi-Fi sensors on classrooms doors
e) Sensors in buses to monitor their location
f) Wearables (watches or smart belts) for attendance monitoring
4. Suggest the technology which will be implemented to perform the following day-to-day tasks:
a) You get a reminder to take medication.
b) You get an SMS alert that you forgot to lock the door.
c) You get an SMS alert that parking space is available near your block.
d) You turn off your LED TV from your wristwatch.
5. Meghna has planned a start-up with her friends. However, she has a limited budget and limited
computer infrastructure. How can she avail the benefits of cloud services to launch their startup?

83
Sample Paper 1- (Solved)
Max Marks: 70 Time: 3 Hrs.

General Instructions:
This question paper contains Five Sections A, B, C, D, E
Section-A: Contains 1 Mark Question
Section -B: Contains 2 Mark Question
Section –C: Contains 3 Mark Question
Section –D: Contains three 5 Mark Case Study Based Questions
Section-E: Contains two 4 Mark Questions

SECTION-A

Q. Question Marks
No.

01. Predict the output of the following code: 1

2//3**2**1+99/11*(2+3)

02. Which one of the following is invalid identifier? 1

a) _abc
b) abc_10
c) 20_abc
d) _abc_
03. What is the output of code 45 % 3 ____________ 1

04. Which one is not a characteristic of Big-Data? 1

a) Volume
b) Variety
c) Velocity
d) Virtual
05. Predict the output of the following code: 1

10>20 and 15 < 20 or 20 < 11 and not 2 = = 2

06. Identify the type of data L= {2:2020,”2”:2021} 1

a) List
b) Tuple
c) Dictionary
d) Boolean

07. Which of the following function belongs to dictionary? 1

a) append()
b) isdigit()
84
c) items()
d) insert()
08. Name two DDL Commands? 1

09. Which command is used to change the datatype of a column in table? 1

(a) Rename
(b) Modify
(c) Drop
(d) Change
10. Which one of the following is wild card character used with LIKE operator? 1

(a) #
(b) @
(c) _
(d) ^
11. Which of the following command is used to remove the rows from a table? 1

(a) Delete
(b) Drop
(c) Kill
(d) Truncate
12. Which of the following command is used for update of record in a table? 1

(a) update table table_name set col_name


(b) update table_name col_name
(c) Insert into table_name set col_name
(d) Insert into table_name col_name
13. When a table cannot have its own primary key then it borrows primary key of 1
another table and is called __________________

14. IoT stands for: 1


a. Internet of Tools
b. Interconnection of Things
c. Internet of Task
d. Internet of Things

15. Name two output devices. 1

16. 4GB equals to _____________ MB. 1

Directions (Question 17 and Question 18): In the following questions, a statement of


Assertion (A) is followed by a statement of Reason (R). Choose appropriate answer
from the following as applicable to the question.

(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
17. Assertion: A database is a collection of unorganized data. 1

85
Reasoning: Data duplication is not encourage by Database

18. Assertion: Python is case sensitive language 1

Reasoning: Two variables with same name written in upper and lower letters are
treated as different variables.

SECTION-B

19. Define system Software? Name two Systems software’s. 2

20. Differentiate between Compiler and Interpreter 2

21. Name any four Application software? 2

22. Differentiate between RAM and ROM? 2

23 What is the purpose of get() and items() method of dictionary. 2

24. Define Domain and Relation in reference to Database. 2

25. Find the output of the following Code: 2

days=[1:”Sun”,2: [“Mon”, ”Tues”], 3:”Fri”}


print( days[2][1])
print(days[2])
SECTION C

26. Define SaaS, PaaS and IaaS? 3

Or

Define grid computing and its application.

27. Write a Program in Python to convert temperature given in Degree into Fahrenheit. 3

28. Write a program in python to find the average of marks for five subjects 3

29 Write the syntax/format of the below commands: 3


Delete, Insert,Alter-Drop

30. i. Which command is used to view the description of table. 1+2


ii. Ravi is using a table Employee with following columns:
Name, Subject , Department, Salary , Designation

He needs to display names of employees are in Computer Department and have


salary greater than 50000.
He wrote the following command, which did not give the desired result.

SELECT Name, From Employee WHERE Department is ‘Computer’ or Salary >


50000
Help him to run the query by removing the error and write correct query.

86
SECTION-D

31 A relation ‘Sports’ has the following attributes: 5

(Sports_ID, Name, No_Players, Filed_Type, Location )

a) Name the attribute which should be taken as the Primary Key?


b) Write a command to insert a single row in the table mentioned above.
(Assume appropriate values)

c) Write a command to change constraint of column Name to Not Null.


d) Write a command to add new column “Capacity” use appropriate datatype
e) Write command to update the value of Location to “India” where ID is 109
32. Create a dictionary of employees which stores emp_id, Salary and Designation for 5
5 employees and print the employee information whose salary is greater than 50000
Or
Consider the following dictionary:
name={1:”India”,2:‟australia‟,3:‟Japan‟,4:‟America‟,5:‟China‟}
Perform the below mentioned operations in the
dictionary:

a) Write command traverse a dictionary and print keys one by one


b) Write command to print values only.
c) Write command to add new element having key 6 and values as
“Ireland” .
d) Write command to change value of key 3 to “New Zealand”.
e) Write command to delete values Japan.
33. Consider the table ‘Student’ given below and write suitable SQL queries of the 5
following:
Table: Student
ID Name Class Subject Marks

1001 Bharti X Hindi 33

1002 Pratima XII NULL 22

1003 Savitri IX Computer 30

1004 Aashna X Biology 39

1005 Sunil XI English 34

i. Display the Name and marks of stduents whose name start with ‘a’
ii. Display name of all those students whose subject is Hindi.
iii. Display ID and Name all those students whose number of marks is in the
range of 30 to 40. (both values included )
iv. Display the details of all those students teachers who have not been
assigned any subject.
v. Display the details of all those students Class is either X or XI
SECTION-E

87
34. Write MySql command to create database and table with given structure 4

Database: Company
Table: Sales
Column Data Type Constraint
Item Character
ID Integer Primary Key
Quantity Integer Default
(use 0 as Default value)
Quarter Integer
35. The record of IT_Shop is stored in the following list as: 4

(Item_Name,Qty,sale of three quarters ,Balance)


IT_List = [‘Laptop’,200000 ,[35000,42000,85000],20000]
Write Python statements to retrieve the following information from the list IT_List:

i) Print the sale of 1st Quarter.


ii) add 30000 to sale of 3rd quarter.
iii) Change value from Laptop to Computer.
iv) print max from sales of three quarters.
or

Consider the following dictionary:


Alpha= {‘D’: ‘Delhi’, ‘K’: ‘Kite’, ‘T’: ‘Toy’, ‘B’: ‘Boy’}
Write Python statements for the following:
i) To insert (‘M’ : ‘Monkey’) in the dictionary.
ii) To return the value corresponding to the key ‘K’
iii) To return the length of the dictionary.
iv)To delete the item from the dictionary corresponding to the key ‘B’
Answers

SECTION-A
Q. No. Question Marks
01. 45.0 1
02. c) 20_abc 1
03. 0 1
04. Virtual 1
05. Predict the output of the following code: 1
False
06. Dictionary 1
07. items() 1

08. Create, Drop 1


09. Modify 1
10. _ 1
11. Drop 1
12. update table table_name set col_name 1
13. Foreign Key 1
14. Internet of Things 1

88
15. Speaker, Monitor 1
16. 4096 MB 1
Directions (Question 17 and Question 18): In the following questions, a statement
of Assertion (A) is followed by a statement of Reason (R). Choose appropriate
answer from the following as applicable to the question.

(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
17. (D) A is false but R is True 1
18. (A) Both A and R are true and R is the correct explanation for A 1
SECTION-B
19. System software is a type of computer program that is designed to run a 2
computer's hardware and application programs. If we think of the computer system
as a layered model, the system software is the interface between the hardware and
user applications.
Operating System, Device Driver
20. • Compiler: A compiler translates code from a high-level programming
language into machine code before the program runs.
• Interpreter: An interpreter translates code written in a high-level
programming language into machine code line-by-line as the code runs.

21. Ms-Word, MS-Paint, Adobe Acrobat, Google Chrome


22. RAM is memory that stores the data that you're currently working with, but it's
volatile, meaning that as soon as it loses power, that data disappears.
ROM refers to permanent memory. It's non-volatile, so when it loses power, the
data remains.
23 get() Returns the value for the given
key () Return the list with all dictionary keys with values

24. Domain It contains a set of basic values that an attribute can take.
Relation: It is a table with records(rows) and attributes(columns)
25. print( days[2][1]) Tues
print(days[2]) Mon, Tues

SECTION C
26. infrastructure-as-a-Service (IaaS). A set of raw IT resources offered to the user 3
by the cloud service provider. They can be used to virtualise an infrastructure, or
for resource-intensive projects — i.e. machine learning, big data, hosting, etc.
Platform-as-a-Service (PaaS). A platform that a provider offers to its customers
via the internet. It enables teams — especially developers — to build applications
and software on a solution without having to maintain it.
Software-as-a-Service (SaaS). This is the most popular cloud service. It is
software that runs on a provider’s infrastructure. The user pays for the licence, but
does not manage the data storage or physical hardware maintenance.

Or
Grid computing is a computing infrastructure that combines computer resources
spread over different geographical locations to achieve a common goal. All unused
resources on multiple computers are pooled together and made available for a
single task. Organizations use grid computing to perform large tasks or solve
complex problems that are difficult to do on a single computer.
89
The following are some common applications of grid computing.
Financial services, Gaming, Entertainment, Engineering
27. celsius = 47 3
fahrenheit = (celsius * 1.8) + 32
printing the result
print(“output”,fahrenheit))

28. print(“Enter marks of five subjects: “) 3


S1=float(input())
S2=float(input())
S3=float(input())
S4=float(input())
S5=float(input())
total = S1 + S2 + S3 + S4 + S5;
average = total/5.0;

print(“Average marks = “, average)


29 Delete from table name where condition 3
Insert into tablename values()
Alter table table_name drop column name

30. Describe Command 1+2

SELECT Name From Employee WHERE Department = ‘Computer’ and Salary


> 50000;
SECTION-D
31 A relation ‘Sports’ has the following attributes: 5
(Sports_ID, Name, No_Players, Filed_Type, Location )
a) Sports_ID,
b) Insert into Sports values (101,”Criciket”,”Round”,”India”)
c) alter table Sports Modify Name Char(100) Not Null
d) alter table Sports Add Capacity Integer
e) update sports set Location=”India” where id=109
32. emp={101:[20000:”Teacher”], 102:[10000:”Engineer”], 103:[25000:”Doctor”], 5
104:[30000:”Teacher”], 105:[34000:”Scientist”]}

for i in emp:
if emp[i][0]>50000:
print(i)
print(emp[i])
or
Consider the following dictionary:
name={1:”India”,2:‟australia‟,3:‟Japan‟,4:‟America‟,5:‟China‟}
Perform the below mentioned operations in the
dictionary:
i) Write command traverse a dictionary and print keys one by one
for i in name:
print(i)
ii) Write command to print values only.
print(name.values())
iii) Write command to add new element having key 6 and values as
90
“Ireland”
name[6]=”Ireland”
iv) Write command to change value of key 3 to “New
Zealand”
name[3]=”New Zealand”
v) write command to delete values Japan
del name[3]
33. Consider the table ‘Student’ given below and write suitable SQL queries of the 5
following:
Table: Student

ID Name Class Subject Marks


1001 Bharti X Hindi 33
1002 Pratima XII NULL 22
1003 Savitri IX Computer 30
1004 Aashna X Biology 39
1005 Sunil XI English 34

i. Select name,marks from student where name like ‘a%’;


ii. Select name from student where subject=”hindi”;
iii. Select ID,name from student where marks between 30 and 40;
iv. Select * from student where subject is NULL;
v. Select * from student where class =’x’ or class=’XI”;
SECTION-E
34. Create database Company 4
Use Company
Create table Sales (
Item Char(100) ,
ID Integer primary key,
Quantity Integer default= 0,
Quarter Integer )

35. 4
i) print(IT_List[2][0])
ii) IT_List[2][2]= IT_List[2][2]+30000
iii) IT_List[0]=”Computer”
iv) print(max(IT_List[2][0], IT_List[2][1], IT_List[2][2]))

or

Consider the following dictionary:


Alpha={‘D’: ‘Delhi’ , ‘K’ : ‘Kite’ , ‘T’ : ‘Toy’ , ‘B’ : ‘Boy’}
Write Python statements for the following:

i) Alpha[“M”]=”Monkey”
ii) print(Alpha[“K”])
iii) print(len(Alpha))
iv) del Alpha[“B”]

91
Unsolved Sample Paper – 1
Max Marks: 70 Time:3 hrs.

General Instructions:

This question paper contains Five Sections A, B, C, D, E


Section-A: Contains 1 Mark Question
Section -B: Contains 2 Mark Question
Section –C: Contains 3 Mark Question
Section –D: Contains three 5 Mark Case Study Based Questions
Section-E: Contains two 4 Mark Questions

Section-A
Q. Question Marks
No.
01. Predict the output of the following code: 1
2//2**2**2+99/11*(50-45)
02. Which one of the following is valid identifier? 1
a) @abc b)_abc c)20_abc d) else
03. What is the output of code 23 % 2 ____________ 1
04. A network of devices which communicate with one another on the same network 1
form:
(A)DBMS
(B)IoT
(C)SaaS
(D) NLP
05. Predict the output of the following code: 1
10>20 AND 5 < 20 OR 9 > 11 AND NOT 4==2
06. What is the output of following code: 1
print(type(30.0))
07. Which of the following function belongs to dictionary? 1
(a) append()
(b) isdigit()
(c) items()
(d) insert()
08. What is the difference between drop and delete? 1
09. Which command is used to change the structure of table in Database? 1
(a) Rename (b) Distinct (c) Alter (d) Update
10. Which one of the following is wild card character used with LIKE operator? 1
(a) % (b) @ (c) $ (d) #
11. Which of the following command is used to remove the entire table? 1
(a) Delete (b) Drop (c) Kill (d) Truncate
12. Which of the following keyword is used to avoid duplicate records? 1
(a) IS (b) NULL (c) DISTINCT (d) READ
13. Which of the Key is used to identify the records uniquely in a table? 1
(a) PRIMARY KEY (b) CANDIDATE KEY
(c) ALTERNATE KEY (d) FOREIGN KEY
14. What is a humanoid Robot? 1
15. What is the difference between primary key and unique constraint? 1
92
16. ____________Uniquely identifies a person on the basis of physical or behavioural 1
traits such as fingerprints, DNA etc.
a) Touch screen
b) Biometric sensor
c) Optical character reader
d) QR code
Directions (Question 17 and Question 18): In the following questions, a statement
of Assertion (A) is followed by a statement of Reason (R). Choose appropriate
answer from the following as applicable to the question.
(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
17. Assertion: A database can have only one table in MySql. 1
Reasoning: If a piece of data is stored in two places in the databases, then storage
space is wasted.
18. Assertion: Comments are executed by interpreter. 1
Reasoning: Comments are used to add a remark or a note in the source code.
SECTION-B
19. Differentiate between Application and System software. 2
20. Differentiate between Compiler and Interpreter. 2
21. Name any four operating systems? 2
22. What happens when data is deleted? 2
23 How many times world ‘Python’ will be printed in the following statement? 2
a = 'I am in Class 12'
for ch in s[3 : 8]:
print ("Python")
24. What is Difference between DDL and DML. 2
25. Find the output of the following Code: 2
Data=[34,45,67,[23,44],89,89]
print( Data[3])
print(Len(Data))

SECTION-C
26. Differentiate between cloud computing and grid computing with suitable 3
examples.
Or
Define Artificial Intelligence and list its various Subfields.
27. Write a program in python to find factorial of number. 3
28. To find sale price of an item with given cost and discount (%). 3
29 Categorize the below commands into DML and DDL: 3
Delete , Select, Alter, Drop, Update, ADD
30. i. Which command is used to see all the tables within a databases? 2+1

ii. Ajay is using a table Students with following columns:


Name, Class, Stream_Id, Stream_Name.

He needs to display names of students who have not been assigned any stream or
have been assigned Stream_Name that ends with ‘computers’.
He wrote the following command, which did not give the desired result.

SELECT Name, FROM Students WHERE stream_Name = NULL or


93
Stream_Name=’%computers’;

Help him to run the query by removing the error and write correct query.

SECTION-D
31 A relation ‘Order’ has the following attributes: 5
(Order_No, Order_Name, Order_date, Order_Qty, Order_price)

a)Write a command to insert a single row in the table mentioned above.


(Assume appropriate values)
b) Name the attribute which should be taken as the Primary Key?
c) Write a command to add new column “Order_Section” with character as data
type
d) Write command to delete the column Order_Date.
e) Write command to change the data type of Order_Price to Char from varchar.

32. Create a dictionary of students to store names and marks obtained in 5 subjects for 5
5 students and display name student whose average of marks is greater

Or
Consider the following dictionary: states={‘D’: ‘Delhi’ , ‘K’ : ‘Kerala’ , ‘T’ :
‘Tamil Nadu’ , ‘B’ : ‘Bihar’}
Write Python statements for the following:
a) To insert (‘M’ : ‘Mumbai’) in the dictionary states.
b) To return the value corresponding to the key ‘T’
c) To return the length of the dictionary states.
d) To delete the item from the dictionary corresponding to the key ‘K’
e) To delete the dictionary ‘states’
33. Consider the table ‘Teacher_Details’ given below and write suitable SQL queries 5
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 Hindi 29
1004 Aashna 2020-02-24 English 28

a) Display the T_Name and Num_of_Periods whose name end with a.


b) Display T_Name of all those teachers whose date of joining is after 1st Jan
2019.
c) 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 )
d) Display the details of all those teachers who have not assigned any subject.
e) Display the details of all those teachers whose subject is either Hindi or
Science;
SECTION-E
34. Write MySql command to create database and the table as per given structure 4
Database: Office
Table: Shop
Column Data Type Constraint
Shop_ID Integer Primary Key
Items Character
94
Owner_Name Character
Shop_Name Character NOT NULL

35. The record of salesman is stored in the following list as: 4


(Name, Item Sold, sale of three quarters , Commission)
Sale=[‘Amit’, ‘Laptop’, [35000,42000,85000], 20000]

Write Python statements to retrieve the following information from the list Sales:
i) Print the sale of 2nd Quarter.
ii) Add 56000 as sale of 4th quarter.
iii) Change value of product from Laptop to Tablet
iv) Delete Commission from the list

Or
Write a program to create a list of 10 elements (Integer Values) and print the
numbers which satisfy the equation : X + 2*3 =10 [X is element from list]

95
Unsolved Sample Paper 2
Max Marks: 70 Time:3 hrs.

General Instructions:

This question paper contains Five Sections A, B, C, D, E


Section -A: Contains 1 Mark Question
Section -B: Contains 2 Mark Question
Section -C: Contains 3 Mark Question
Section -D: Contains three 5 Mark Case Study Based Questions
Section -E: Contains two 4 Mark Questions

Section-A
Q. Question Marks
No.
01. Predict the output of the following code: 1
3//2*2**1+80/10*(2+3)
02. Which one of the following is valid identifier? 1
a) #abc b)IF c) if d) for
03. What is the output of code 15 // 7 ____________ 1
04. Which one these is not field of artificial intelligence. 1
i. Face recognition
ii. Voice recognition
iii. Web Designing
iv. Robotics
05. Predict the output of the following code: 1
25>20 or 15 < 20 and 20 < 11 and not 2>1
06. Predict the output: 1
marks=[20,30,40]
print(marks*2)
print(marks[1]*2)
07. Which of the following function belongs to list? 1
e) key()
f) items()
g) append()
h) clear()
08. Name two DML Commands . 1
09. Which command is used to change the datatype of a column in table? 1
(a) Rename (b) Modify (c) Drop (d) Change
10. Wildcard character % and _ are used with _____________ SQL clause . 1
11. Find the error in below command: 1
Select * from Student where marks = null
12. What is the difference between primary key and foreign key. 1
13. Write the command for showing all the tables within the database. 1
14. Define Term Big-Data. 1
15. Name two Input devices . 1
16. 8192 MB equals to _____________ GB. 1
Directions (Question 17 and Question 18): In the following questions, a
96
statement of Assertion (A) is followed by a statement of Reason (R). Choose
appropriate answer from the following as applicable to the question.

(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
17. Assertion: A record is collection of values assigned to attributes. 1
Reasoning: An attribute whose value is unique can be used as key.
18. Assertion: Python interpreter works in interactive and script mode. 1
Reasoning: Interpreter converts all code at once into machine code.
SECTION-B
19. Define system Application? Name two Application software’s. 2
20. Differentiate between Compiler and Interpreter. 2
21. Name any four Utility Software’s. 2
22. Differentiate between SRAM and DRAM? 2
23 What is the purpose of key() and clear() methods of a dictionary. 2
24. Define Degree and cardinality in reference to Database. 2
25. Find and underline the error: 2
abc==10
for x is Range(1,abc):
print(x)
SECTION-C
26. Define Grid computing and Block Chain Technology? 3
Or
What is Immersive Technology? Define AR and VR.
27. Write a Program in Python to calculate profit and loss given the cost and sale 3
price.
28. Write a program in python to count number of vowels in a given string 3
29 Write the syntax/format of the below commands: 3
Update, Select , Alter-Add
30. i. Which command is used to work on database. 1+2

ii. Sanya is using a table Shop with following columns:


Name, S_ID , Sales, Quarter ,Year

she needs to display names of articles for which sale is > 50000 in year 2020

she wrote the following command, which did not give the desired result.

SELECT Name From Shop WHERE year is 2020 and Sales > ‘50000’

Help her to run the query by removing the error and write correct query.
SECTION-D
31 A relation ‘Zoo’ has the following attributes: 5
(Z_ID, animal_Name, No_animals, Food_type, Location )
(a) Name the attribute which should be taken as the Primary Key?
(b) Write a command to insert a single row in the table mentioned above.
(c) (Assume appropriate values)
(d) Write a command to delete the record for which Location is ‘Upper
Area’.
(e) Write a command to add new column “Zookeeper” and use appropriate

97
datatype.
(f) Write command to update the value of animal_Name to ‘Cats’ where
ID is 120.
32. Write a program to create a dictionary with eid, name and salary of 5 of 5
employees and display names of employees who have got more than 25000
salary.
Or
Consider the following dictionary:
d={1:‟One‟,3:‟Three‟,5,‟Five‟,7:‟Seven‟,9:‟N
ine‟} Perform the below mentioned operations
in the dictionary:
(a) Write command traverse a dictionary and print key & values
(b) ii) Write command to print only values of dictionary.
(c) Write command to delete the second last element of
dictionary.
(d) Write command to delete all elements of the dictionary
(e) v) write command to add another element with key as
33 and value 23
33. Consider the table Company given below and write suitable SQL queries of 5
the following:
Table: Company
ID Name Skill Section Salary
1001 Ajay Medium HR 30000
1002 Vijay Basic Manufacturin 40000
g
1003 Waseem Basic Sales NULL
1004 Gazala Medium Sales 25000
1005 Surbhi Expert HR 30000
(a) Display the Name and salary of employees whose name end with ‘y’
(b) Display name of all employees whose section is ‘Sales’
(c) Display ID and Name all those students whose salary is in the range
of 25000 to 30000. (both values included )
(d) Display the details of all those employees whose skill is Medium
(e) Display the details of all those employees whose salary is not
mentioned
SECTION-E
34. Write MySql command to create database and the table as per given structure 4
Database: School
Table: Student
Column Data Type Constraint
Name Character
Subject Character
ID Integer Primary Key

Marks Integer Default


(use 0 as Default value)

35. Given a list named “Marks” write the statement for the following operations: 4
(a) To add another element in the list
(b) Find the find the length of the list
(c) To remove the last element from the list
98
(d) To reverse the list.

Or

Write a program to identify even numbers and odd numbers in a list, store
their sum separately and print the sum.

99
Unsolved Sample Paper 3
Max Marks: 70 Time: 3 Hrs.

General Instructions:
This question paper contains Five Sections A, B, C, D, E
Section-A: Contains 1 Mark Question
Section -B: Contains 2 Mark Question
Section –C: Contains 3 Mark Question
Section –D: Contains three 5 Mark Case Study Based Questions
Section-E: Contains two 4 Mark Questions

SECTION A
Q. No. Question Ma
rks
01. Predict the output of the following code: 1
10//2**2+70/10*(2+3)
02. An identifier name is allowed to have # symbol (True/False) 1
03. What is the output of code: 1
len( [20,[30,40]] )
04. Define virtual reality. 1
05. Predict the output of the following code: 1
25>20 and 25 < 30 or 18 < 10 or not 10>15
06. Predict the output: 1
days={1:”sun”,2:”Mon”,3:”Fri”}
print(days[1])
print(days. values() )
07. Find the output: 1
avg=[34,56,43,56,78]
avg.append(34)
avg.pop()
avg.pop()
print(avg)
08. Update and Delete are DML commands (True/False). 1
09. Which command is used to delete column in a table 1
(a) Rename (b) Modify (c) Drop (d) Change
10. What would following command do: 1
Select name, id from student where name is null and marks >100;
11. Find the error in below command: 1
Update teacher show id=200 where marks =500;
12. Define Database. 1
13. What is purpose of show command. 1
14. Define Term Grid Computing. 1
15. What is an impact printer. 1
16. Convert 4096 MB to GB. 1

100
Directions (Question 17 and Question 18): In the following questions, a statement of
Assertion (A) is followed by a statement of Reason (R). Choose appropriate answer from
the following as applicable to the question.

(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
17. Assertion: Foreign key is used when a table does not have its own primary key. 1
Reasoning: Foreign key does same work as primary key.
18. Assertion: variable names whether in capital or small letters are treated as different 1
python.
Reasoning: Python is a case sensitive language.
SECTION B
19. Define Operating System. Name two operating systems. 2
20. Differentiate between Compiler and Interpreter . 2
21. ROM and RAM Stands for ____________________, ____________________, 2
22. Name two Application software’s. 2
23 Name four built in functions of Dictionary. 2
24. Rewrite the query after removing errors: 2
Delete from student where student name = ‘%D’ and mark is 200.
25. Find and underline the error: 2
IF x > 20
print(x)
else:
print(X-20)
SECTION C
26. Define Cloud Computing and name various cloud service models 3
Or
What is NLP? List its applications.
27. Write a Program in Python to calculate perimeter of a rectangle. 3
28. Write a program in python to print only prime numbers from the given list. 3
29 Define DDL and DML? List one command of each. 3
30. A relation “School” has the following attributes: 3
(S_ID, Name, Class_Rooms, Reg_No )
(a) Name the attribute which can be used a Key?
(b) Write a command to add new column location.
(c) Write a command to delete column Class_rooms

SECTION-D
31 Consider the table Cricket given below and write the output of SQL queries give below: 5
Table: Cricket
ID Name Position Type Avg
1001 Anil Opener All-Rounder 34
1002 Rishabh Middle Order Bastman 40
1003 Ramesh One Down All-Rounder 43
1004 Javaid Opener Batsman 42
101
1005 Aadil Two Down Batsman 39
(a) Select name,position from cricket where type=’Batsman’;
(b) Select Avg from cricket where Avg in (40,34);
(c) Select id, Type from cricket where name like ‘%s%’;
(d) Select * from cricket where type=’All-Rounder’ and avg=43;
(e) Select position, id from cricket where avg between 40 and 43;
32. Write a program to create a dictionary with Shop_Id, Name and Location of 5 shops and 5
display location of shops who have items “soap”
Or
a.) Explain working of while loop with example.
b.) Define the Following:
update(), del , clear()
33. Consider the table Electronics given below and write suitable SQL queries of the 5
following:
Table: Electronics
ID Name Quantity Price Sales
1001 TV 300 20000 100
1002 Mobiles 140 18000 20
1003 IPads 240 21000 160
1004 Music Player 123 NULL 110
1005 Play Station 7 40000 3
(a) Display the Name of items for which sales is greater than 120 .
(b) Display name, quantity of all items whose price is in range 15000 and 20000 .
(c) Display sales and price of items for which name end with s .
(d) Display the all details of items for which quantity is less than 10.
(e) Display details all details of items for which price is null.
SECTION E
34. Write sql commands to create database and table with given structure : 4
Database : Shops
Table: Show_room
Column Data Type Constraint
Id Integer Primary Key
Name Character
Item_Type Character NOT NULL
Quantity Integer
35. Given a list named “School” write the statement for the following operations: 4
(a) To add another element in the list
(b) Find the find the no of occurrences of element 105 in the list
(c) To delete the element at last position
(d) To sort the list in ascending order

Or
Write a program to create a list of 10 elements (Integer Values) and print the average
of even elements only

102
Link to CBSE Syllabus of Class XI IP :
https://cbseacademic.nic.in/web_material/CurriculumMain25/SrSec/Informatics_Practic
es_SrSec_2024-25.pdf

Multimedia links for Class XI IP :


• https://nabhacantt.kvs.ac.in/sites/default/files/Class_XI_IP_NCERT.pdf
• https://ncert.nic.in/textbook/pdf/keip101.pdf
• https://ncert.nic.in/textbook/pdf/keip102.pdf
• http://python.mykvs.in/presentation.php
• https://www.magnetbrains.com/course/class-11th-informatics-practices-065-book-
full-video-course/
• https://www.youtube.com/watch?v=KWI0F_bN8AU
• https://www.youtube.com/watch?v=NE5ItNKxLi0
• https://www.youtube.com/watch?v=QCmUl3U8_t8
• https://www.youtube.com/watch?v=meVdWsl47rs

Best of Luck

103

You might also like