0% found this document useful (0 votes)
60 views

11_IP_Study_Material

GRADE 11 IP STUDY MATERIAL WITH SAMPLE PAPERS
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

11_IP_Study_Material

GRADE 11 IP STUDY MATERIAL WITH SAMPLE PAPERS
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

Grade - XI

INFORMATICS PRACTICES
INDEX
S.NO. TOPIC PAGES

1 Fundamental of Computer 4-17

2 Python Fundamentals 18-37

3 List and Operations 38- 44

4 Dictionary 45- 64

5 Database Concepts 65-74

6 Structured Query Language 75-101

7 Artificial Intelligence 102-118

8 Sample Papers 118-149

3 | Page
Introduction to computer and computing
This topic covers the fundamental concepts and components of computers, as well as an overview of
computing history and basic terminology. Here are some key points to consider:
Definition of a Computer: A computer is an electronic device that processes data and performs
various tasks according to a set of instructions (programs).
Basic Components of a Computer:

● Central Processing Unit (CPU): The brain of the computer, responsible for executing
instructions and performing calculations.
● Memory (RAM): Temporary storage for data and programs that are actively being used.
● Storage Devices: Hard drives, solid-state drives, and other media for long-term data storage.
● Input Devices: Keyboards, mice, touch screens, etc., used to input data and commands.
● Output Devices: Monitors, printers, speakers, etc., used to display or present data.

Data Representation:
Computers use binary (base-2) numbering system to represent and process data, using 0s and 1s.
Software vs. Hardware:
Software: Programs, applications, and operating systems that provide instructions for the hardware
to follow.
Hardware: Physical components of a computer system.
Types of Computers:
Personal Computers (PCs): Used by individuals for general purposes, such as desktops and laptops.
Servers: Computers that provide services to other computers or devices over a network.

4 | Page
Mainframes: Powerful computers used for large-scale data processing and critical applications.
Supercomputers: Extremely powerful computers used for complex scientific calculations.
History of Computing:
The history of computing dates back to ancient devices like the abacus, and it progressed through
various mechanical and electronic inventions.
Notable figures include Charles Babbage (conceptualized the Analytical Engine) and Alan Turing
(pioneered theoretical computer science).
Operating Systems:
Software that manages computer hardware and provides services for software applications.
Examples include Windows, macOS, and Linux.
Networking and the Internet:
Computers can connect to each other via networks, and the Internet is a global network that allows
communication and data exchange.
Ethical and Social Considerations:
Computers and computing have significant ethical and societal impacts, ranging from privacy
concerns to job automation.
Evolution of Computing Devices:
Pre-Modern Computing Devices:
Early tools like the abacus and counting boards were used for basic arithmetic.
The Antikythera mechanism (ancient Greek) is considered one of the earliest analog computers for
astronomical calculations.
Mechanical Calculators:
Blaise Pascal's Pascaline (17th century) and Gottfried Wilhelm Leibniz's Stepped Reckoner
introduced mechanical calculating mechanisms.
Analog Computers:
Developed in the 20th century, these devices used continuous physical quantities to perform
calculations.
Differential analyzers and slide rules were common examples.
GENERATION OF COMPUTERS
First Generation Computers (1940s-1950s):
● Used vacuum tubes for processing.
● ENIAC and UNIVAC were early examples.

5 | Page
● Large, expensive, and consumed a lot of power.

Second Generation Computers (1950s-1960s):


● Transistors replaced vacuum tubes, leading to smaller and more reliable computers.
● IBM 1401 and IBM 7090 were prominent second-generation machines.

Third Generation Computers (1960s-1970s):


● Integrated circuits allowed even smaller and faster computers.
● IBM System/360 series marked a significant advancement.

Fourth Generation Computers (1970s-1980s):


● Microprocessors brought computing power to small form factors.
● Altair 8800 and IBM Personal Computer (PC) were notable.
● Fifth Generation Computers (1980s-Present):
● Focus on parallel processing, AI, and advanced technologies.
● Supercomputers like Cray-1 and modern PCs fall into this category.

Fivth Generation Computers (1970s-1980s):


● Huge development of storage
● Multi -processor based system
● Use of AI
● More powerful micro and macro system
● Use of optical fibre in circuits

Components of a Computer System:


Central Processing Unit (CPU):
● The "brain" of the computer that executes instructions.
● Comprised of the control unit and the arithmetic logic unit (ALU).

Memory:
● RAM (Random Access Memory): Temporary storage for active programs and data.
● ROM (Read-Only Memory): Permanent storage for firmware and system software.

Storage Devices:
Hard Disk Drives (HDDs) and Solid State Drives (SSDs) store data and programs.
Optical drives (CD, DVD, Blu-ray) for reading and writing optical discs.

Input Devices:

6 | Page
● Keyboard, mouse, touchpad, touchscreen, microphone, etc.
● Convert user input into digital signals for the computer.

Output Devices:
● Monitor, printer, speakers, etc.
● Display or present information from the computer to the user.

Motherboard:
● Main circuit board connecting all components.
● Contains CPU socket, RAM slots, and connectors for other peripherals.
● Expansion Cards:
● Graphics cards, sound cards, network cards, etc.
● Enhance the capabilities of the computer.

Interconnections:
Buses:
● Data Bus: Transfers data between components.
● Address Bus: Specifies memory locations.
● Control Bus: Manages communication and control signals.

Ports and Connectors:


● USB, HDMI, Ethernet, audio jacks, etc.
● Allow connection to external devices and networks.

Networking:
● Ethernet and Wi-Fi enable communication between computers.
● Routers and switches manage data traffic.

Operating System (OS):


● Software that manages hardware resources and provides a user interface.
● Coordinates communication between components.

Software:
● Applications, utilities, and programs run on the hardware.
● Interact with users and perform tasks.

Input Devices:

7 | Page
Keyboard:
● Allows users to input alphanumeric characters and special symbols.
● Used for text entry, commands, and data manipulation.

Mouse:
● Enables pointing, clicking, and dragging on the screen.
● Used for navigating graphical user interfaces and selecting objects.

Touchscreen:
● Detects touch gestures directly on the screen.
● Common in smartphones, tablets, and some laptops.

Trackpad/Touchpad:
● A touch-sensitive pad used for cursor control and gestures.
● Found on laptops and some desktop keyboards.

Graphic Tablet:
● Used by artists and designers to draw directly on a pad with a stylus.
● Offers precise control for digital art and graphic design.

Scanner:
● Converts physical documents or images into digital format.
● Useful for archiving, sharing, and editing printed content.

Microphone:
● Captures audio input, allowing voice recognition and communication.
● Used for voice commands, calls, and recording.

Webcam:
● Captures video input for video conferencing, streaming, and recording.

Barcode Reader/Scanner:
● Reads barcodes for inventory management and retail operations.
● Quick and accurate data entry.

Biometric Sensors:
● Fingerprint, facial recognition, and iris scanners for secure authentication.

8 | Page
Joystick and Game Controllers:
● Used in gaming and simulation applications for precise control.

Output Devices:
Monitor/Display:
● Visual output device that presents text, images, and videos.
● Various types include LED, LCD, OLED, and CRT monitors.

Printer:
● Produces hard copies of digital documents and images.
● Types include inkjet, laser, dot matrix, and 3D printers.

Speaker and Headphones:


● Output audio for sound effects, music, and communication.
● Essential for multimedia experiences and communication.

Projector:
● Displays computer output on a larger screen or surface.
● Used for presentations, movies, and classroom teaching.

Plotters:
● Precise output devices used to draw graphics, schematics, and technical drawings.

Computer Memory: Units of memory, types of memory – primary and secondary, data deletion, its
recovery and related security concerns
Units of Memory:
1. Bit (Binary Digit):The smallest unit of digital data, representing either 0 or 1.
2. Byte: A group of 8 bits. Used to represent a character, such as a letter or number.
3. Kilobyte (KB): 1,024 bytes. Commonly used for measuring small amounts of data.
4. Megabyte (MB): 1,024 KB or 1,048,576 bytes. Used for larger data storage and file sizes.
5. Gigabyte (GB): 1,024 MB or 1,073,741,824 bytes.Used for measuring storage capacity of
devices and files.
6. Terabyte (TB): 1,024 GB or 1,099,511,627,776 bytes. Commonly used for describing storage
capacity of hard drives.
7. Petabyte (PB): 1,024 TB or 1,125,899,906,842,624 bytes. Used for large-scale data storage,
especially in data centers.
8. Exabyte (EB): 1,024 PB or 1,152,921,504,606,846,976 bytes. Relevant in contexts of massive
data and cloud storage.

9 | Page
Types of Memory:
1. Primary Memory (Main Memory):
a. Random Access Memory (RAM):
Volatile memory used for active programs and data.
Fast access speeds but temporary storage.
Cleared upon power loss or restart.
b. Read-Only Memory (ROM):
Non-volatile memory containing firmware and system instructions.
Retains data even after power loss.
c. Cache Memory:
Small, high-speed memory used to store frequently accessed data.
Speeds up CPU operations by reducing memory access time.
2. Secondary Memory (Storage):
a. Hard Disk Drives (HDD):

Non-volatile storage using spinning disks and magnetic read/write heads.


High capacity but slower access compared to RAM.
b. Solid State Drives (SSD):

Non-volatile storage using flash memory chips.


Faster access, lower power consumption, and more durable than HDDs.
c. Optical Storage (CD, DVD, Blu-ray):
Uses lasers to read and write data on optical discs.
Read-only or rewritable formats.
d. USB Drives and Memory Cards:

Portable and convenient storage using flash memory.


Widely used for data transfer and backup.
e. Cloud Storage:

Data stored remotely on servers accessible over the Internet.


Examples include Google Drive, Dropbox, and iCloud.

10 | Page
Data Deletion, Recovery, and Security Concerns:
Data Deletion: Deleting files often involves marking storage sectors as available, making data
seemingly inaccessible. Operating systems use mechanisms like "Trash" or "Recycle Bin" to hold
deleted files temporarily.
Data Recovery:
Deleted data can be recovered using specialized software until the sectors are overwritten.
Data recovery services may be able to retrieve lost data in some cases.
Security Concerns:
Inadequate data deletion can lead to data breaches and privacy violations.
Sensitive information must be securely wiped using data destruction methods to prevent recovery.
Encryption helps protect data even if storage devices are compromised.
Data Encryption:
Encrypting data renders it unreadable without the appropriate decryption key.
Provides an additional layer of security for stored and transmitted data.
Backup and Redundancy: Regular data backup ensures recovery from accidental deletion, hardware
failure, or cyberattacks.
Redundancy strategies help maintain data integrity and availability.
Software Definition:
Software refers to the collection of instructions, programs, and data that enable a computer to
perform tasks and accomplish specific functions.
Purpose of Software:
Software serves as the bridge between users and hardware, enabling them to interact with and
utilize computer systems effectively.
Types of Software:
1. System Software:
a. Operating System (OS): Manages hardware resources, provides user interfaces, and
facilitates communication between software and hardware.
Examples include Windows, macOS, Linux.
b. Device Drivers: Enable communication between hardware devices and the operating
system. Ensure proper functioning and compatibility of hardware components.
c. Utility Software: Tools for managing and optimizing system resources, file management,
data backup, and security. Examples include antivirus programs, disk cleanup utilities,
and file compression tools.

11 | Page
2. Application Software:
a. General-Purpose Software: Software designed to perform a wide range of tasks and
cater to various user needs. Examples include word processors, spreadsheets, web
browsers.
b. Specific-Purpose Software: Designed to fulfill a particular set of tasks or address specific
industry needs. Examples include graphic design software (Adobe Photoshop), video
editing software (Final Cut Pro), and CAD software (AutoCAD).

Generic and Specific Purpose Software:


Generic-Purpose Software: Designed to be versatile and suitable for a broad range of tasks.
Often used for personal and business applications. Provides flexibility to perform various functions
within a single software package.
Examples: Microsoft Office (Word, Excel, PowerPoint), web browsers (Chrome, Firefox).
Specific-Purpose Software: Tailored to fulfill specialized tasks or requirements of a specific
industry or domain. Offers advanced features and tools for specialized tasks. May have a steeper
learning curve due to its targeted nature.
Examples: AutoCAD (architecture and engineering), MATLAB (scientific computing), QuickBooks
(accounting).
Difference between impact and non-impact Printers

Aspect Impact Printers Non-Impact Printers


Physically strike paper for Apply ink/toner without
Mechanism
printing impact
Noise Noisy operation Quieter operation
Print Quality Lower print quality Higher print quality
Speed Slower printing speed Faster printing speed
Types Dot Matrix, Daisy Wheel Laser, Inkjet, Thermal
Documents, graphics,
Uses Multipart forms, invoices, copies
photos
Can print multiple copies,
Advantages High print quality, versatility
durability
Disadvantages Noisy, lower print quality, slower Limited for multiple copies

12 | Page
LET’S PRACTICE
Multiple Choice questions

1. Which of the following accurately describes the evolution of computing devices?


a. Computing devices have consistently increased in size and weight over time.
b. The evolution of computing devices has followed a linear path without significant
changes
c. Early computing devices were mechanical, followed by vacuum tubes,
transistors, and integrated circuits.
d. The evolution of computing devices has only been driven by hardware
advancements.
2. What are the components of a computer system and how are they interconnected?
a. Computer components are isolated units with no interconnections.
b. Components include only the monitor, keyboard, and mouse, which are
interconnected wirelessly.
c. Components such as CPU, memory, storage, and input/output devices are
interconnected through buses or channels.
d. Components of a computer system do not require any interconnections.
3. Which of the following is a primary input device?
a. Printer
b. Monitor
c. Keyboard
d. Speaker
4. Which unit is used to measure computer memory?
a. Hertz
b. Volt
c. Byte
d. Kilogram
5. What is the main difference between primary and secondary memory?
a. Primary memory is slower than secondary memory.
b. Secondary memory is volatile, while primary memory is non-volatile.
c. Primary memory is used for long-term storage, while secondary memory is used
for temporary storage.
d. Primary memory is directly accessible by the CPU, while secondary memory is
not directly accessible.
6. Which type of software is responsible for managing hardware resources and providing
essential functionalities?
a. Application software
b. Generic purpose software
c. Specific purpose software
d. System software
7. What is the purpose of system software?
a. Creating documents, presentations, and spreadsheets.
b. Playing video games and multimedia applications.

13 | Page
c. Managing computer hardware and providing a platform for other software to
run.
d. Designing graphics and illustrations.
8. Which type of software is designed for a particular task or industry?
a. Application software
b. System software
c. Utility software
d. Firmware
9. What are the potential security concerns related to data deletion and recovery?
a. There are no security concerns related to data deletion and recovery.
b. Data recovery is always a straightforward process and does not involve security
risks.
c. Deleted data can be recovered using specialized tools, posing a risk if not
properly managed.
d. Data recovery is impossible, eliminating security concerns.
10. What is the term used for software that is designed to perform a specific task for a
particular user or organization?
a. General-purpose software
b. Commercial software
c. Specific-purpose software
d. Freeware

Answers to Multiple Choice Questions:


Question 1: C) Early computing devices were mechanical, followed by vacuum tubes, transistors, and
integrated circuits.
Question 2: C) Components such as CPU, memory, storage, and input/output devices are
interconnected through buses or channels.
Question 3: C) Keyboard
Question 4: C) Byte (B)
Question 5: D) Primary memory is directly accessible by the CPU, while secondary memory is not
directly accessible.
Question 6: D) System software
Question 7: C) Managing computer hardware and providing a platform for other software to run.
Question 8: A) Application software
Question 9: C) Deleted data can be recovered using specialized tools, posing a risk if not properly
managed.
Question 10: C) Specific-purpose software

14 | Page
One Line Questions:

Question: What is the evolution path of computing devices?


Answer: From mechanical devices to vacuum tubes, transistors, and integrated circuits.
Question: How are components of a computer system interconnected?
Answer: Components are interconnected through buses or channels.
Question: What are input/output devices in a computer system?
Answer: Input devices (e.g., keyboard) allow data entry, while output devices (e.g., monitor) display
information.
Question: What is the unit of measurement for computer memory?
Answer: Byte (B).
Question: Differentiate between primary and secondary memory.
Answer: Primary memory is directly accessible by the CPU, while secondary memory is not directly
accessible.
Question: What are the security concerns related to data deletion and recovery?
Answer: Deleted data can be recovered, posing a security risk if not managed properly.
Question: What is the purpose of system software?
Answer: Managing hardware resources and providing a platform for other software.
Question: Define application software.
Answer: Software designed for specific tasks, such as word processing or photo editing.
Question: What is the difference between generic and specific purpose software?
Answer: Generic software serves general needs, while specific-purpose software targets particular
tasks or industries.

15 | Page
Short Answer Questions:

Question: Explain the evolution of computing devices and their impact on modern technology.

Answer: The evolution of computing devices has been marked by significant advancements, from
early mechanical calculators to the integration of transistors and microprocessors. This progression
has led to the development of faster, smaller, and more powerful computers that have revolutionized
various industries. These devices have become an essential part of our daily lives, enabling tasks that
were previously unimaginable.

Question: Describe the components of a computer system and how they are interconnected to
enable its functionality.

Answer: A computer system consists of several interconnected components that work together to
perform various tasks. These components include the central processing unit (CPU), memory, storage
devices, input/output devices, and more. Interconnections are established through buses and
channels, allowing seamless communication between the components. For instance, the CPU
processes instructions stored in memory and interacts with input devices like keyboards or mice to
perform user actions, ultimately displaying outcomes on output devices such as monitors.

Question: Elaborate on the concept of computer memory, including primary and secondary
memory, and their roles within a computer system.

Answer: Computer memory refers to the storage capacity used by a computer to temporarily or
permanently store data and instructions. Primary memory, also known as RAM (Random Access
Memory), is a volatile form of memory that provides fast access to data for the CPU. It stores active
programs and data currently in use. Secondary memory, on the other hand, includes non-volatile
storage devices like hard drives and solid-state drives (SSDs), used for long-term data storage. Unlike
primary memory, secondary memory retains data even when the computer is powered off.

Question: Discuss data deletion, recovery, and the associated security concerns in the context of
computer memory.

Answer: Data deletion involves removing files or information from storage devices. However, even
after deletion, traces of data may remain, making recovery possible through specialized software.
While data recovery can be beneficial for accidental data loss, it also poses security concerns. Sensitive
information might fall into the wrong hands if not properly managed. To mitigate these risks, secure
deletion methods and data encryption are recommended to ensure that recovered data remains
inaccessible to unauthorized users.

16 | Page
Question: Define software and explore the different categories, such as system software and
application software.

Answer: Software refers to the collection of programs, instructions, and data that enable a computer
to perform various tasks. System software is essential for managing hardware resources, providing a
platform for other software, and ensuring the overall functionality of the computer. Examples include
operating systems and device drivers. Application software, on the other hand, serves specific user
needs and includes programs like word processors, graphics editors, and web browsers.

Question: Differentiate between generic and specific purpose software, highlighting their
respective roles and importance.

Answer: Generic purpose software, also known as general-purpose software, is designed to cater to
common tasks applicable to a wide range of users. It includes software like office suites and web
browsers that fulfill general needs. Specific-purpose software, however, is tailored for particular tasks
or industries. This software addresses unique requirements and can range from specialized scientific
simulations to industry-specific design tools. The distinction allows users to choose software that best
matches their specific needs and enhances their efficiency.

Question: Distinguish between primary memory and secondary memory in terms of functionality
and accessibility.

Answer: Primary memory (RAM) provides fast access to data for the CPU but is volatile and temporary,
while secondary memory (hard drives, SSDs) offers non-volatile storage for long-term data retention
but with slower access speeds.

Question: How does system software differ from application software in terms of their roles within
a computer system?

Answer: System software manages hardware resources and provides a platform for other software to
run, ensuring the computer's overall functionality, while application software serves specific user
tasks or functions.

17 | Page
PYTHON >>>

⮚ Python is an object-oriented, high-level programming language.


⮚ Object-oriented means this language is based around objects (such as data) rather than
functions, and high-level means it's easy for humans to understand.
⮚ Python developed by Guido van Rossum in 1991
⮚ Python is an interpreted language, meaning that it does not require a separate compilation
step before executing the code. Instead, the Python interpreter directly reads and executes
the source code line by line.
⮚ Python is a case-sensitive language. Uppercase or capital and lowercase or small letters are
different.
⮚ Python prompt: >>>
⮚ Python program/script/file extension: .py
⮚ IDLE is Python’s Integrated Development and Learning Environment i.e. Python default
software or interface to write programs

Execution Modes
There are two ways to run a program using the Python interpreter:
a) INTERACTIVE MODE – Also, known as Shell Window
b) SCRIPT MODE – Also, known as Editor Window. (A script is a file containing source code /
program – a set of instructions)
Structure of a Program
● Expressions - A sequence of operands and operators, like a + b - 5, is called an expression. In
Python, operators are special symbols that designate that some sort of computation should
be performed. The values that an operator acts on are called operands.
● Statements - A statement is a programming instruction that does something i.e. some action
takes place. A statement executes and may or may not result in a value. E.g. print(x + 2), y = x
+ 5, x = 10
● Comments - Comments are the additional readable information to clarify the source code.
Comments in Python are the non-executable statements which begin with a hash symbol (#)
and generally end with end of the line. E.g. #This is a comment
● Function - A function is a code that has a name and it can be reused (executed again) by
specifying its name in the program, where needed.
● Blocks & indentation - A group of statements which are part of another statement or a function
are called block or code-block or suite in python. Indentation is used to show blocks in python.
Four spaces together mark the next indent-level.

18 | Page
IDENTIFIERS are names used to identify a variable, function, or other entities in a program.
The rules for naming an identifier in Python are as follows:
● The name should begin with an uppercase or a lowercase alphabet or an underscore sign
(_). This may be followed by any combination of characters a-z, A-Z, 0-9 or underscore (_).
Thus, an identifier cannot start with a digit.
● It can be of any length. (However, it is preferred to keep it short and meaningful).
● It should not be a keyword or reserved word.
● We cannot use special symbols like !, @, #, $, %, etc. in identifiers.

Constant – Value unable to change (Fixed Value).


Variable – Value able to change or vary.

⮚ Immutable Built-in Data Types - that does not allow you to change their value or data
● Numbers
● Booleans
● Strings
● Tuples
⮚ Mutable Built-in Data Types - that allow you to change their value or data
● Lists
● Dictionaries
● Sets

To accept user input – input() function.By default, it stores data in string format.

19 | Page
To get output – print() function. By default, sep parameter is whitespace and end parameter is new
line.
Datatype conversion or type casting – To convert one datatype into another datatype.
int() – to convert into integer
str() – to convert into string
float() – to convert into floating-point or decimal number

ARITHMETIC OPERATORS RELATIONAL OPERATORS LOGICAL OPERATORS


Returns True if both
+ Addition < Less than and
conditions are True
Returns True if either
- Subtraction > Greater than or
one condition is True
Complements result, if
* Multiplication <= Less than or equal to not True then False or vice-
versa
Greater than or equal
/ Division >=
to
// Floor Division == Equal to
% Modulus != Not Equal to
** Exponential
ASSIGNMENT OPERATORS MEMBERSHIP OPERATORS IDENTITY OPERATORS
Assign value of right To check if a
= side of expression to left in character/ is That determine
side operand substring/ element whether the given
exists in a sequence operands have the
Add right side operand or not. Evaluate to same identity—that
with left side operand
+= not in True if it finds or is not is, refer to the same
and then assign to left
False, if it does not object.
operand
finds it
Similarly, -= *= /= %= //= **=

20 | Page
Precedence of Operators

Debugging – To remove errors from a program.

If-else Condition While Loop For Loop

21 | Page
LET’S PRACTICE
Multiple Choice Questions (MCQ)
Q1. Which of the following is syntactically correct text?
a) “This is great!”
b) ‘she shouted ‘HELLO’ loudly’
c) “Goodbye’
d) “This “course” is good”

Q2. Python language is …………………………………


a) Free
b) Open Source
c) Free and Open Source
d) Proprietary

Q3. Identify the correct print() statement:


a) print(Hello)
b) print(“Hello”)
c) print(‘Hello”)
d) print(“Hello’)

Q4. Single-line comments in Python begin with ……………… symbol.


a) %
b) “
c) ‘’’
d) #

Q5. Python is a case-sensitive language. This means …………………………………


a) Capital and small letters are same for Python
b) Python doesn’t care about the case of alphabets
c) Python treats capital and small letters as different
d) Python automatically capitalized the small letters

Q6. Which of the following are not the fundamental building blocks of a Python program?
a) Identifiers
b) Constants
c) Keywords
d) Errors

22 | Page
Q7. Identifier name cannot be composed of special characters other than ………………………..
a) #
b) Hyphen (-)
c) $
d) Underscore (_)

Q8. What is the order of precedence of arithmetic operators given below in Python?
1. Division 2. Exponential 3. Subtraction 4. Parenthesis 5. Addition 6. Multiplication
a) 1,2,3,4,5,6
b) 2,3,4,5,6,1
c) 4,3,2,6,1,5
d) 4,2,6,1,5,3

Q9. What will be the output of the following snippet?


x, y = 2, 6
x, y = y, x + 2
print(x, y)
a) 6 4
b) 4 4
c) 4 6
d) 6 6

Q10. Which of the following is an invalid statement?


a) a=b=c=20
b) a,b,c = 10,20,30
c) abc = 20 30 40
d) a_b_c = 20

Q11. Write the output of the following:


print(range(0,8,2))
a) 0,2,4,6
b) range(0,8,2)
c) Error
d) None of the above

Q12. Write the output of the following:


x=2
x=5
x=x+x
print(x)
a) 7 b) 4 c) 10 d) Error

23 | Page
Q13. Each statement in Python is terminated by ………………………………
a) Semicolon(;)
b) Colon(:)
c) Comma(,)
d) None of the above

Q14. Write the output of the following:


print(‘Hello, world!’);print(“H”)
a) Hello world! H
b) Hello world!H
c) Hello world!
H
d) Error

Q15. Which of the following is invalid variable name?


a) Sum1
b) Num_1
c) Num 1
d) N1

Q16. Write the output of the following:


a=9
x=str(a)
b=5
y=str(b)
x+y
a) 14
b) 9,5
c) 95
d) None of the above

Q17. Write the output of the following:


7+2//1**2>5+2**2//3
a) True
b) False
c) Error
d) None of the above
Q18. Which of the following is invalid identifier?
a) _
b) _1st
c) 1stName
d) While

24 | Page
Q19. Which of the following statement will display “RAM” two times?
a) “RAM” + 2
b) “RAM” * 2
c) “RAM” ** 2
d) None of the above

Q20. ………………………….. operators are used to check if a value is a member of the given sequence
or not.
a) Logical
b) Identity
c) Membership
d) Relational

Answers
1. (a) 6. (d) 11. (b) 16. (c)
2. (c) 7. (d) 12. (c) 17. (a)
3. (b) 8. (d) 13. (d) 18. (c)
4. (d) 9. (a) 14. (c) 19. (b)
5. (c) 10. (c) 15. (c) 20. (c)

25 | Page
Very Short Answer Questions (VSA)
Q1. What is None literal in Python?
Ans: Python has one special literal, which is None. The None literal is used to indicate absence of value.
It is also used to indicate the end of lists in Python. It means “There is nothing here”.

Q2. What is the error in following code:


x, y =7?
Ans: The following error comes - 'int' object is not iterable. Which means an integer object i.e. cannot
be repeated for x and y. one more integer object is required after 7.

Q3. What will the following code do:


a=b=18?
Ans: This code will assign 18 to a and b both.

Q4. Following code is creating problem X = 0281, find reason.


Ans: 0281 is an invalid token.
(SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for
octal integers)

Q5. Find the error in the following code:


(a) temp=90 (b) a=12 (c) print(“x=”x) (d) a, b, c=2, 8, 4
print temp b=a+b print(a, b, c)
print( a and b) c, b, a = a, b, c
print(a; b; c)
(e) x = 23 (f) else = 21-4
4=x

Ans: (a) Missing parentheses in call to 'print'. (b) Name „b‟ is not defined. (c) Invalid Syntax. (d) Invalid
Syntax in second print statement. (e) can't assign to literal in second line. (f) Invalid Syntax.

Q6. Find the error in the following code:


(a) y = x +5 (b) a=input(“Value: “) (c) print(x = y = 5)
print(x,y) b = a/2
print( a, b)
Ans: (a) Name 'x' is not defined. (b) Unsupported operand type(s) for /: 'str' and 'int'. (c) Invalid Syntax
Q7. Identify the data types of the following values given bellow – 3, 3j, 13.0, ‘12’, “14”, 2+0j, 19
Ans: int, complex, float, string, string, complex, int

Q8. What will be the output of the following?


(a)12/4 (b)14//14 (c)14%4 (d) 14.0/4 (e) 14.0//4 (f)14.0%4
Ans: (a) 3.0 (b) 1 (c) 2 (d) 3.5 (e) 3.0 (f) 2.0
Q9. What will be the output of the following?

26 | Page
Ans: 4
4.25
1
4

Q10. What will be the output of the following ?


(a)87//5 (b)(87//5.0) == (87//5) (c) 87//5.0 (d) 17%5.0
Ans: (a) 17 (b) True (c) 17.0 (d) 2.0

Q11. Identify the valid variable(s) name:


First Name, Price, Stud.Id, while, Unit_Price, Ticket#1, _Sno_
Ans: Price, Unit_Price, _Sno_

Q12. Evaluate the following expressions:


(a) 12 + 3 * 4 – 6/2
(b) (12+3)*4-6/2
(c) 12+3*(4-6)/2
(d) 12+(3**4-6)/2
(e) 12*(3%4)//2+6
(f) 12%3**4//5+6
Ans: (a) 21.0 (b)57.0 (c) 9.0 (d) 49.5 (e)24 (f) 8
Q13. Write the full form of “IDLE”.
Ans: Integrated Development and Learning Environment

Q14. Is Python a compiled or an interpreted language?


Ans :The normal execution of Python program is interpreted. However, subsets of the language can
be compiled.

Q15. Python is a free and open-source language. What do you understand by this feature?
Ans: This feature signifies that Python is freely available, i.e., we do not have to pay anything to
download Python. Also, being an open-source language, its source code is also available if we wish
to modify it.

27 | Page
Short Answer Type Questions

Q1. What is the difference between a keyword and an identifier?


Ans: Difference between Keyword and Identifier: Every language has keywords and identifiers, which
are only understood by its compiler. Keywords are predefined reserved words, which possess special
meaning. An identifier is a unique name given to a particular variable, function or label of class in the
program.

Q2. What are literals in Python? How many types of Literals allowed in Python?
Ans: Literals: Python comes with some built-in objects. Some are used so often that Python has a
quick way to make these objects, called literals. The literals include the string, Unicode string,
integer, float, long, list, tuple and dictionary types.

Q3. How many types of sequences are supported in Python?


Ans: Three Types of Sequences are supported in python:
(i) String (ii) List (iii) Tuple

Q4. What factors guide the choice of identifiers in program?


Ans: (i) An identifier must start with a letter or underscore followed by any number of digits and/or
letters.
(ii) No keyword / reserved word or standard identifier should be used.
(iii) No special character (Other than underscore) should be included in the identifier.
(iv) As python is case sensitive language, so capital and small case letters are different
Eg sum and Sum are different variables.

Q5. What is the difference between an expression and a statement in Python?


Ans: A statement is an instruction that the Python interpreter can execute. We have only seen the
assignment statement so far. Some other kinds of statements that we’ll see shortly are while
statements, for statements, if statements, and import statements. (There are other kinds too!)
An expression is a combination of values, variables, operators, and calls to functions. Expressions
need to be evaluated. If you ask Python to print an expression, the interpreter evaluates the
expression and displays the result.

Q6. What are tokens in Python? How many types of tokens allowed in Python?
Ans: Tokens are the smallestindivisible unit of the program.
There are following tokens in Python:
∙ Reserved words or Keywords
∙ Identifiers
∙ Literals
∙ Operators
∙ Punctuators

28 | Page
Q7. What are operators? What is their function? Give examples of some unary and binary operators.
Ans: “Operators are those symbols used with operands, which tells compiler which operation is to
be done on operands.” in other words – “operators are tokens that trigger some computation/action
when applied to variables and other objects in an expression.”
Operators are of following types:
♣ Unary operators like (+) Unary Plus, (-) Unary Minus, not etc.
♣ Binary Operators like (+) addition, (*) multiplication, and etc.
Q8. What is block/code block/suit in Python?
Ans: Sometimes a group of statements is part of another statement of function. Such a group of one
or more statements is called block or code-block or suite in python. e.g.

Here both the sections are separate


code-blocks

Q9. What is the role of indentation in Python? Ans:


Indentation plays a very important role in Python. Python uses indentation to create blocks of code.
Statements at same indentation level are part of same block/suit. You cannot unnecessarily indent a
statement; python will raise an error for that.

Q10. How many types of strings are supported by Python?


Ans: Python supports two types of strings:
(i) Single-line string That terminates in single line.
(ii) Multi-line String That stores multiple lines of text.

Q11. What will be the output of the following?


(a)12/4 (b)14//14 (c)14%4 (d) 14.0/4 (e) 14.0//4 (f)14.0%4
Ans: (a) 3.0 (b) 1 (c) 2 (d) 3.5 (e) 3.0 (f) 2.0

Q12. What will be the output of the following ?


(a)87//5 (b)(87//5.0) == (87//5) (c) 87//5.0 (d) 17%5.0
Ans: (a) 17 (b) True (c) 17.0 (d) 2.0

Q13. Write following expressions in Python.

Ans: (a) (b*b*h)/3


(b) d=math.sqrt(pow(x2-x1,2)+pow(y2-y1,2))
(c) x1=((-b) + math.sqrt((b*b)-(4*a*c)))/(2*a)
x2=((-b) - math.sqrt((b*b)-(4*a*c)))/(2*a)
(d) pow(a,n) * pow(a,m) = pow(a,m+n)

29 | Page
Q14. What do you understand by term „immutable‟?
Ans: Immutable types are those data types that can never change their value in place. In Python the
following types are immutable: (i) integers (ii) floating-point numbers (iii) Booleans (iv) Strings (v)
Tuples

Q15. What will be the output of the following code? Why? (a) 13 or len(13) (b) len(13) or 13
Ans: (a) 13 (b) TypeError: object of type 'int' has no len()

HOTS

Q1. What will be the sizes of following constants? (a) ‘\a’ (b) “\a” (c) “kumar\’s” (d) ‘\”’ (e) “it’s”
Ans: (a) 50 (b) 50 (c) 56 (d) 50 (e) 53 This screenshot is the output of the above question.

Q2. How can you create multi-line strings in Python?


Ans: We can create multi-line string by putting a backslash (\) at the end of line which allows you to
continue typing in next line in same string.

Q3. Which of the following are syntactically correct strings? State reason.
(a) ”Python is nice Language”
(b) ‘He called me “Friend!” when he came’
(c) “Very Good’
(d) ‘This is a good book’
(e) “Namaste
(f) “I liked ‘Harry Potter’ very much”
Ans: (a) Correct (b) Correct (c) Incorrect (d) Correct (e) Incorrect (f) Correct

30 | Page
Q4. What is the error in following Python program with one statement?
print(“My name is : “, name) suggest a solution
Ans: Error is : “name 'name' is not defined”. And the solution is to declare the variable-name before
this statement.

Q5. Predict the output of the following:

Ans: Output: 17 5

Q6. What will be the output of the following code:

Ans: Output: Hari , you are 18 now but You will be 19 next year

Q7. Write a Program to obtain temperature in Celsius and convert it into Fahrenheit using formula – C
X 9/5 + 32 = F
Ans:

Q8. Predict output:

Ans: Output: 4 6 8

31 | Page
Q9. WAP to read today’s date (only date Part) from user. Then display how many days are left in the
current month.
Ans:

Q10. WAP to print the area of circle when radius of the circle is given by user.
Ans:

Q11. WAP to print the volume of a cylinder when radius and height of the cylinder is given by user.
Ans:

Q12. WAP that asks your height in centimeters and converts it into foot and inches.
Ans :

32 | Page
Q13. WAP to find area of a triangle.
Ans:

Q14. WAP to calculate simple interest.


Ans:

Q15. WAP to read a number in n and prints n 2 , n3 , n4


Ans:

Q16. WAP that searches for prime numbers from 15 through 25.
Ans:

33 | Page
Q17. WAP to test if given number is prime or not.
Ans:

Q18. WAP to compute the result when two numbers and one operator is given by user.
Ans:

Q19. WAP to calculate the roots of a given quadratic equation.


Ans:

34 | Page
Q20. WAP to input a digit and print it in words.
Ans:

Q21. WAP to print first n odd numbers in descending order.


Ans:

Q22. WAP to find the sum of n natural numbers.


Ans:

35 | Page
Q23. WAP to find the sum of first n even numbers.
Ans:

Q24. WAP to find the sum of first n odd numbers.


Ans:

Q25. WAP to print the following pattern

Ans:
(a)

(b)

(c)

36 | Page
(d)

37 | Page
LIST
The data type list is an ordered sequence which is mutable and made up of one or more elements.
Elements of a list are enclosed in square brackets and are separated by comma.
[] empty list
[1, 2, 3] list of integers
[‘a’, 1,’b’,2] list of mixed values
[1, 2, [10, 20], 5, 6] Nested list
Creating /Initializing List
<list name>= [ ]
LIST= [ ] # empty list
LIST = [1, 2, 3] #list of integers
LIST= [‘a’, 1,’b’,2] # list of mixed values
LIST = [1, 2, [10, 20], 5, 6]
Accessing Elements in a List
Each element in list is accessed using value called index. The first index value is 0, the second index
is 1 and so on. Elements in the list are assigned index values in increasing order starting from 0.
Positive Index
0 1 2 3 4 5 6 7
10 20 30 40 50 60 70 80
-8 -7 -6 -5 -4 -3 -2 -1
Negative Index
To access an element, use square brackets with the index [] value of that element.
We may also use negative index value to access elements starting from the last element in the list,
having index value -0.
List1=[10,20,30,40,50,60,70,80]
>>>List[6]
70
>>>List[-3]
60

38 | Page
TRAVERSINGALIST
Traversing means to access each element of the list. It can be done using IN operator inside a for loop
or a whileloop.
List traversal using for loop:
>>>list1=['Red','Green','Blue','Yellow', 'Black']
>>>foriteminlist1:
print(item)
Output:RedGreenBlueYellowBlack

LISTMANIPULATION:

1. Updating elements from the list–By assigning new value to the element of the list
through its index will change an element. Ex:
>>>l1=[1,2,3]

>>>l1[2]=4

2. Deleting elements from the list–the del statement is used to remove an individual item,
or to remove all items identified by a slice.
>>>l1=[10,12,13,14]

>>>del l1[2]

l1

[10,12,14]

1. Slicing the list–Like string as part of the list will be displayed.

>>> l1=[10,12,14,20,22,24,30,32,34]

>>> l1[3:-3]

[20,22,24]

39 | Page
2. JoiningLists-Theconcatenationoperator+whenusedwithtwolists,joinstwolists together
>>>l1=[1,2,3]

>>>l2=[4,5,6]

>>>l1+l2

>>>[1,2,3,4,5,6]

3. ReplicatingLists-The*operatorreplicatealistspecifiednumberoftimes.

>>>l1=[1,2]

>>>l1*2

>>>[1,2,1,2]

40 | Page
List Functions

Pythonalsooffersmanybuilt-infunctionsandmethodsforlistmanipulation.Thesecanbe applied to
list as per following syntax :

<listobject>.<method name>()

Method Description Example


len() Returnsthelengthofthelistpassedastheargu >>>list1=[10,20,30,40,50]
ment >>>len(list1)
5
list() Createsanemptylistifnoargumentispassed >>>list1=list()
>>> list1[]

>>>str1='aeiou'
Createsalistifasequenceispassedasanargume >>>list1=list(str1)
nt >>>list1
['a','e','i','o','u']
append() Appendsasingleelementpassedasanargume >>>list1=[10,20,30,40]
ntattheendofthelist >>>list1.append(50)
>>>list1
Alistcanalsobeappendedasanelementtoanexi [10,20,30,40,50]
stinglist >>>list1=[10,20,30,40]
>>>list1.append([50,60])
>>>list1
[10,20,30,40,[50,60]]
insert() Insertsanelementataparticularindex inthelist >>>list1=[10,20,30,40,50]
#insertselement25atindexvalue2
>>>list1.insert(2,25)
>>>list1
[10,20,25,30,40,50]
>>>list1.insert(0,100)
>>>list1
[100,10,20,25,30,40,50]
count() Returns the number of timesa >>>list1=[10,20,30,10,40,10]
givenelementappearsinthelist >>> list1.count(10)
3
>>> list1.count(90)

41 | Page
0

remove() Removes the given element from >>>list1=[10,20,30,40,50,30]


thelist.Iftheelementispresentmultipletimes >>>list1.remove(30)
,onlythefirstoccurrenceisremoved.Iftheele >>>list1
mentisnotpresent,thenValue [10,20,40,50,30]
Errorisgenerated >>> list1.remove(90)
ValueError: list.remove(x)
x not in list
pop() Returnstheelementwhoseindexispassedasa >>>list1=[10,20,30,40,50,60]
rgumenttothisfunctionandalsoremovesitfr >>>list1.pop(3)
omthelist.Ifno argument 40
isgiven,thenitreturnsandremovesthelastele >>>list1
mentofthelist
[10,20,30,50,60]
>>>list1=[10,20,30,40,50,60]
>>>list1.pop()
60
>>>list1
[10,20,30,40,50]
reverse() Reverses >>>list1=[34,66,12,89,28,99]
theorderofelementsinthegivenlist >>>list1.reverse()
>>>list1
[99,28,89,12,66,34]
>>> list1 = [ 'Tiger' ,'Zebra' ,'Lion','Cat','Elephant','Dog']
>>>list1.reverse()
>>>list1
['Dog', 'Elephant', 'Cat', 'Lion','Zebra','Tiger']

sort() Sorts the elementsofthegivenlistinplace >>>list1=['Tiger','Zebra','Lion','Cat','Elephant','Dog']


>>>list1.sort()
>>>list1
['Cat', 'Dog', 'Elephant', 'Lion','Tiger','Zebra']
>>>list1=[34,66,12,89,28,99]
>>>list1.sort(reverse=True)
>>>list1[99,89,66,34,
28,12]
min() Returnsminimumorsmallestelementoftheli >>>list1=[34,12,63,39,92,44]
st >>> min(list1)
12
max() Returnsmaximumorlargestelementofthelist >>>
max(list1)92
sum() Returnssumoftheelementsofthelist >>>sum(list1)
284

42 | Page
PROGRAMMING PRACTICE ON LISTS

1
Programforprintingonlytheoddnumbersofthegivenlist

m = [2,7,8, 3,5,9,0]
forvalin m:
ifval%2!=0:
print(val)

2 Programforfindingthesumofallevennumbersinagivenlist

k= [9,4,8, 2,14,2]
Sum_even=0
for valink:
ifval%2==0:
Sum_even+=val
print(“Sumofalltheevennumbersinthegivenlistis”,Sum_even)

3
Program tocalculateaveragemarksof n students where n is entered bytheuser.

list1=[]
print("Howmanystudentsmarksyouwanttoenter:")
n=int(input())
foriinrange(0,n):
print("Enter marks of student",(i+1),":")
marks=int(input())
#append marks in the
listlist1.append(marks)#initializ
etotal
total=0
formarksinlist1:add marks to total
total=total+marks
average=total/n
print("Averagemarksof",n,"studentsis:",average)

4
Program to check if a number
ispresentinthelistornot.Ifthenumberispresent,printthepositionofthenumber. Print an
appropriate message ifthenumberisnotpresentinthelist.

43 | Page
list1=[]
print("Howmanynumbersdoyouwanttoenterinthelist:")
maximum=int(input())
print("Enter a list of numbers: ")
foriinrange(0,maximum):
n=int(input())
list1.append(n)
num=int(input("Enterthenumbertobesearched:"))

position=-1
foriinrange(0,lin(list1)
iflist1[i]==num:
position=i+1
ifposition==-1:
print("Number",num,"isnotpresentinthelist")
else:
print("Number",num,"ispresentat",position+1,"position")

44 | Page
DICTIONARIES

⮚ Dictionariesaremutablewhichimpliesthatthecontents of the dictionary can be changed after it


hasbeencreated.
⮚ Dictionaries are unordered and unindexed data structure
⮚ It is amapping between a set of keys and a set of values.
⮚ Thekey-valuepairiscalledanitem.
⮚ Akeyisseparatedfromitsvaluebyacolon(:)andconsecutiveitemsareseparatedby commas.
⮚ The keysmust be unique and should be of anyimmutable data type .
⮚ Thevaluescanberepeatedandcanbeofanydatatype.

CREATINGADICTIONARY

To create a dictionary, the items entered are s


eparatedbycommasandenclosedincurlybraces.Eachitemisa key value pair, separated through
colon (:).

#dict1isanemptydictionary
>>>dict1={}
>>>dict1 {}

#dict3isthedictionarythatmapsnamesofthestudentstomarksinpercentage
>>>dict3={'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>>dict3
{'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}

ACCESSINGITEMSINADICTIONARY

Theitemsofadictionaryareaccessed viathekeys.Each key serves as the index and maps toavalue.


<dict>[<key>]
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3['Ram']
89
Intheaboveexamplesthekey'Ram'alwaysmapstothevalue89

* If the key is notpresentinthedictionarywegetKey Error.

45 | Page
MEMBERSHIPOPERATION

ThemembershipoperatorIN
checksifthekeyispresentinthedictionaryandreturnsTrue,elseitreturnsFalse.

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}


>>> 'Suhel' in dict1
True

ThenotinoperatorreturnsTrueifthekeyisnot presentinthedictionary,elseitreturnsFalse.

ADDINGANEWITEM

Wecanaddanewitemtothedictionaryasshowninthefollowingexample:

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}


>>>dict1['Meena']=78
>>>dict1
{'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85,'Meena':78}

UPDATINGANEXISTINGITEM

Theexistingdictionarycanbemodifiedbyjustoverwriting the key-value pair.

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}


#MarksofSuhelchangedto93.5
>>>dict1['Suhel']=93.5
>>>dict1
{'Mohan':95,'Ram':89,'Suhel':93.5, 'Sangeeta':85}

TRAVERSINGA DICTIONARY

We can access each item of the dictionary or traverse adictionaryusingforloop.

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, ‘’ Sangeeta':85}


Method1:
>>>forkeyindict1:
print (key,':',dict1[key])
Mohan:95
Ram :89
Suhel:92
Sangeeta:85

46 | Page
Method2:

>>> for key,value in dict1.items():


print(key,':',value)
Mohan:95
Ram:89
Suhel:92
Sangeeta:85

DELETING ELEMENT
We can remove an item from the existing dictionary by using del command or using pop()
1. Using del command- The keyword del is used to delete the key present in the dictionary. If the key
is not found, then it raises an error.
del <dict>[key]
2. Using pop() method – pop() method will not delete the item specified by the key from the
dictionary but also return the deleted value.
<dict>.pop(key)
3. popitem()- It returns and removes the last inserted item from dictionary
<dict>.popitem()

47 | Page
DICTIONARYMETHODS ANDBUILT-IN FUNCTIONS

Python provides many functions to work on dictionaries.

Method Description Example


dict() Creates a dictionary from pair1=[('Mohan',95),('Ram',89),
asequenceofkey-valuepairs ('Suhel',92),('Sangeeta',85)]
>>>pair1
[('Mohan',95),('Ram',89),('Suhl',
92),('Sangeeta',85)]
>>>dict1=dict(pair1)
>>>dict1
{'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
len() Returns the length or number >>> dict1 =
ofkey: value pairs of the {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85
dictionarypassedastheargument
}
>>>len(dict1)
4
keys() Returnsalistofkeysinthedictionar >>> dict1 = {'Mohan':95,
y 'Ram':89,'Suhel':92,'Sangeeta':85}
>>>dict1.keys()
dict.keys(['Mohan', 'Ram', 'Suhel', ‘ Sangeeta'])

values() Returnsalistofvaluesinthedictiona >>> dict1 = {'Mohan':95,


ry 'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict1.values()
dict.values([95,89,92,85])
items() Returnsalistoftuples(key— >>> dict1 = {'Mohan':95,
value)pair 'Ram':89,'Suhel':92,'Sangeeta':85}
>>>dict1.items()
Dict.items([('Mohan',95),('Ram',89),
('Suhel',92),('Sangeeta',85)])
get() Returnsthevaluecorrespondingto >>> dict1 = {'Mohan':95,
thekeypassedastheargument 'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict1.get('Sangeeta')85
Ifthekeyisnotpresentinthedictiona
ryitwillreturnNone

update() appends thekey-value pair >>> dict1 = {'Mohan':95,


ofthedictionarypassedastheargu 'Ram':89,'Suhel':92,'Sangeeta':85}
ment to the key-value pair >>>dict2={'Sohan':79,'Geeta':89}
ofthegivendictionary
>>>dict1.update(dict2)
>>>dict1
{'Mohan':95,'Ram':89,'Suhel':92,
48 | Page
'Sangeeta':85,'Sohan':79,'Geeta':89}
>>>dict2
{'Sohan':79,'Geeta':89}
clear() Deletesorclearalltheitems >>> dict1 =
ofthedictionary {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85
}
>>>dict1.clear()
>>>dict1
{}
del() Deletestheitemwiththegivenkey >>> dict1 =
Todeletethedictionaryfromthem {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85
emorywewrite: }
delDict_name
>>>deldict1['Ram']
>>>dict1
{'Mohan':95,'Suhel':92,'Sangeeta':85}

49 | Page
PROGRAMMING PRACTICE ON DICTIONERY
1
Program to count the numberof times a character appears in a givenstring.

st=input("Enterastring:")
dic={}
forchinst:
ifchindic:
dic[ch]+=1
else:
dic[ch]=1
forkeyindic:
print(key,':',dic[key])

2
Programtoconvertanumberentered by the user into its correspondingnumber in
words.
(for example if the inputis876thentheoutputshouldbe‘EightSevenSix’.)

num=input("Enteranynumber:")
numberNames={0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',\
5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine'}
result=''

forchinnum:
key=int(ch)
value=numberNames[key]

result = result + ' ' + value

print("Thenumberis:",num)
print("ThenumberNameis:",result)

3
A program to enternamesofemployeesandtheirsalariesas input and store them
in a dictionary.Herenistoinputbytheuser.

num=int(input("Enterthenumberofemployeeswhosedatatobestored:"))
count=1
employee=dict()
forcountinrange(n):
name=input("EnterthenameoftheEmployee:")
salary = int(input("Enter the salary: "))
employee[name]=salary
print("\n\nEMPLOYEE_NAME\tSALARY")
forkinemployee:
print(k,'\t\t',employee[k])
50 | Page
LET’S PRACTICE
MULTIPLE CHOICE QUESTIONS
1. Which of the following commands will create a list?
a) list1 = list()
b) list1 = []
c) list1 = list([1, 2, 3])
d) all of the mentioned

Answer: d

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


a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) [‘hello’]
c) [‘llo’]
d) [‘olleh’]

Answer: a

3. Suppose listExample is [‘h’,’e’,’l’,’l’,’o’], what is len(listExample)?


a) 5
b) 4
c) None
d) Error

Answer: a

4. Suppose list1 is [2445,133,12454,123], what is max(list1)?


a) 2445
b) 133
c) 12454
d) 123

Answer: c

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


a) 3
b) 5
c) 25
d) 1
51 | Page
Answer: d

6. Suppose list1 is [1, 5, 9], what is sum(list1)?


a) 1
b) 9
c) 15
d) Error

Answer: c

7. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of the following is correct syntax for slicing
operation?
a) print(list1[2:])
b) print(list1[:2])
c) print(list1[:-2])
d) all of the mentioned

Answer: d

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


a) Error
b) None
c) 25
d) 2

Answer: c
9. 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]

Answer: a
10. What will be the output of the following Python code?

1. >>>names =['Amir', 'Bear', 'Charlton', 'Daman']


2. >>>print(names[-1])
a) A
b) Daman
c) Error
d) n

52 | Page
Answer: d
11. 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]
d) [1, 3, 2, 3, 2, 1]

Answer: c

12.What will be the output of the following Python code?

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


2. >>>list2 =[11, 2, 2]
3. >>>list1 < list2
a) True
b) False
c) Error
d) None

Answer: b

13.. To add a new element to a list we use which command?


a) list1.add(5)
b) list1.append(5)
c) list1.addLast(5)
d) list1.addEnd(5)

Answer: b.
14. 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)

Answer: b

15. 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”)

Answer :a
53 | Page
Dictionary
1. Which of these about a dictionary is false?
a) The values of a dictionary can be accessed using keys
b) The keys of a dictionary can be accessed using values
c) Dictionaries aren’t ordered
d) Dictionaries are mutable

Answer: b

2. Which of the following is not a declaration of the dictionary?


a) {1: ‘A’, 2: ‘B’}
b) dict([[1,”A”],[2,”B”]])
c) {1,”A”,2”B”}
d) { }

Answer: c

3. What will be the output of the following Python code snippet?


a={1:"A",2:"B",3:"C"}
fori,jina.items():
print(i,j,end=" ")
a) 1 A 2 B 3 C
b) 1 2 3
c) A B C
d) 1:”A” 2:”B” 3:”C”

Answer: a

4. What will be the output of the following Python code snippet?


a={1:"A",2:"B",3:"C"}
print(a.get(1,4))
a) 1
b) A
c) 4
d) Invalid syntax for get method

Answer: b

5. What will be the output of the following Python code snippet?


a={1:"A",2:"B",3:"C"}
print(a.get(5,4))
a) Error, invalid syntax
b) A
c) 5
54 | Page
d) 4

Answer: d

6. What will be the output of the following Python code snippet?


a={1:"A",2:"B",3:"C"}
print(a.setdefault(3))
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
b) C
c) {1: 3, 2: 3, 3: 3}
d) No method called setdefault() exists for dictionary

Answer: b

7. What will be the output of the following Python code snippet?


a={1:"A",2:"B",3:"C"}
a.setdefault(4,"D")
print(a)
a) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’}
b) None
c) Error
d) [1,3,6,10]

Answer: a

8. What will be the output of the following Python code?


a={1:"A",2:"B",3:"C"}
b={4:"D",5:"E"}
a.update(b)
print(a)
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
b) Method update() doesn’t exist for dictionaries
c) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’, 5: ‘E’}
d) {4: ‘D’, 5: ‘E’}

Answer: c

9. What will be the output of the following Python code?


a={1:"A",2:"B",3:"C"}
b=a.copy()
b[2]="D"
print(a)
a) Error, copy() method doesn’t exist for dictionaries
b) {1: ‘A’, 2: ‘B’, 3: ‘C’}
55 | Page
c) {1: ‘A’, 2: ‘D’, 3: ‘C’}
d) “None” is printed

Answer: b

10. What will be the output of the following Python code?


a={1:"A",2:"B",3:"C"}
a.clear()
print(a)
a) None
b) { None:None, None:None, None:None}
c) {1:None, 2:None, 3:None}
d) { }

Answer: d

56 | Page
SHORT ANSWER TYPE QUESTIONS
1 What is the output of print list[0] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
Ans: abcd

2 What is the output of print tinylist * 2 if tinylist = [123, 'john']?


Ans: [123,’john’,123,’john’]

3
What is the output of print list[2:] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?

Ans: [2.23,’john’,70.2]
4
What do you understand by list ?

Ans: A list is the data structure which is mutable and ordered sequence of Elements

5 What is a nested list ?

Ans: A list inside another the list is known as nested list

6 Write a short note on indexing in a list

Ans: Each element in list is accessed using value called index.


● The first index value is 0, the second index is 1 and so on.
● Elements in the list are assigned index values in increasing
order sterling from 0.
● To access an element, use square brackets with the index []
value of that element.
● We may also use negative index value to access
elements starting from the last element in the list,
having index value -0.
Eg: L=[1, 2, 3, 4, 5]
print(L[0]) will display 1 and print(L[-1]) will display 5

7 Predict the output based on the list, cod = [98, 45, 62, 14, 1007]
a) print(len(cod))
Ans :5
b) print(cod * 2)

Ans: [98, 45, 62, 14, 1007, 98, 45, 62, 14, 1007]

c) print(1007 in cod)
Ans: True
d)print(cod[:2]+cod[2:])
Ans : [98, 45, 62, 14, 1007]

e) cod=[98, 45, 62, 14, 1007, 1010]


print(cod. pop(1))

57 | Page
Ans:45

8 The record of a student is stored as a list in the following format(Name, Roll.No,


Marks in 3 subjects, Percentage)
RecordList = [‘Komal’, ‘A-19’, [71, 86, 72], 76.3]
Write Python statements to retrieve the following information from the list, RecordList
● Name of the student
● Mark in the first subject
● Percentage obtained
● Change the name of the Student from “Komal” to “Kunal”

Ans :RecordList[0]
RecordList[2][0]
RecordList[-1]
RecordList[0]=”Kunal”

9 Write a program to accept elements of a list from the user. Multiply all the
elements of the list with 7 and display the elements.

Ans :
num = eval(input(“Enter a list of numbers:”))
for i in range(len(num)):
num[i] = num[i] * 7
print(“List after processing”, num)

10 Consider the following list, p = [‘v’, ‘a’, ‘c’, ‘c’, ‘i’, ‘n’, ‘a’, ‘t’, ‘i’, ‘o’, ‘n’).
Write a program to display each character along with its positive index and
negative index

Ans :
pos_index=0
neg_index=-1
for val in p:
print(val, “Positive index=”, pos_index, “Negative index=”,
neg_index) pos_index +=1
neg_index -=1
11 Differentiate between list and dictionary with examples

List vs Dictionary
1. Lists are mutable ordered sequences of values while Dictionaries are
mutable unordered collection with items in the form of key-value
pairs.

58 | Page
2. List value can be accessed with indices, whereas dictionary values are
accessible with the keys.
Eg: L=[1, 2, 3, 4, 5]
D = {1:’one’, 2:’two’, 3:’three’}

12 Predict the output based on the list, cod = [98, 45, 62, 14, 1007]
1. print(len(cod+cod))
2. print(cod[2:4] * 3)
3. print(‘14’ not in cod)
4. print(50-5 in cod)
5. print(cod[::-1]+cod[0:1])

Ans : a.10
b. [62, 14, 62, 14, 62, 14]
c. True
d. True
e. [1007, 14, 62, 45, 98, 98]

13 The record of a student is stored as a list in the following format(Name, Roll.No,


Marks in 3 subjects, Percentage)
RecordList = [‘Komal’, ‘A-19’, [71, 86, 72], 76.3]
Write Python statements to retrieve the following information from the list,
RecordList
. Percentage of the student
a. Total of all the marks
b. Maximum mark obtained
c. Copy only the marks to a new list, m1

Ans:
. RecordList[3] (or) RecordList[-1]
a. Sum(RecordList[2])
b. max(RecordList[2])
c. m1=RecordList[2]

14 Write a program to accept elements of a list from the user. Multiply elements of the
list with 7, if an element is a multiple of 7 otherwise multiply each element with 4.
After processing, display the elements.
Ans:

num = eval(input(“Enter a
list of numbers:”))

for i in range(len(num)):
if num[i]%7==0:
num[i] = num[i] * 7
else:
num[i] = num[i] * 4
print(“List after processing”, num)
59 | Page
15 Consider the following list, p = [‘v’, ‘a’, ‘c’, ‘c’, ‘i’, ‘n’, ‘a’, ‘t’, ‘i’, ‘o’, ‘n’). Write a
program to display each character along with its frequency of occurrence, and also
excluding duplicates from displaying multiple times.

Ans :
k=[]
for val in p:
if val not in k:
c = p. count(val)
print(val, “occurs”, c, “times”)
k. append(val)

Worksheet Dictionary (Level 1)

1 What is python dictionary

Ans: dictionary consists of a collection of key-value pairs. Each key-value pair


maps the key to its associated value. Dictionary is listed in curly brackets, inside
these curly brackets, keys and values are declared. Each key is separated from its
value by a colon (:), while commas separating each element.

2 What are the properties of dictionary

Ans: Dictionaries hold the data as key-value pairs. For each key, we have a value
that makes the dictionaries very easy to access.
Dictionaries are unordered and their data elements are not accessible in a defined
order

3 What is dict() in dictionary

Ans: The dict() is a constructor to create a dictionary. It does not return anything.

4 Write the code to print all the keys of the dictionary

Ans: To get all keys of the Python dictionary inbuilt keys() method is used.

60 | Page
61 | Page
Worksheet Dictionery Level -2
1 Write a python statement to add a new key, 11 and corresponding value
“Eleven” to the dictionary, “ODD “

Ans ODD[11] = “Eleven”

2 Consider the following dictionary cpwords:


cpwords = {"Soil": "Pollution", "Traffic": "Jam", "Air": "Purifier", "Play":
"Ground"}
Find the output of the following statements
. print(cpwords[‘Soil’])
a. print(cpwords. keys())
b. print(cpwords. values())
c. cpwords. update({"Play": "Station"}) print(cpwords)
d. del cpwords["Traffic"]
print(cpwords)
e. cpwords. update({"Water" : "Conservation"})
print(cpwords)

Ans . Pollution
a. dict_keys["Soil", "Traffic", "Air", "Play"]
b. dict_values["Pollution", "Jam", "Purifier", "Ground"]
c. {"Soil": "Pollution", "Air": "Purifier", "Play": "Ground"}
d. {"Soil": "Pollution", "Traffic": "Jam", "Air": "Purifier", "Play":
"Station"}
e. {"Soil": "Pollution", "Air": "Purifier", "Play":
"Ground", "Water": "Conservation"}

3 0. Write Python statements for performing the following on a dictionary,


“PTM”
. To check whether the value “s1” is existing as the dictionary’s keys
a. To remove the key ‘s3’ and its corresponding values from the dictionary
b. To find the number of elements in a dictionary
c. To change the value corresponding to “s5” to 99
d. To find the minimum value among the keys of the dictionary

Ans . ‘s1’ in PTM


a. PTM. clear()
b. len(PTM)
c. PTM[‘s5’]=99
d. min(PTM)

4 Write a Python program to accept names of 5 students and their


corresponding marks, and adds it to a dictionary named Stu_mark.

Ans Stu_mark={}
for i in range(5):
62 | Page
name = input(“Enter the name of the student”)
mark = int(input(“Enter the mark obtained”))
Stu_mark[name] = mark
print(Stu_mark)

5 Write a Python program that can accept a month’s number( from 1 to 12) and
display the number of days in the given month, based on an existing dictionary
month, which has number of the month as keys and the number of days as
values.
Ans month={1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6:30, 7: 31, 8: 31, 9: 30, 10: 30, 11:30,12:
31}
mon = int(input(“Enter the number of the month”))
if mon in month:
d = month[m1]
print(mon, “has”, d, “days”)
else:
print(“Enter a valid month name”)

63 | Page
Worksheet Dictionery Level -3

1 Write a python statement, to delete the item from the dictionary


corresponding to the key 9 of the following dictionary,
ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}

Ans ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}

2 Consider the following dictionary cpwords:


cpwords = {"Soil": "Pollution", "Traffic": "Jam", "Air": "Purifier", "Play":
"Ground"}
Find the output of the following statements
. print(cpwords. get("Air"))
a. print(“Play” in cpwords. keys())
b. print(“ground” not in cpwords. values())
d.cpwords. update({"play": "Station"})
print(cpwords)
c. del cpwords["Jam"]

Ans . Purifier
a. True
b. True
c. {"Soil": "Pollution", "Air": "Purifier", "Play": "Ground", "play": "Station" }
d. KeyError

3 Write Python statements for performing the following on a dictionary,


“PTM”
. To check whether the value “s1” is existing as the dictionary’s values
a. To remove the value 93 from the dictionary
b. To concatenate dictionary, d2={“s5” : 100, “s9”: 97} with PTM
c. To find the minimum value among the values of the dictionary
d. To add a key “s8” with value 74, if the key already exists then it should
only update the value.

Ans . ‘s1’ in PTM. values()


a. for key in PTM:
if PTM[key]==93:
del PTM[key]
b. PTM. update(d2)
. min(PTM. values())
. PTM. update({‘s8’: 74})

4 Write a Python program to accept names of 5 students and their corresponding


marks, and adds it to a dictionary named Stu_mark. Input a student name and
display his/ her corresponding mark.
Stu_mark={
64 | Page
Ans for i in range(5):
name = input(“Enter the name of the student”)
mark = int(input(“Enter the mark obtained”))
Stu_mark[name] = mark
Name1 = input(“Enter a name for searching”)
if Name1 in Stu_marks:
print(Stu_marks[Name1])
else:
print(“No such student exists..”)

65 | Page
DATABASE CONCEPT
1. Database - A database is collection of interrelated data; a database system is basically a computer
record keeping system
2. Type of database model
1. Relational: A relation is a two-dimensional table.
2. Hierarchical
3. Network
4. Object oriented
3. Key Concepts of Database
1. Database Schema -table A database table is a collection of rows and columns which
describes the basic storage structure of RDBMS.
2. Data Constraint -keys
3. Meta data - data about data
4. Database Instance – Copy of Schema
5. Query -Sql Command
6. Data Manipulation - insertion, deletion and updating
4. Properties of data base
1. Databases Reduces Redundancy
2. Database Controls Inconsistency
3. Database facilitate Sharing data
4. Database ensures Security
5. Database maintains Integrity
6. Database enforces Standard
5. Common Databases (RDBMS)
1. Oracle, SQL Server, DB2, Foxpro etc – These are proprietary RDBMS
2. MySQL, SQLite, PostgreSQL etc – these are open source RDBMS
6. Definitions
Database. - It refers to collection of logically related data.
Data Redundancy. - The duplication of data is known as data redundancy.
Data Inconsistency. - Multiple mismatching copies of same data represent data inconsistency.
Data Security. - Protection of data against accidental or intentional disclosure to unauthorized
persons, or unauthorised modification or destruction.
Data Privacy. - Rights of individuals and organizations to determine for themselves when, how
and to what extent information about them is to be transmitted to others.
DDL.- Data Definition Language. SQL part-language that facilitates defining creation/modification
etc. of database objects such as tables, indexes, sequences etc. For example, CREATE, DROP,
ALTER etc.
DML.- Data Manipulation Language. SQL part-language that facilitates manipulation (addition/
deletion/modification) of data residing in database tables. For example, SELECT, INSERT etc.
Relational Data Model. The data model wherein the data is organized into tables called relations.
Relationship among multiple tables is established on the basis of common column.
Attribute.- A column in a relation is called attribute.
Tuple - A row in a relation is called tuple.
Degree.- Number of attributes in a relation is called its degree.
Cardinality.- Number of tuples in a relation is called its cardinality.
Domain.- A pool of values where from a field can draw values is called domain.

66 | Page
Relation. A table having non-empty atomic values with unordered rows and columns is a
relation. SQL. Structured Query Language. A non-procedural UGL used for querying upon
relational databases. Tuple. A row in a relation is called tuple.
View. A virtual table that does not really exist in its own right but is instead derived from one or
more underlying base tables is called a view.

************************************

MCQ

67 | Page
1 Each table comprises of ________ and _________________
(A) rows, columns (B) data, information (C) database, table (D) None of these
Ans. Option (A) is correct.
Explanation: A database is an organized collection of data that is arranged in rows and columns.

2 The design of the database is known as what?


(A) Attribute (b) Database Schema
(C) obstruction (D) Database Oriented
Ans. Option (B) is correct
Explanation: Database schema is the logical representation of data which shows how the data is
stored logically in the entire database.
3 A relational database is a collection of
(A) Attributes (C) Records
(B) Tables (D) Fields
Explanation: In a relational database, all data is arranged in tables, which are made up of rows and
columns.
4 A tuple in RDBMS is referred to _______________ of a table
(A) Record (B) Field
(C) Table (D) Key
Ans. Option (A) is correct
Explanation: A single row of a table, that contains a single record for that relation is called a tuple.
5 Which of the following are used in data defini- tion?
(a) DML (c) TCL
(b) DDL (d) None of these
Ans. Option (B) is correct.
6 A field of a table is termed as
. Row (C)Attribute
. Tuple (D) Key

Ans - Option (c) is Correct


Explanation – In RDBMS Columns or field are termed as attributes
7 A _________________ is a collection of interrelated data, stored to server multiple applications
. . File (C) Information
. Datafile (D) Database

Ans. Option D is correct


Assertion and Reason Based MCQs
Directions: In the following questions, A statement of Assertion (A) is followed by a statement of
Reason (R). Mark the correct choice as.
. 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 correct explanation for A.
(C) A is true but R is false.
(D) A is false but R is true.
8 Assertion (A): A database consists of a number of tables.
Reason (R): Each table comprises of rows and re- cords.

68 | Page
Ans. Option (C) is correct.
Explanation: A database consists of a number of tables. Each table comprises of rows (records) and
columns (attributes). Each record contains values for the the corresponding attributes. The value of
the attributes for a record are interrelated.

9 Assertion (A): TCL stands for Transaction Control Language.


Reason (R): These commands perform retrieval, insertion, deletion and modification etc. on data-
bases.

Ans. Option (C) is correct.


Explanation: TCL commands allows you to manage and control the transactions.
1 Assertion (A): Databases Reduces Redundancy
0 Reason (R): Database Controls Inconsistency

Ans – Option A is Correct

Short Answer Question

Q. 1. What is relation? Define the relational data model.

Ans. A relation is a table having atomic values, unique and unordered rows and columns. The
relational model represent data and relationship among data by a collection of tables known as
relation, each of which has a number of columns with unique

Q. 2. What is table? Also, define Candidate Key.

Ans. A table consists of a number of rows and columns. Each record contains values for the
attributes. A candidate key is the smallest subset of the super key for which there does not exist a
proper subset that is super key. In other words, all attribute combinations inside a relation that can
serve as primary key are candidate keys.

Q3. Define degree and cardinality.

Ans. Degree is the number of attributes or columns present in a table.

Cardinality is the number of tuples or rows present in a table.

Q4. What is database Schema

Ans. The design of the database is known as the database schema.

Q5. What is DBMS

Ans - The term DBMS expand to database management System. A DBMS is specialised software
that is responsible for the creation, maintenance and use of a database.

Q6. What is RDBMS?

Ans. The term expands to Relational Database Management System. AN RDBMS stores the data
centrally in the form of a collection of tables known as relations. The relationship between two
‘tables/relations is established on common fields between the tables.

69 | Page
Q7. What is data redundancy? What are the problems associated with it?

Ans. Duplication of data is data redundancy. It leads to the problems like wastage of space and
data inconsistency.

Q8. What is data inconsistency?

Ans. The problem of multiple mismatched copies of same data, in a database, is called data
inconsistency. It is the result of unsupervised data redundancy. -

Long Question

Q4. What is Difference between DDL and DML


Ans . The difference between DDL and DML:
DDL DML
It stands for Data Definition Language. It stands for Data Manipulation Language.
It is used to create database schema and can be
It is used to add, retrieve or update the data.
used to define some constraints as well.
It basically defines the column (Attributes) of the It add or updates the row of the table. These rows
table. are called tuple.
Basic command present in DDL are CREATE, BASIC command present in DML
DROP, RENAME, ALTER etc. are UPDATE, INSERT, MERGE etc.
DDL is used to define the structure of a DML is used to manipulate the data within the
database. database.
DDL is used to create and modify database DML is used to perform operations on the data
objects like tables, indexes, views, and constraints. within those database objects.

Q5. What is Difference between DML and TCL


Ans . The difference between DML and TCL:

70 | Page
S.
no. Category DML TCL

DML stands for Data Manipulation TCL stands for Transaction Control
1. Full Form
Language. Language.

Transaction Control Language (TCL)


DML stands for Data Manipulation Language
consists of commands that deal
and is used to manipulate data in the
2. Definition with the transactions within
database by performing insertion, updating
databases.
and deletion operations.

Use in DML cannot be used for database TCL is used for handling database
3
Transactions transactions. transactions.

Frequently used commands present in DML Frequently used commands present


4. Commands are: UPDATE, INSERT, MERGE, SELECT, in TCL are: COMMIT, ROLLBACK,
DELETE, CALL, EXPLAIN PLAN, LOCK TABLE. SAVEPOINT, SET TRANSACTION.

Q6. What is Difference between DDL and DML


Ans. The difference between DDL and DML:
Difference between DDL and TCL:
S.
No. DDL TCL

1. It stands for Data Definition Language. It stands for Transaction Control Language.

It is used to define data structures or It contains those commands, which are used to
2.
overall database schema. manage transactions within the database.

By using DDL commands, database TCL commands are meant to handle database
3.
transactions cannot be handled. transactions.

Some DDL commands which are frequently Some TCL commands which are frequently used :
4.
used : CREATE, ALTER, DROP. COMMIT, ROLLBACK.

Q. What is SQL? What are different categories of commands available in SQL?

Answer =In order to access data within the Oracle database, all programs and users must use,
Structured Query Language (SQL). SQL is the set of commands that is recognized by nearly all
RDBMS.
SQL commands can be divided into following categories:
71 | Page
1. Data Definition Language (DDL) Commands.
2. Data Manipulation Language (DML) Commands.
3. Transaction Control Language (TCL) Commands.
4. Session Control Commands.
5. System Control Commands.

CONSTRAINT

● NOT NULL: This constraint tells that we cannot store a null value in a column. That is, if a
column is specified as NOT NULL then we will not be able to store null in this particular column
any more.
● PRIMARY KEY: A set of one or more attributes that can uniquely identify tuples within the
relation. The Primary Key column can not contain null value.
● FOREIGN KEY: A non-key attribute whose values are derived from the primary key of some
other tables.
● Candidate Key: All attribute combinations inside a relation that can serve as primary key.
● Unique Key - This constraint when specified with a column, tells that all the values in the
column must be unique. That is, the values in any row of a column must not be repeated.
● CHECK - This constraint helps to validate the values of a column to meet a particular condition.
That is, it helps to ensure that the value stored in a column meets a specific condition.
● DEFAULT: This constraint specifies a default value for the column when no value is specified by
the user.

Constraint-> Rules and conditions set for data being stored in a database.
Table constraint -
Column Constraint-

Consider the following two tables:


Student detail

Admn_no_new Name Class


1001 A 12
1002 B 11
1003 C 12
Attendance_table_12

Admn_no Roll_no Total_present Total_absent


1001 1 110 10
1003 10 98 22
Column Constraint - at the time of column define

Create table Attendaance_table_12(


Admn_no int (4) references student_detail(admn_no_new),
Roll_no int(2),
.
.
72 | Page
);

Table Constraint – written after define of all column, at the last before closing parenthesis.

Create table Attendaance_table_12 ( Admn_no int (4) , Roll_no . Foreign Key Admn_no references
student_detail(admn_no), );

Required Condition for making foreign key

1. Primary key in primary table/parents table


2. Both table in Same database
3. Same data type and size of column

Referential Integrity is enforced following rules

1. In Parent table can’t delete row if row value is used in another table.
2. In Parent table can’t modify row if row value is used in another table.
3. In Child table can’t insert new value which are not in parents table.

MCQ

73 | Page
1 An attribute whose value is derived from the primary key of some other table
. Primary key (C) Alternate key
. Foreign key (D) None of these

Ans. Option (B) is correct.


Explanation: A foreign key is a column or a group of columns in a relational database table that
provides a link between data in two tables
2 . An Alternate key can be defined as
(A) An attribute which is a primary key (C) A candidate key
(B) An attribute which is not a primary key (D) None of These
Ans – option (B) is Correct
Explanation- all the keys which did not become the primary key are called alternate key
3 The attributes which have all the properties of primary key
(A) Foreign key (C) Candidate key
(B) Alternate key (D) Both (a) and (c)
Ans. Option (C) is correct.
Explanation: The purpose of both candidate key and the primary key is the same, i.e. to uniquely
identify the tuples. The difference between two is that a table can have one or more than one
candidate key, there can be only one primary key for a table.
4 An Attribute in a relation is termed as a foreign key when it refers the ______________ of another
table
. Primary key (C) Alternate key
. Foreign key (D) check constraint

Ans – option a is Correct


5 Which of the following is not a legal constraint for a CREATE table command
. Primary key (C) Alternate key
. Foreign key (D) Distinct

Ans- Option D is correct


Explanation- Distinct is function to unique value from column and others are constraint
6 The primary key is selected from
. Composite key c) determinants
. Candidate key d) foreign Key

Ans- Option B is correct


7 Which of the following types of table constraint will prevent the entry of duplicate rows?
. Unique c) distinct
. Foreign key d) NULL

Ans – option A is correct


8 Assertion (A): INSERT command is an SQL command.
Reason (R): NOT NULL constraint ensures that a column cannot have a NULL value.
Ans. Option (B) is correct.
Explanation: INSERT command is used to add tuples (rows) in a table.
9 Assertion (A): UNIQUE constraint holds same value for the column.
Reason (R): There can be multiple UNIQUE constraints.

74 | Page
Ans. Option (D) is correct.
Explanation: UNIQUE constraint ensures that all values in a column are distinct. No two rows can hold
the same value in a column.
10 Assertion (A): The columns that are not PRIMARY should have FOREIGN KEY constraint.
Reason (R): Referential integrity is ensured through FOREIGN KEY.
Ans. Option (A) is correct.
Explanation: Whenever two tables are related by a common column then the related columns in the
parent table should be either declared PRIMARY KEY

or UNIQUE key and the related columns in the child table should have FOREIGN KEY constraint.

Short Question

Q1. How are constraints related to data integrity?

Ans. Through constraints, data integrity is maintained and assured, as before some data is put in a
table, it must fulfil the conditions and rules imposed by the constraints. This ensures data integrity
by allowing only the correct data ‘as per the rules and conditions, to enter in the table.

Q2. What is the role of NOT NULL constraint?

Ans. It indicates that in the data being inserted, the column must have some value and cannot be
left NULL.

Q3. What is the role of UNIQUE constraint?

Ans. This constraint ensures that for an attribute there will be a unique value for each row and no
value is being repeated in any other row for that attribute.

Q4. What is the role of PRIMARY KEY constraint?

Ans. This constraint implements NOT NULL and UNIQUE constraints together and designated an
attribute or a set of attributes as the primary key of the table so that its value can identify each
record with a unique identity.

Q5. What is the role of FOREIGN KEY constraint?

Ans. This constraint is used to ensure the referential integrity of data in the table. It matches the
value of the column designated as the foreign key in one table with another table’s PRIMARY KEY.

Q6. What is the role of CHECK constraint?

Ans. This constraint ensures whether the value in columns fulfils the specified condition.

Q7. What is an Alternate Key ?

Ans. A candidate key that is not a primary key is called an Alternate Key. In Supplier table if there
are 2 candidate keys — Suppld and Supp_Name and Suppld is the primary Key then Supp_Name is
the alternate key

Q8. What is a unique key? Is it a primary key?

75 | Page
Ans. A unique key in a table/relation is any non-primary-key field which also store unique values
for each row just like a primary-key does. But only one key is designate as a primary key. So unique
is unique non-key field of a table.

Q9 How many primary keys and unique keys can be there in a table?

Ans. There can be multiple unique keys in a table but there can be only primary key in

Table.

Long Question

Q1 Difference between Primary key and unique key

Ans.

Parameters PRIMARY KEY UNIQUE KEY


Used to serve as a unique Uniquely determines a row that
Basic
identifier for each row in a table. isn’t the primary key.
NULL value acceptance Cannot accept NULL values. Can accept NULL values.
Number of keys that can be
Only one primary key More than one unique key
defined in the table
The primary Key is used for The Unique Key is used for
Uses
indicating the rows uniquely. preventing duplicate entries.

Q2 Difference between Primary key and unique key

Ans.
The following table highlights all the important differences between primary key and foreign key –
Key Primary Key Foreign Key
It is used to maintain relationship between
Basic It is used to uniquely identify data in the table.
tables.
Null It can't be NULL. It can accept the NULL values.
It can carry duplicate value for a foreign key
Duplicate Two or more rows can't have same primary key.
attribute.
Primary key constraint can be defined on
Tables It can't be defined on temporary table
temporary table.

Q3. Are NULL values are same as a zero or a blank space?


Ans No, A NULL value isn’t the same as a zero or a blank space. A zero is a legal numeric value and
a blank space is a legal character value, whereas NULL is a legal empty value that cannot be
accessed or compared with other values.
Q4. What is Referential Integrity?
Ans. Referential Integrity is a set of rules that applies to tables having relationships through
common fields (foreign keys linked with primary keys). The Referential integrity ensures that every
foreign key must store only a valid value, i.e.
The value stored in a foreign key column must exist in the primary key, key column of its parent
table.
Parent table cannot delete a record if its referenced value is stored in some foreign key.
76 | Page
Q5. What is the similarity between UNIQUE and PRIMARY KEY constraints?

Ans. The UNIQUE and the PRIMARY KEY constraints, both, ensure that the attribute(s) they are
applied upon, contain the unique values (non-duplicate values) for each row/tuple in those
attributes.

77 | Page
STRUCTURED QUERY LANGUAGE(SQL)

SQL (Structured Query Language) is a language that is used to manage data that is held
in a relational database management system. It uses tables to manipulate and retrieve
information from databases for analysis.
By using SQL commands, one can search for any data in the database and perform
other functions like creating tables, adding records, modifying data, removing rows,
dropping tables etc.

SQL Commands
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.
SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.
Types of SQL Commands

There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

DDL or Data Definition Language

DDL or 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.
List of DDL commands:

CREATE: This command is used to create the database or its objects (like
table, index, function, views, store procedure, and triggers).
DROP: This command is used to delete objects from the database.
78 | Page
ALTER: This is used to alter the structure of the database.
TRUNCATE: This is used to remove all records from a table, including all
spaces allocated for the records are removed.
COMMENT: This is used to add comments to the data dictionary.
RENAME: This is used to rename an object existing in the database.
DML (Data Manipulation Language):

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.

DATA TYPES
Data types are means to identify the type of data and associated operations for handling it.
MySQL data types are divided into three categories:
● Numeric
● Date and time
● String types

Numeric Datatype
1. int– used for number without decimal.
2. decimal (m, d) – used for floating/real numbers. m denotes the total length of number
and d is number of decimal digits.
Date and Time Datatype
1. date–used to store date in YYYY-MM-DD format.
2. time–used to store time in HH:MM: SS format.
String Datatype
1. char(m)–used to store a fixed length string, m denotes max. number of characters.
2. varchar(m)–used to store a variable length string, m denotes max. no. of characters.
DATABASE COMMANDS
1. VIEW EXISTING DATABASE
To view existing database names, the command is: SHOW DATABASES;

0. CREATING DATABASE IN MYSQL


For creating the database in MySQL, we write the following command:
CREATE DATABASE databasename>; e.g. In order to create a
database Student, command is:
CREATE DATABASE Student;
79 | Page
ACCESSING A DATABASE
For accessing already existing database,we write:
USE<databasename>;
e.g.to access a database named Student, we write command as:
USE Student;
DELETING DATABASE
For deleting any existing database,the command is:
DROP DATABASE <databasename>;
e.g.to delete a database, say student, we write command as:
DROP DATABASE Student;
VIEWING TABLE IN DATABASE
In order to view tables, present in currently accessed database, command is:
SHOW TABLES;
CREATING TABLES IN MYSQL
Syntax of CREATE TABLE command is:
CREATE TABLE <table-name>(<colname> datatype, <colname> datatype,…);
E.g. Inorder to create table EMPLOYEE given below:
ECO ENA GEND GRA GRO
DE ME ER DE SS
Create table employee (ecode integer, ename varchar(20),gender char(1),grade
char(2),gross integer);
Inserting Data into Table:
Syntax:
Insert into <tablename> values(<v1>,<v2>,…);
Or
Insert into <tablename>(<column list> )values(<values list>);
Eg: insert into employee values (1001, ‘Ravi’,‘M’,‘E4’,50000);
Or
Insert into employee (ecode, ename) values(1002,’Meena’);
The left-out columns will be filled with null values.

Select Command:

It helps to display the records as per our requirement.

Different forms of select command:


1. Select * from employee;
It displays all rows and columns from the table.

2. Select ecode, ename from employee;


It displays selected columns from the table.

0. For displaying particular rows.

80 | Page
Syntax: select * from <tablename> where
<cond>; Eg. Select * from employee where
gender=’M’;

ELIMINATING REDUNDANT DATA

DISTINCT(GENDER)
M
F
The distinct keyword is used to eliminate duplicate records from the table. Eg. Select distinct

(gender) from employee;

USING COLUMN ALIASES


The columns that we select in a query can be given a different name, i.e. column
alias name for output purpose.

Syntax: SELECT <columnname> AS column alias, <columnname> AS column alias


…..FROM <tablename>;
Eg.select ecode as “EMP_Code” from employee;
CONDITION BASED ON A RANGE

The BETWEEN operator defines a range of values that the column values must fall
into make the condition true. The range include both lower value and upper
value.
e.g.To display ECODE,ENAME and GRADE of those employees whose salary is
between 40000 and 50000,command is:
SELECT ECODE, ENAME, GRADE FROM EMPLOYEE
WHERE GROSS BETWEEN 40000 AND 50000;
NOTE: For displaying records not in the specified range, we have to use not between operator.
CONDITION BASED ON A LIST
The in operator is used to display records based on a list of values.
Eg. To display details of employees who have scored A,B
and C grades. Select * from employee where grade
in(‘A’,’B’,’C’);
Note: For displaying records that do not match in the list, we have to use not in operator.

CONDITION BASED ON PATTERN MATCHES

LIKE operator is used for pattern matching in SQL. Patterns are described using
two special wildcard characters: % and _ (underscore)
1. Percent (%)– The % character matches any substring.

81 | Page
2. Underscore (_)– The _ character matches any single character.
e.g.To display names of employee whose name starts with R in EMPLOYEE table,
the command is: select ename from employee where ename like “R%”;
e.g. To display details of employee whose second
character in name is: select * from employee where
ename like ‘_e%’;

SEARCHING FOR NULL


The NULL value in a column can be searched for in a table using IS NULL in
the WHERE clause. E.g. to list employee details whose salary contain NULL,
we use the command:
Select * from employee where gross is null;
Note: For listing employees who earn salary, then it is:
Select * from employee where gross is not null;
Relational Operators
● To compare two values, a relational operator is used. The result of the
comparison is true or false. Relational Operators recognized by SQL: =, >, <, <=,
>=, <> (not equal or !=)

Eg. Select * from employee where ecode <> 1001;


Above query will not display those employee details whose ecode column value is 1001.

Logical Operators- (OR, AND, NOT)


1. To list the employee details having grades E2 or E3.
Select ecode, ename, grade, gross from employee where (grade=‘E2’ OR grade=‘E3’);

0. To list all the employees’ details having grades as ‘E4’ but with gross < 9000.
Select ecode, ename, grade, gross from employee where grade=‘E4’ and gross< 9000;

0. To list all the employees’ details whose grades are other than ‘G1’.
Select ecode, ename, grade, gross from employee where (NOT grade= ‘G1’);

Sorting Results- ORDER BY clause

Results of SQL query can be sorted in a specific order using ORDER BY clause.
The ORDER BY clause allows sorting of query results by one or more columns. The
sorting can be done either in ascending or descending order.

Eg. Select * from emp order by ename;


Above query arranges the records in alphabetical order of ename value. By default
order by clause arranges in ascending order.

TO DISPLAY RECORDS IN DESCENDING ORDER

82 | Page
● Select * from employee order by ename desc;
Above query gives output in descending order of ename.
● Select * from employee ORDER BY grade DESC, ename ASC;
Above query displays records first in the descending order of grade and within
the same grade, employees are displayed in the ascending order of
Ename.

DELETE Command

This command removes rows from a table.


Syntax: DELETE FROM <tablename> [WHERE <cond>];

Eg: To remove all the contents of items table, the query is: DELETE from
items;
Eg: To remove the tuples from employee that have gross less than 20000 is : DELETE from
employee WHERE gross<20000;

UPDATE Command

Update Command allows to change some or all the values in an existing rows.
Update command specifies the rows to be changed using the WHERE clause and
the new data using the SET keyword.
Eg. UPDATE employee SET gross= 25000;
The above query sets the gross of all records as 25000.

UPDATE employee SET gross=40000, grade=’A’ WHERE ecode=1001;


The above query changes the gross and grade values for the record with ecode 1001.

ALTER TABLE

ALTER TABLE command is used to change the structure of the existing table. It can be
used to add or drop new columns or modify the existing columns of table.
Eg. 1. Alter table Employee Add comm int;
0. ALTER TABLE Emp MODIFY (ename varchar(60));
0. Alter table emp drop comm;

DROP TABLE:

DROP TABLE command allows to remove a table from database. Once the DROP
command is issued, the table will no longer be available in the database.
Eg. DROP TABLE employee;

INTEGRITY CONSTRAINTS
83 | Page
A constraint is a condition or check applicable on a field or set of fields. Common types of
constraints include:

S.N Constraint Description


o. s
1 NOT NULL Ensures that a column cannot have NULL value
2 DEFAULT Provides a default value for a column when none
is
Specified
3 UNIQUE Ensures that all values in a column are different
4 PRIMARY Used to uniquely identify a row in the table
KEY
5 FOREIGN Used to ensure referential integrity of the data
KEY

ADDING CONSTRAINT TO A TABLE

ALTER TABLE statement can be used to add constraints to your existing table by using it in
following manner:

Eg: alter table employee add primary key(ecode);


REMOVING CONSTRAINTS FROM A TABLE
Eg: alter table employee drop primary key;

Setting primary and foreign key constraint:

Eg: CREATE TABLE STUDENT(ROLL_NO integer PRIMARY KEY


,NAME VARCHAR(30),CLASSVARCHAR(3));

CREATE TABLE SCORE(ROLL_NO integer ,MARKS integer, FOREIGN KEY(ROLL_NO)


REFERENCES STUDENT(ROLL_NO));

Accessing/selecting Database:

Command: USE

Syntax: USE database-name; Example: USE xiiip;

Create Database:

Command: CREATE DATABASE

Syntax: CREATE DATABASE database-name; Example: CREATE DATABASE xiiip;

84 | Page
Dropping Database:

Command: DROP DATABASE

Syntax: DROP DATABASE database-name; Example: DROP DATABSE xiiip;

Display Existing Databases: Command: SHOW DATABASES Example: SHOW DATABASES;

Creating Table:

Command: CREATE TABLE

Syntax: CREATE TABLE table-name(

column-name data-type<COLUMN CONSTRAINT>,

....

....

PRIMARY KEY(column-name,. ));

Example: CREATE TABLE employee(

ecode integer NOT NULL ,

voter id integer

ename varchar(20) UNiQUE, sex char(1),

grade char(2) DEFAULT ‘E1’, gross decimal,

deptcode char(4) , CHECK(gross>2000), PRIMARY KEY(ecode),

FOREIGN KEY(deptcode) REFERENCES department(deptcode));

Describing Table:

Command: DESC

Syntax: DESC table-name; or DESCRIBE table-name; Example: DESC employee; or DESCRIBE


employee;

Inserting Data into Table:

85 | Page
Command: INSERT INTO

Syntax: INSERT INTO table-name(column-name1, column-name2,. )

VALUES(value,value,. );

Example: INSERT INTO employee

VALUES(123,’Raju’,’M’,’E3’,10000.00,’acco’);

Altering Table:

Command: ALTER TABLE

Syntax for remove column: ALTER TABLE table-name DROP COLUMN column–name; Example:
ALTE TABLE employee DROP COLUMN grade;

Syntax for add column: ALTER TABLE table-name ADD COLUMN column-name datatype(length);
Example: ALTER TABLE employee ADD COLUMN grade char(2);

Syntax for changing an existing column:

ALTER TABLE table-name CHANGE [old column-name] [new column-name] datatype; Example:
ALTER TABLE table-name CHANGE grade score char(2);

Syntax for resize a column: ALTER TABLE table-name MODIFY column-name datatype(length);
Example: ALTER TABLE employee MODIFY enamevarchar(25);

Change the value in the table:

Command: UPDATE

Syntax: UPDATE table-name SET column-name=value1 [WHERE column-name=value]; Example:


UPDATE employee SET gross=gross+500 WHERE grade=’E3’;

Deleting rows from a table:

Command: DELETE FROM

Syntax: DELETE FROM table-name [WHERE condition]; Example: DELETE FROM employee;

DELETE FROM employee WHERE grade=’E2’;

Remove a table:

86 | Page
Command: DROP TABLE

Syntax: DROP TABLE table-name; Example: DROP TABLE employee;

Display the contents of all the columns of a table:

Command: SELECT *

Syntax: SELECT * FROM table-name; Example: SELECT * FROM employee;

Selecting specific columns:

Syntax: SELECT column1, column2,... FROM table-name; Example:SELECT ename, grade, sex
FROM employee;

Use search condition to specify the rows you want to retrieve from the table:

Command: WHERE

Syntax: SELECT * FROM table-name WHERE condition;

Example: SELECT * FROM employee WHERE grade=’A’;

We can use two types of operators in the condition part:

1. Relational Operators: The mathematical operators which are used to perform certain
type of comparison between two variables are called relational operators. =, >, <, >=, <= are
examples of relational operators.

2. Boolean or Logical Operators: Boolean operators are the ones which are either true or
false. They are used to combine one or more conditions. AND, OR, NOT are examples of Boolean
operators.

Remove duplicate rows in the output:

Command: DISTINCT

Syntax: SELECT DISTINCT column-name FROM table-name;

Example: SELECT DISTINCT ename FROM employee;

Retrieve information from the table where the values of a column belong to a specified range:

87 | Page
Command: BETWEEN

Syntax: SELECT * FROM table-name WHERE column-name BETWEEN value1 AND value2;
Example: SELECT * FROM employee WHERE ecode BETWEEN 100 AND 123;

Pattern Matching:

Command: LIKE

Syntax: SELECT * FROM table-name WHERE column-name LIKE condition-based-on-pattern;


Example: SELECT * FROM employee WHERE grade LIKE ‘E%’;

N.B: Percent (%) means zero or one or more characters.

Underscore (_) means exactly one character.

Retrieve information from the table where the values of a column belong to a specified list:

Command: IN

Syntax:

SELECT * FROM table-name WHERE column-name in (value 1, value 2, , value n);

Example: SELECT * FROM employee WHERE grade IN (‘E1’,’E3’,’E5’); SELECT * FROM


employee WHERE grade NOT IN (‘E1’,’E3’,’E5’);

Sorting Results:

Command: ORDER BY

Syntax: SELECT column-name1 [,column-name2,...] FROM table-name [WHERE <condition>]


ORDER BY column-name [ASC/DESC];

Example: SELECT * FROM employee;

SELECT ename, gross FROM employee WHERE gross>5000 ORDERBY ename DESC;

Group the rows in the result table by columns that have the same values, so that each group is
reduced to a single row:

Command: GROUP BY

88 | Page
Syntax: SELECT column-name1, column-name2,. FROM table-name

GROUP BY column-name;

Example: SELECT grade, AVG(gross) FROM employee GROUP BY grade;

Apply condition to restrict grouped rows that appear in the result table:

Command: HAVING

Syntax: SELECT column-name1, column-name2, FROM table-name

GROUP BY column-name HAVING column-name CONDITION value; Example:

SELECT grade, AVG(gross) FROM employee GROUP BY grade

HAVING AVG(gross)>5000;

Check whether a column value is NULL or NOT:

Command: IS NULL

Syntax: SELECT * FROM table-name WHERE column-name IS NULL; Example:

SELECT * FROM employee WHERE deptcode IS NULL; Command: IS NOT NULL

Syntax: SELECT * FROM table-name WHERE column-name IS NOT NULL; Example: SELECT *
FROM employee WHERE deptcode IS NOT NULL;

Column Alias:

Command: AS

Syntax: SELECT column-name AS alias-name FROM table-name; Example:

SELECT ename AS EmployeeName FROM employee;

Multiple Choice Questions (MCQs)

Q1. MySQL database system consists of-


(a) MySQLServerInstance
(b) MySQLDatabase
(c) MySQL Query Optimizer
(d) (a)&(b)both

89 | Page
Q2. Which commands are used to define or redefine schema objects?
(a) DDL
(b) DML
(c) TCL
(d) (a)&(b)both

Q3. Data definition includes:


(a) Creating of database
(b) Undoing changes to the database.
(c) Modification of data stored in the database.
(d) All of the above

Q4. Which is not a TCL command?


(a) Commit
(b) Rollback
(c) Exit
(d) Savepoint

Q5. Which is not a function of DML?


(a) Retrieval of data stored in the database
(b) Insertion of data into the database
(c) Deletion of data from the database
(d) Making changes permanent to the database.

Q6. Which is not a numeric type?

(a) Int
(b) Float
(c) Blob
(d) Double

Q7. The default date format in MySQL is:


(a) DD/MM/YYYY
(b) YYYY/MM/DD
(c) MM-DD-YYYY
(d) YYYY-MM-DD
Q8. Which is not a way to represent comment in MySQL? (a)/* */
(b) --
(c) #
(d) //

Q9. The command is used to access database in MySQL is-


(a) Open <databasename>;
(b) USE <databasename>;
(c) Access <databasename>;
(d) (a)&(b) both

10. Which is a valid CREATE TABLE statement?


(a) Create table emp add(id integer(3));
90 | Page
(b) Create table emp(id integers(3));
(c) Create table emp modified(id integer(3));
(d) Create table emp(id integer(3));

Q11. How can you insert a new row into the “STORE” table.
(a) INSERT ROW(1,‟RAMSINGH‟)INTO STORE;
(b) INSERT VALUES(1,‟RAMSINGH‟)INTO STORE;
(c) INSERT INTO(1,‟RAMSINGH‟)STORE;
(d) INSERT INTO STORE VALUES(1,‟RAMSINGH‟);

Q12. Select statement has four clauses 1.Where 2.Having 3.Group By 4.Orderby
The correct order of all clauses in a select is:- (a)1,2,3&4
(b)1,3,2&4
(c)1,4,3&2
(d)1,3,4&2

Q13. Conditionally retrieval of rows from a table with SELECT, which clause is used?
(a) Where
(b) Having
(c) Group By
(d) Order by

Q14. The key word eliminates duplicate rows from the result of a
SELECT statement.
(a) All
(b) Unique
(c) Distinct
(d) IN

Q15. Which operator defines a range of values that the column values must fall in?
(a) In
(b) Like
(c) Between
(d) Is
Q16. To specify a list of values………………..Operator is used.
(a) In
(b) Like
(c) Between
(d) Is

Q17. We use operator with select for condition based on pattern matching.
(a) In
(b) Like
(c) Between
(d) Is

Q18. Which SQL statement will not generate any error message?
(a) SELECT*FROM EMP WHERE EMPNO LIKE(1,2,3,4);
(b) SELECT*FROM EMP WHERE SAL BETWEEN 3000 TO 15000;
91 | Page
(c) SELECT*FROM EMP WHERE COMM IS NOT NULL;
(d) All of the above

Q19.To display the detail of employee having ‘e’ in their name in descending order of salary. The
correct SQL statement is:
(a) SELECT*FROM emp WHERE ename LIKE “e%” ORDER BY SAL;
(b) SELECT*FROM emp ORDER BY SAL DESC WHERE ename LIKE

“%e%”;
(c) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY DESC SAL;
(d) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY SAL DESC;

Q20. Which statement is valid?


(a) ALTER TABLE EMPLOYEE MODIFY(last_name CHAR2(2000));
(b) ALTER TABLE EMPLOYEE CHANGE(last_name CHAR2(2000));
(c) ALTERTABLE EMPLOYEE CHANGE(last_name VARCHAR2(2000));
(d) ALTER TABLE EMPLOYEE MODIFY(last_name VARCHAR2(2000));

Answers

Q.No. Answers
1 d
2 a
3 a
4 c
5 d
6 c
7 d
8 d
9 b
10 d
11 d
12 b
13 a
14 c
15 c
16 a
17 b
18 c
19 d
20 d

Very Short Answer Questions (VSA)

Q1. Define the terms:


Database Abstraction
Data inconsistency
Conceptual level of database implementation/abstraction
92 | Page
Primary Key
Candidate Key
Relational Algebra
Domain

Answer
Define the terms:
i. Database Abstraction
Ans: Database system provides the users only that much information that is required by them,
and hides certain details like, how the data is stored and maintained in database at hardware
level. This concept/process is Database abstraction.
ii. Data inconsistency
Ans: When two or more entries about the same data do not agree i.e. when one of them stores
the updated information and the other does not, it results in data inconsistency in the
database.
iii. Conceptual level of database implementation/abstraction
Ans: It describes what data are actually stored in the database. It also describes the relationships
existing among data. At this level the database is described logically in terms of simple data-
structures.
iv. Primary Key
Ans : It is a key/attribute or a set of attributes that can uniquely identify tuples within the
relation.
v. Candidate Key
Ans : All attributes combinations inside a relation that can serve as primary key are candidate
key as they are candidates for being as a primary key or a part of it.
vi. Relational Algebra
Ans : It is the collections of rules and operations on relations(tables). The various operations
are selection, projection, Cartesian product, union, set difference and intersection, and joining
of relations.
vii. Domain
Ans : it is the pool or collection of data from which the actual values appearing in a given column
are drawn.

Q2. Answer the following questions:


.Differentiate between DDL and DML?
.What is a constraint?
.What are single row functions?
.Compare CHAR and VARCHAR data types.
.What are the differences between DELETE and DROP commands of SQL?
.What do you understand by MySQL Client?

.A table "Animals" in a database has 3 columns and 10 records. What is the degree and
cardinality of this table?
.Which keyword is used to remove redundant data from a relation.

Answers:

. Data Definition Language (DDL): This is a category of SQL commands. All the commands which are
used to create, destroy, or restructure databases and tables come under this category. Examples of
93 | Page
DDL commands are - CREATE, DROP, ALTER. Data Manipulation Language (DML): This is a category of
SQL commands. All the commands which are used to manipulate data within tables come under this
category. Examples of DML commands are - INSERT, UPDATE, DELETE.
. A constraints is a condition or check application on a field or set of fields.
Example: NOT NULL (ensure that column con not have null value), CHECK (make sure that all
value satisfy certain criteria), UNIQUE (ensure that all values in a column are different) etc.

iii. Single Row Function work with a single row at a time. A single row function returns a result for
every row of a quired table
Examples of Single row functions are Sqrt(), Concat(), Lcase(), Upper(), Day(), etc.

iv. The CHAR data-type stores fixed length strings such that strings having length smaller than the
field size are padded on the right with spaces before being stored. The VARCHAR on the other
hand supports variable length strings and therefore stores strings smaller than the field size
without modification.
iv. DELETE is DML command while DROP is a DDL command. Delete is used to delete rows from a
table while DROP is used to remove the entire table from the database.
iv. MySQL Clients are programs that connect to MySQL Server and issue queries in predefined
format.
iv. WHERE clause is used to select particular rows that satisfy the condition where having clause
is used in connection with the aggregate function GROUP BY clause. FOR EXAMPLE-
select * from student where marks >80;
Select * from student group by stream having marks>90;
viii. Degree 3 and Cardinality=10
viii. COMMIT command permanently saves the changes made during the transacation
execution.RROLLBACK command undoes the changes made during transaction execution.
viii. DISTINCT

Short Answer Questions

Q1. Categorize the following SQL commands into DDL and DML :
CREATE, UPDATE, INSERT, DROP
Ans. DDL Commands : CREATE, DROP
DML Commands : INSERT, UPDATE

Q2. A SQL table ITEMS contains the following columns:


INO, INAME, QUANTITY, PRICE, DISCOUNT
Write the SQL command to remove the column DISCOUNT from the table.
Ans. ALTER TABLE ITEMS DROP COLUMN DISCOUNT; OR
ALTER TABLE ITEMS DROP DISCOUNT;

Q3. Differentiate between Candidate Key and Primary Key in the context of Relational Database
Model.
Ans. A table may have more than one or a combination of attribute(s)that identifies a tuple
uniquely. All such attribute(s) are known as Candidate Keys.

94 | Page
Out of all the Candidate keys, the most appropriate one, which is used for unique identification of
the Tuples, is called the Primary Key.

Q4. In the table Loan below


. Identify the candidate key(s) from the table Loan.
. Which field will be considered as the foreign key if the tables Customers and Loan are related
in a database?

Q5. Write the names of SQL functions to perform the following operations i) Convert email-id to
lowercase.

ii) Count the number of characters in your name.


Ans. i) Select lower(emailed);
ii) Select length(name);

Q7. Mr. Roger is using a table LIBRARY. It has the following columns:
BCode, BName, Price, author. He wants to display maximum price Author wise.
He wrote the following command:
SELECT Author, Max(Price) FROM LIBRARY;

95 | Page
But he did not get desired result. Rewrite the above query with necessary change to help him get
the desired output and
explain the reason.

Ans.
SELECT Author, Max(Price) FROM LIBRARY GROUP BY AUTHOR;
Group By clause is used to group the rows together that contain the same values in a specified
column.so to display maximum price of each author , the table must be grouped author wise using
group by clause.

Q8. Differentiate ORDER BY and GROUP BY with an example.


Ans. Order By : Order by keyword sort the result-set either in ascending or in descending order.
This clause sorts the result-set in ascending order by default. In order to sort the result-set in
descending order DESC keyword is used.
Order By Syntax –
SELECT column_1, column_2, column_3...........
FROM Table_Name
ORDER BY column_1, column_2, column_3 ASC|DESC;
Group By : Group by statement is used to group the rows that have the same value. It is often used
with aggregate functions for example:AVG(), MAX(), COUNT(), MIN() etc. One thing to remember
about the group by clause is that the tuples are grouped based on the similarity between the
attribute values of tuples.
Group By Syntax –
SELECT function_Name(column_1), column_2
FROM Table_Name
WHERE condition
GROUP BY column_1, column_2 ORDER BY column_1, column_2;

Long Answer Questions

Q1. Consider the following tables GAMES and PLAYER. Write SQL commands for the statements to (iv)
and give outputs for SQL queries (v) to (viii).
Table: GAMES
GCode GameName Number PrizeMoney ScheduleDate
101 Carom Board 2 5000 23-Jan-2004
102 Badminton 2 12000 12-Dec-2003
103 Table Tennis 4 8000 14-Feb-2004
105 Chess 2 9000 01-Jan-2004
108 Lawn Tennis 4 25000 19-Mar-2004
Table: PLAYER
PCode Name Gcode
1 Nabi Ahmad 101
2 Ravi Sahai 108
3 Jatin 101
4 Nazneen 103

96 | Page
.To display the name of all Games with their Gcodes.
.To display details of those games which are having PrizeMoney more than 7000.
.To display the content of the GAMES table in ascending order of ScheduleDate.
.SELECT DISTINCT Gcode FROM PLAYER;

Answer
(i) SELECT GameName,Gcode FROM GAMES;
ii.SELECT * FROM GAMES WHERE PrizeMoney>7000;
ii.SELECT * FROM GAMES ORDER BY ScheduleDate;
ii.19-Mar-2004 12-Dec-2003
ii.59000
ii.101
103
108

Q2. Consider the following tables FACULTY and COURSES. Write SQL commands for the
statements (i) to (iv) and give outputs for SQL queries (v) to (vi).

FACULTY
F_ID Fname Lname Hire_date Salary
102 Amit Mishra 12-10-1998 12000
103 Nitin Vyas 24-12-1994 8000
104 Rakshit Soni 18-5-2001 14000
105 Rashmi Malhotra 11-9-2004 11000
106 Sulekha Srivastava 5-6-2006 10000
COURSES
C_ID F_ID Cname Fees
C21 102 Grid Computing 40000
C22 106 System Design 16000
C23 104 Computer Security 8000
C24 106 Human Biology 15000
C25 102 Computer Network 20000
C26 105 Visual Basic 6000

.To display details of those Faculties whose salary is greater than 12000.
.To display the details of courses whose fees is in the range of 15000 to 50000 (both
values included).
.To increase the fees of all courses by 500 of “System Design” Course.
Answer
.Select * from faculty where salary > 12000;
.Select * from Courses.where fees between 15000 and 50000;
.Update courses set fees = fees + 500 where Cname = “System Design”;

97 | Page
Q-3 Write SQL Command for (a) to (e) and output of (f)
TABLE : GRADUATE
S.NO NAME STIPEND SUBJECT AVERAGE DIV
1 KARAN 400 PHYSICS 68 I
2 DIWAKAR 450 COMP Sc 68 I
3 DIVYA 300 CHEMISTRY 62 I
4 REKHA 350 PHYSICS 63 I
5 ARJUN 500 MATHS 70 I
6 SABINA 400 CHEMISTRY 55 II
7 JOHN 250 PHYSICS 64 I
8 ROBERT 450 MATHS 68 I
9 RUBINA 500 COMP Sc 62 I
10 VIKAS 400 MATHS 57 II

. List the names of those students who have obtained DIV I sorted by NAME.
. Display a report, listing NAME, STIPEND, SUBJECT and amount of stipend received in a year
assuming that the STIPEND is paid every month.
. To count the number of students who are either PHYSICS or COMPUTER SC graduates.
. To insert a new row in the GRADUATE table: 11,”KAJOL”, 300, “computer sc”, 75, 1
. Add a new column GRADE of character type.
. Give the output of following sql statement based on table GRADUATE:
.Select MIN(AVERAGE) from GRADUATE where SUBJECT=”PHYSICS”;
.Select SUM(STIPEND) from GRADUATE WHERE div=2;
.Select AVG(STIPEND) from GRADUATE where AVERAGE>=65;
.Select COUNT(distinct SUBJECT) from GRADUATE;

Answer
. SELECT NAME from GRADUATE where DIV = ‘I’ order by NAME;
. SELECT NAME,STIPEND,SUBJECT, STIPEND*12 from GRADUATE;
. SELECT SUBJECT,COUNT(*) from GRADUATE group by SUBJECT having
SUBJECT=’PHYISCS’ or SUBJECT=’COMPUTER SC’;
. INSERT INTO GRADUATE values(11,’KAJOL’,300,’COMPUTER SC’,75,1);
. ALTER TABLE GRADUATE ADD(GRADE CHAR(2));
. (i) 63
ii. 800
iii. 475
iv. 4

98 | Page
Previous Year’s Questions

1. What MySql command will be used to open an already existing database “LIBRARY”? Delhi-11
Ans: USE LIBRARY;

2. The Mname column of a table Members is given below:


Mname
Aakash
Hirav
Vinayak
Sheetal
Rajeev
Based on the information, find the output of the following queries:
(i) SELECT Mname FROM Members WHERE Mname LIKE ‘%v’;
(ii) SELECT Mname FROM Members WHERE Mname LIKE ‘%e%’;
Ans: (i)
Mna
me
Hirav
Rajee
v
(ii)
Mname
Sheetal
Rajeev

3. A table “TRAINS” in a database has degree 3 and cardinality 8. What is the number of rows and
columns in it?
Ans: Rows=8 and Columns=3.

4. Differentiate between Alternate key and Candidate key.


Ans: Candidate Key: A candidate key is the one that is capable of becoming primary key.

Alternate Key: A candidate key that is not primary key is called alternate key.

5. Sarthya, a student of class xi, created a table ‘RESULT’. Grade is one of the column of this
table. To find the details of students whose Grades have not been entered, he wrote the
following MySql query, which did not give the desired result.
SELECT * FROM RESULT WHERE Grade=’Null’;
Help Sarthya to run the query by removing the errors from the query and write the correct
Query.
Ans: SELECT * FROM RESULT WHERE Grade IS Null;

6. Write MySql command to display the list of existing databases.


Ans: SHOW DATABASES;

7. Mr. William wants to remove all the rows from Inventory table to release the storage space, but he
does not want to remove the structure of the table. What MySql statement should he use?1 Ans:
DELETE FROM Inventory;
99 | Page
8. A table FLIGHT has 4 rows and 2 columns and another table AIRHOSTESS has 3 rows and 4
columns. How many rows and columns will be there if we obtain the Cartesian product of these
two tables?
Ans: Rows = 4 rows of FLIGHT × 3 rows of AIRHOSTESS = 12 rows.
Columns = 2 columns of FLIGHT + 4 columns of AIRHOSTESS = 6 columns.

9. Mr. Mittal is using a table 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, Class FROM Students WHERE
Stream_Name=NULL or Stream_Name=’%computers’;
Help Mr. Mittal to run the query by removing the error and write correct query.
Ans: SELECT Name, Class FROM Students WHERE Stream_Name IS
NULL or Stream_Name LIKE ’%computers’;

10. Mr. Sondhi created two tables with DEPTNO as primary key in Table1 and foreign key in Table2.
While inserting a row in Table2, Mr. Sondhi is not able to enter a value in the column DEPTNO.
What could be the possible reason for it?
Ans: The possible reason could be the DEPTNO being entered in Table2 is not
present in Table1 i.e. the referential integrity is imposed.

11. Write a command to add a NOT NULL constraint on Fees column of a Student table.
Ans: ALTER TABLE Student MODIFY Fees INTEGER NOT NULL;

12. Define Foreign Key with reference to RDBMS.


Ans: A non key attribute is called foreign key if it is a primary key of another table.

13. Table BANK has 2 rows and 3 columns. Table CUSTOMER has 4 rows and 3 columns. What will be
the cardinality and degree of the Cartesian product of them?
Ans: Cardinality = Rows = 2 rows of BANK × 4 rows of CUSTOMER = 8 rows.
Degree = Columns = 3 columns of BANK + 3 columns of CUSTOMER = 6 columns.

14. There is a column HOBBY in a Table CONTACTS. The following two statements are giving
different outputs. what may be the possible reason?
SELECT COUNT(*) FROM CONTACTS;
SELECT COUNT(HOBBY) FROM
CONTACTS;
Ans: They are giving different values because there exist NULL values in the column
HOBBY of the table CONTACTS.

15. Mr. Tandon is using table EMP with the following columns.
ECODE, DEPT, ENAME, SALARY
He wants to display all information of employees (from EMP table) in ascending order of
ENAME and within it in ascending order of DEPT. He wrote the following command,
which did not show the desired output.
SELECT * FROM EMP ORDER BY NAME DESC, DEPT;
Rewrite the above query to get the desired output.

100 | Page
Ans: SELECT * FROM EMP ORDER BY NAME, DEPT;

16. Write two examples of DBMS software.


Ans: MySQL and Oracle.

17. What is meant by NULL value in MySQL?


Ans: NULL indicates no value is provided.

18. Table ‘Club' has 4 rows and 3 columns. Table ‘Member’ has 2 rows and 05 columns. What will be
the cardinality of the Cartesian product of them?
Ans: Cardinality = No of Rows = 4 rows of Club Table × 2 rows of Member Table = 8

19. A numeric data field CHANGER contains 25565.7765. Write a commands round off CHANGER to (i)
up to 2 decimal places (i.e., expected result 25565.78) (ii) whole number (i.e., expected result
25566)
Ans: (i) SELECT ROUND(25565.7765,2);
(ii) SELECT ROUND(25565.7765,0); or SELECT ROUND(25565.7765);

20. Gopi Krishna is using a table Employee. It has the following columns:
Code, Name, Salary, Deptcode
He wants to display maximum salary department wise. He wrote the following
command SELECT Deptcode, MAX(Salary) FROM Employee;
But he did not get the desired result. Rewrite the above query with necessary changes to
help him get the desired output.
Ans: SELECT Deptcode, MAX(Salary) FROM Employee GROUP BY Deptcode;

HOTS BASED QUESTIONS

1. What is the purpose of DROP TABLE command in MySql? How is it different from DELETE
command?
Ans: The DROP TABLE command is used to remove a table from the database, and
also removes all of its data. The DELETE command only deletes rows from a
MySQL database but the table remain in the database.

2. Table Employee has 4 records and Table Dept has 3 records in it. Mr. Jain wants to display all
information stored in both of these related tables. He forgot to specify equi-join condition in the
query. How many rows will get displayed on execution of this query?
Ans: 20 rows will get displayed.

Consider the table RESULT given below Write commands in MySql for (i) to (iv) and output
for
(v) to (vii):

101 | Page
(i) To list the names of those students, who have obtained Division as FIRST in the ascending
order of Name.
(ii) To display a report listing NAME, SUBJECT and Annual stipend received assuming that the
stipend column has monthly stipend.
(iii) To count the number of students, who have either Accounts or Informatics as Subject.
(iv) To insert a new row in the table Result: 7, "Mohan", 500, "English", 73, "Second";

Ans: (i) SELECT Name FROM Result WHERE Division=’FIRST’ ORDER BY Name;
(ii) SELECT Name, Subject, Stipend*12 AS ‘Annual Stipend’ FROM Result;
(iii) SELECT COUNT(*) FROM Result WHERE Subject=’Accounts’ OR
Subject=’Informatics’;
(iv) INSERT INTO Result VALUES (7, "Mohan", 500, "English", 73, "Second");

3. Write a MySQL command for creating a table "PAYMENT" whose structure is given below:

CREATE TABLE PAYMENT (


Loan_number INTEGER(4) PRIMARY KEY ,
Payment_number VARCHAR(3) , Payment_date
DATE ,
Payment_amount INTEGER (8) NOT NULL) ;

4. Given below is a table Patient.

102 | Page
(i) Identify the primary key in the given table.
(ii) Write MySQL query to add a column Department with data type varchar and size 30 in the
table Patient.
Ans: (i) Primary key: P_No.
(ii) ALTER TABLE Patient ADD (Department varchar(30));

5. State difference between date functions NOW( ) and SYSDATE( ) of MySql.


Ans: SYSDATE( ) returns the time at which it executes. This differs from the behaviour for
NOW(), which returns a constant time that indicates the at which the statement
began to execute.
Example:

6. Name a function of MySql which is used to remove trailing and leading spaces from a string. 1
Ans: TRIM()

7. Consider the following table named “SBOP” with details of account holders. Write commands of
MySQL for (i) to (iv) and output for (v) to (vi).

(i) To display Accountno, Name and DateOfopen of account holders having transactions more
than 8.
(ii) To display all information of account holders whose transaction value is not mentioned.
(iii) To add another colurnn Address with datatype and size as VARCHAR(25).
(iv) To display the month day with reference to DateOfopen for all the account holders.
(v) SELECT Count(*) FROM SBOP;
(vi) SELECT Name, Balance FROM SBOP WHERE Name LIKE "%i";
(vii) SELECT ROUND(Balance, -3) FROM SBOP WHERE Accountno=”SB- 5";
Ans: (i) SELECT Accountno, Name, DateOfopen FROM SBOP WHERE Transaction>8;
(ii) SELECT * FROM SBOP WHERE Transaction IS NULL;
103 | Page
(iii) ALTER TABLE SBOP ADD (Address varchar(25));

COUNT(*)
5
(iv) SELECT DAYOFMONTH(Dateofopen) FROM SBOP; (v)

Name Balance
Mrs.Sakshi 45000.00

104 | Page
Artificial Intelligence

ArtificialIntelligence(AI)basicallyreferstotheabilityofamachineoracomputerprogram to think
and learn. In simple words, field of AI revolves around
bringingouttechnologiesthathelpbuildmachinesthatcanthink,act,andlearnlikehumans.

An Al based program and technology should be capable of:

● Itshouldbeabletomimichumanthoughtprocessandbehaviore.g.,learning from
mistakes,catchingupwithnewideas,learningnewthingsfromnewexposure,past
experiences(this ability is called heuristics.)etc.
● Itshouldactinahuman-likeway-
intelligent,rational,ethical,i.e.,itshouldtakerightdecisionsinethical ways.

Applications of AI

● Handwriting Recognition
● Gaming
● Intelligent Robots
● Natural Language Processing etc.

Common examples o Al to dayare:

● Humanoid Robot-Sophia
● Sirior 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 likeTesla.
● Online games like Alien:Isolation

MachineLearning

105 | Page
● MachineLearningisasubsystemofArtificialIntelligence,whereincomputers have the
ability to learn from data using statistical techniques, without being explicitly
programmed by a human being.
● Itcomprisesalgorithmsthatusedatatolearnontheirownandmakepredictions.
● These algorithms, called models, are first trained, and tested using a trainingdata 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 (NLP)

● NLP is an artificial intelligence technique that lets machines process


andunderstandlanguagelikehumansdousingcomputationallinguisticscombinedwithm
achinelearning,deeplearning, and statistical modelling.
● The predictive typing (Auto complete) feature of search engine hat helps
usbysuggestingthenextwordinthesentencewhiletypingkeywordsandthespell

106 | Page
checking features are examples of Natural Language Processing(NLP).
● It deals with the interaction between human and computers using human spoken
languages, such as Hindi, English, etc.
Immersive Experiences
● Immersive experiences allow us to visualize, feel and react by stimulating our senses.
It enhances our interaction and involvement, making them more realistic and
engaging.
● Used in driving simulators, flight simulator, videogames and soon.
● Immersive experience can be achieved using virtual reality and augmented reality.

Driving Simulator

Virtual Reality
● VirtualReality(VR)isathree-dimensional,computer-
generatedsituationthatsimulatesthe 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.

● Used in gaming, military training, medical procedures, entertainment etc.

VR Headset

107 | Page
Augmented reality

● The superimposition of computer-generated perceptual information over the existing


physical surroundings is called as Augmented Reality (AR).
● It adds components of the digital world to the physical world, along with the
associated lean do the sensory requirements, there by making the environment
interactive and digitally manipulate able.

Virtual Component+ Reality=Augmented Reality

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:
o NASA’s Mars Exploration Rover (MER) mission is a robotic space mission to
study about the planet Mars.
o Sophiaisahumanoidthatusesartificialintelligence,visualdataprocessing, facial
recognition and also imitates human gestures andfacial expressions.

108 | Page
Bigdataanditscharacteristics

● Data sets of enormous volume and complexity are called BigData.


● Such data cannot be processed and analyzed using traditional data processing tools
as the data is not only voluminous, but also unstructured like our posts, instant
messages and chats, photographs that we share through various sites, our tweets,
blog articles, news items, opinion polls and their comments, audio/video chats, etc.
● Italsoinvolvesvariouschallengeslikeintegration,storage,analysis,searching,processing,
transfer,querying and visualization of such data.

● Characteristics of BigData:
o Volume: Enormous size.
o Velocity: Which the data under consideration is being generated and stored.
o Variety : Data set has varied data, such as structured, semi-structured and
unstructured data. Some examples are text, images, videos, web pages and
soon.
o Veracity: Veracity refers to the trustworthiness of the data. Big data can be
sometimes inconsistent, biased, noisy.
o Value: Bigdata possess to have hidden patterns and useful knowledge.

InternetofThings(IoT)

● The ‘Internet of Things’ is a network of devices that have an embedded hardware and
software to communicate (connect and exchange data) with other devices on the
same network.

109 | Page
● The term computer network that we commonly use is the net work of computers.
● Such a network consists of a laptop, desktop, server, or a portable device like tablet,
smart phone, smart watch, etc., connected through wire or wireless.
● We can communicate between these devices using Internet or LAN.
● IoT tends to bring together these devices to work in collaboration and assist each
other in creating an intelligent network of things.
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-the-
go using our smart phone.

● A smart sensor is a device that takes input from the physical environment and uses
built-in computing resources to perform pre defined 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.

110 | Page
● 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,healthandsanitation,trafficcongestions,publicsafety,andsecurity 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.
● Example:
The smart building uses sensors to detect earthquake tremors and
thenwarnnearbybuildingssothattheycanpreparethemselvesaccordingly.

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
111 | Page
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

CloudServices

● Different computing services delivered through cloud are Infrastructure as aService


(IaaS), Platform as a Service (PaaS), and Software as a Service(SaaS).
● InfrastructureasaService(IaaS):TheIaaSproviderscanofferdifferentkindsof 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.

● SoftwareasaService(SaaS):SaaSprovideson-
demandaccesstoapplicationsoftware,usuallyrequiringalicensingorsubscriptionbytheu
ser.WhileusingGoogledoc,MicrosoftOffice365,DropBox,etc.,toeditadocumentonline,
weuseSaaSfrom
cloud.Auserisnotconcernedaboutinstallationorconfigurationofthesoftwareapplicatio
niftherequiredsoftwareisaccessible.

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
112 | Page
power and storage.
● The constituent resources are called nodes.
● 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 centralize ddatabase
and the transactions performed are updated one by one on
thedatabase.Thatishowtheticketbookingwebsitesorbanksoperate.However,sinceallt
hedataisstoredonacentrallocation,therearechancesofdatabeinghacked 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
ornodethatparticipatesintheblockchainreceivesafullcopyofthedatabase.
● 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
113 | Page
transactions are ensured because all the members in the network keep ac opy of the
block chain and so it is not possible for a single member of the network to make
changes or alter data. Popular application of block chains technology is in digital
currency
Questions

MCQ

1. ___________ are the state-of-the-art technologies, which gain popularity and set a new
trend among users.
a. Emerging trends
b. Popular trends
c. Trends
d. None of the above
2. Example of Artificial Intelligence
a. Google Now
b. Cortana
c. Alexa
d. All of the above

3. Spell checking features are examples of ___________.


a. Data Science
b. Nero Science
c. Natural Language Processing
d. All of the above
4. ___________ deals with the interaction between human and computers using human
spoken languages, such as Hindi, English, etc.
a. Data Science
b. Nero Science
c. Natural Language Processing
d. All the above
5. ___________ allow us to visualize, feel and react by stimulating our senses.
a. Immersive experiences
b. Augmented Reality
c. Virtual Reality
d. None of the above
6. Immersive experiences have been used in the field of __________.
a. Training
b. Driving Simulators
c. Flight Simulator
d. All the above
7. _____________ is a three-dimensional, computer-generated situation that simulates the
real world.

114 | Page
a. Immersive experiences
b. Augmented Reality
c. Virtual Reality
d. None of the above
8. Virtual Reality have been used in the field of __________.
a. Military training
b. Psychology
c. medical procedures
d. All of the above
9. The superimposition of computer-generated perceptual information over the existing
physical surroundings is called as ________.
a. Immersive experiences
b. Augmented Reality
c. Virtual Reality
d. None of the above
10. A ___________ is basically a machine capable of carrying out one or more tasks
automatically with accuracy and precision.
a. Immersive experiences
b. Augmented Reality
c. Virtual Reality
d. Robot
11. What are the different types of robots.
a. Wheeled robots
b. Manipulators
c. Humanoids
d. All of the above

12. NASA’s Mars exploration _________ mission is a a robotic space mission to study about the
planet mars.
a. Rover
b. Sophia
c. Drone
d. None of the above
13. ____________ is a humanoid that uses artificial intelligence, visual data processing, facial
recognition and imitates human gestures and facial expressions.
a. Rover
b. Sophia
c. Drone
d. None of the above
14. A __________ is an unmanned aircraft which can be remotely controlled or can fly
autonomously through software-controlled flight plans in their embedded systems, working
in conjunction with onboard sensors and GPS.
a. Rover
b. Sophia
c. Drone
d. None of the above
15. Network of interconnected items with integrated sensors that can gather and transmit
data in real time is known as the _______.
115 | Page
a. Internet of Things
b. Big Data
c. Model
d. None of the above

16. Today, there are over a billion Internet users, and majority of the world’s web data is
coming from different device, this is the best example of __________.
a. Top Data
b. Big Data
c. Model
d. None of the above
17. What are the different challenges in the big data.
a. Integration
b. Storage
c. Analysis
d. All the above
18. What is the characteristics of big data.
a. Volume & Velocity
b. Variety & Veracity
c. Value
d. All the above
19. ________ 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.
20. ___________ makes use of computer and communication technology along with IoT to
manage and distribute resources efficiently.
a. Smart Cities
b. Smart Ways
c. Smart planner
d. None of the above

VSA 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?
116 | Page
5. Explain NLP.
6. What is VR?
7. Explain AR.
8. Define Robotics.
9. What is big data?
10.What are sensors?
11.Explain IoT.
12.Write about cloud computing.
13.Explain grid computing.
14.ExplainBlockchaintechnology.

SA 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. How is IoT and WoT related?


3. Differentiate between cloud computing and grid computing with suitable
examples.
4. Explain the use of sensors withexample.
5. Five friends plan to try a startup. However, they have a limited budget
andlimited computer infrastructure. How can they avail the benefits of
cloudservicestolaunchtheir startup?
6. Whichisnot oneofthefeaturesofloT devices?
7. MicrosoftOffice365isanexampleofwhichtypeofcloudservicemodel?
8. PaaSofferingstypicallyfollowapay-as-you-gopricingmodel.

Long Answers-QUESTIONS
1. 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?

2. 'Storageofdataiscosteffectiveandtimesavingincloudcomputing.'Justify the
abovestatement.
3. Whatison-demandservice?Howis itprovided incloudcomputing?
4. Writeexamplesofthefollowing:
a) Governmentprovidedcloudcomputingplatform.
b) Largescaleprivatecloudserviceprovidersandtheservices

117 | Page
5. A company interested in cloud computing is looking for a provider whooffers a
set of basic services such as virtual server provisioning and on-demand storage
that can be combined into a platform for deploying
andrunningcustomizedapplications.Whattypeofcloudcomputingmodelfitsthese
requirements?

ANSWERS
MCQ-Answers
1. a. Emerging trends
2. d. All of the above
3. c. Natural Language Processing
4. c. Natural Language Processing
5. a. Immersive experiences
6. d. All of the above
7. c. Virtual Reality
8. d. All of the above
9. b. Augmented Reality
10. d. Robot
11. d. All of the above
12. a. Rover

13. b. Sophia
14. c. Drone
15. a. Internet of Things
16. b. Big Data
17. d. All of the above
18. d. All of the above
19. d. Veracity
20. a. Smart Cities

VSA -ANSWERS
1.
(A) Infrastructure as a Services (IaaS) -Google Drive, Git, Google Docs.
(B) Platform as a Services (PaaS)-Web Server.
(C)Software as a service (SaaS) -Microsoft Office 365
2. ArtificialIntelligence(AI)basicallyreferstotheabilityofamachineoracomputerpro
gram tothinkandlearn.

3. Self-driving cars: Google and Elon Musk have shown us that self-driving cars are
possible. However, self-driving cars require more training data and testing due
to the various activities that it needs to account for, such as giving right of way
or identifying debris on the road.

118 | Page
4. Machine Learning comprises of algorithms that use data
tolearn on their own andmakepredictions.

5. NLPisanartificialintelligencetechniquethatletsmachinesprocessandunderstand
languagelikehumansdo.

6. Virtual Reality (VR) is a three-dimensional, computer-generated situationthat


simulatesthe realworld.

7. ARaddscomponentsofthedigitalworldtothephysicalworld,alongwiththeassociat
ed tactileandothersensory requirements.

8. Arobotics
isbasicallyamachinecapableofcarryingoutoneormoretasksautomaticallywithacc
uracy andprecision.

9. DatasetsofenormousvolumeandcomplexityarecalledBigData.

10.A smart sensor is a device that takes input from the physical environmentand
uses built-in computing resources to perform predefined
functionsupondetectionofspecificinputandthenprocessdatabeforepassingiton.

11.The ‘Internet of Things’ is a network of devices that have an


embeddedhardware and software to communicate (connect and exchange
data) withotherdevicesonthe same network.

12.Computer-based services delivered over the Internet or the cloud, whichcanbe


accessedanywhere usinganysmartdevice

13.Agridisacomputernetworkofgeographicallydispersedandheterogeneous
computationalresources.

14.The blockchain technology works on the concept of decentralized


andshareddatabasewhereeachcomputerhasacopyofthedatabase.
SA –ANSWERS

1. They can use some free services available on public clouds such as Google Drive, AWS
(Amazon Web Services ) etc.
2. IoT (Internet of Things) is about creating a network of objects, things, people, systems and
applications . WoT(Web of Things) tries to integrate the objects ,things and people etc. to
the web using existing web standards.

119 | Page
IoT needs a single universal application protocol to integrate the things. WoT reuses and
leverages readily available and widely popular web protocols, standards and blueprints to
make data and services offered by objects more accessible .
In overall both IoT and WoT provides a facility to control the different devices remotely by
using smartphone or laptop or desktop.

3. Ans:

CloudComputing GridComputing
Oneservertocomputerseveraltasksorservi MultipleServersareallocatedontheSingle
cesconcurrentlyi,eVirtualizationofservice Application.
s.

ItisServiceOrientedi.emorefrequentlyuse Application oriented, i.e. typicallyused for


dtosupportlongservices. job execution for a limitedtime.

MultipleServices SingleApplication
Ondemandservices Maximum computing for
oneapplication.
Acentralcomputerserverwithsingleaccess Adecentralizedsystem,whichspansgeogra
pointandspansseveralcomputingcentres. phicallydistributedsitesand lackofcentral
LikeGoogleandAmazon. control.

Virtualizationofhardware,softwareand Virtualization of data


storageplatforms. andcomputing
resources.
GoogleDrive,OneDrive,MobileApplications GridGain, JPPF,
IBo55Cache,EhCache

4. Sensors are very commonly used for monitoring and observing elementsin
realworldapplications.
Example:Whathappenswhenyouholdyourmobileverticallyorhorizontally?
The display also changes to vertical or horizontal with respect to the waywe hold
our mobile. This is possible with the help of two sensors,
namelyaccelerometerandgyroscope(gyro).Theaccelerometersensorinthemobil
ephonesdetectstheorientationofthephone.Thegyroscopesensorstrack rotation
or twist of your hand and add to the information suppliedbythe accelerometer.

5. They can use some free services available on public


cloudssuchasGoogleDrive,AWS (AmazonWebServices)etc.

120 | Page
6. b)Programmable
7. c)Softwareas aService

8. a)True

LONG -ANSWERS

1. Using blockchain, a complete trial of all the scholarships allotted and the
allotee’s details will be available .Blockchain will ensure that it is available to all
the clients and cannot be compromised or forged .Thus ,it will promote
accountability ,transparency and efficiency in the distribution of scholarships.

2. Incloudcomputing,theon-demandservicesareavailableinstantlyandone has to
pay only for the service and not for the entire infrastructure. Thus,when one
avails storage on a cloud, they just pay for the storage they usedand not for
other infrastructure, hence it is cost-effective. And since cloudservices
arereadilyavailable,these aretime saving too.

3. On-demand services allow users to use a service instantly as and


whenrequired.Thecloudservicesareon-
demandserviceswhichmakeavailablethecloudresourcesatruntime,whenandwh
ereneeded.On-demandcloudservices allow end users to use cloud computing,
storage, software andotherresources instantlyandinmany caseswithoutlimits.

4. a)MeghRaj

b)Drop Box,GoogleDrive,OneDrive

5. c)Infrastructureas aService

121 | Page

You might also like