0% found this document useful (0 votes)
1 views76 pages

12 Computer Science

The document is a student support material for Computer Science for Class XI under Kendriya Vidyalaya Sangathan for the session 2024-25. It includes a detailed syllabus covering topics such as Python functions, exception handling, file handling, data structures, computer networks, and database concepts, along with practical assessments and learning outcomes. The document also outlines the distribution of marks and provides sample question papers for students' preparation.

Uploaded by

kanav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views76 pages

12 Computer Science

The document is a student support material for Computer Science for Class XI under Kendriya Vidyalaya Sangathan for the session 2024-25. It includes a detailed syllabus covering topics such as Python functions, exception handling, file handling, data structures, computer networks, and database concepts, along with practical assessments and learning outcomes. The document also outlines the distribution of marks and provides sample question papers for students' preparation.

Uploaded by

kanav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

KENDRIYA VIDYALAYA SANGATHAN

STUDENT SUPPORT MATERIAL


(Computer Science)
Class – XI
SESSION: 2024-25

Chief Patron : Ms. Nidhi Pandey, IIS


Commissioner, KVS , New Delhi
Patron : Shri Sardar Singh Chauhan,
Dy. Commissioner, KVS Delhi Region
Guidance : Shri Ghanshyam Panday,
Asstt. Commissioner, KVS Delhi Region
Co-ordinator : Shri Sandeep Arora,
Vice Principal, PM Shri KV JNU, Delhi

Content Contributors
 Sh. Deepak Chand PM SHRI, K V Tagore Grden  Mrs. Savita
Chourisya , PGT CS PM SHRI, KV JNU  Mrs. Monika Rani K V AAI
Rangpuri  Sh. Pawan Kumar Ruhela K V Shahdra  Mrs. Kanchan
Khurana PM SHRI K V Sec-5 Dwarka  Sh. Pawanjeet Singh PM
SHRI K V Delhi Cantt- 2  Sh. Tara Chand Meena PM SHRI KV Delhi
Cantt-3  Sh. Vijay Chawala PM SHRI K V Pitampura  h. Aman
Singh PM SHRI Sanik Vihar  Mrs. Vani Kochhar PM SHR I KV
Arjangarh
2|Page

UNIT NO. UNIT / CHAPTER NAME PAGE NO.


INDEX

1. REVISION OF CLASS XI 7-26 2. PYTHON FUNCTIONS 26- 29 3.

EXCEPTION HANDLING IN PYTHON 29-32 4. FILE HANDLING 33-51

DATABASE CONCEPTS COMPUTER


5. DATA STRUCTURE 51-54 6. 55-90 7.

NETWORKS
91-113
8. SAMPLE QUESTION PAPER - I 114- 121

9. SAMPLE QUESTION PAPER – II 122-133


10. SAMPLE QUESTION PAPER – III 134-146

3|Page
Computer Science (2024-25) CLASS XII Code No. 083
Computer Science- Class XII

1. Learning Outcomes

Student should be able to


a) apply the concept of function.
b) explain and use the concept of file handling.
c) use basic data structure: Stacks
d) explain basics of computer networks.
e) use Database concepts, SQL along with connectivity between Python and SQL.

2. Distribution of Marks:

Unit No. Unit Name Marks Periods Theory Practical


1 Computational Thinking and 40 70 50
Programming – 2
2 Computer Networks 10 15 …

3 Database Management 20 25 20
Total 70 110 70

3. Unit wise Syllabus


Unit 1: Computational Thinking and Programming – 2
● Revision of Python topics covered in Class XI.
● Functions: types of function (built-in functions, functions defined in module, user
defined functions), creating user defined function, arguments and parameters,
default parameters, positional parameters, function returning value(s), flow of
execution, scope of a variable (global scope, local scope)
● Exception Handling: Introduction, handling exceptions using try-except-finally
blocks ● Introduction to files, types of files (Text file, Binary file, CSV file), relative
and absolute paths

4|Page
● Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a text
file, opening a file using with clause, writing/appending data to a text file using
write() and writelines(), reading from a text file using read(), readline() and
readlines(), seek and tell methods, manipulation of data in a text file
● Binary file: basic operations on a binary file: open using file open modes (rb, rb+,
wb, wb+, ab, ab+), close a binary file, import pickle module, dump() and load()
method, read, write/create, search, append and update operations in a binary file
● CSV file: import csv module, open / close csv file, write into a csv file using
writer(),writerow(),writerows() and read from a csv file using reader()
● Data Structure: Stack, operations on stack (push & pop), implementation of stack
using list.

Unit 2: Computer Networks

● Evolution of networking: introduction to computer networks, evolution of networking


(ARPANET, NSFNET, INTERNET)
● Data communication terminologies: concept of communication, components of
data communication (sender,receiver, message, communication media,
protocols), measuring capacity of communication media (bandwidth, data
transfer rate), IP address, switching techniques (Circuit switching, Packet
switching)
● Transmission media: Wired communication media (Twisted pair cable, Co-axial
cable, Fiber-optic cable), Wireless media (Radio waves, Micro waves, Infrared
waves) ● Network devices (Modem, Ethernet card, RJ45, Repeater, Hub, Switch,
Router, Gateway, WIFI card)
● Network topologies and Network types: types of networks (PAN, LAN, MAN,
WAN), networking topologies (Bus, Star, Tree)
● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET,
VoIP ● Introduction to web services: WWW, Hyper Text Markup Language
(HTML), Extensible Markup Language (XML), domain names, URL, website, web
browser, web servers, web hosting
Unit 3: Database Management
● Database concepts: introduction to database concepts and its need
● Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys
(candidate key, primary key, alternate key, foreign key)
● Structured Query Language: introduction, Data Definition Language and Data
Manipulation Language, data type (char(n), varchar(n), int, float, date), constraints
(not null, unique, primary key), create database, use database, show databases,
drop database, show tables, create table, describe table, alter table (add and
remove an attribute, add and remove primary key), drop table, insert, delete, select,
operators (mathematical, relational and logical), aliasing, distinct clause, where
clause, in, between, order by, meaning of null, is null, is not null, like, update
command, delete command, aggregate functions (max, min, avg, sum, count),
group by, having clause, joins: cartesian product on two tables, equi-join and natural
join
● Interface of python with an SQL database: connecting SQL with Python, performing

5|Page
insert, update, delete queries using cursor, display data by using connect(), cursor(),
execute(), commit(), fetchone(), fetchall(), rowcount, creating database connectivity
applications, use of %s format specifier or format() to perform queries

4. Practical
[Link] Unit Name Marks (Total=30)
Lab Test:
8
1. Python program (60% logic + 20%
1
documentation + 20% code quality)

2. SQL queries (4 queries based on one


4
or two tables)

Report file:
 Minimum 15 Python programs.
 SQL Queries – Minimum 5 sets
2
7
using one table / two tables.
 Minimum 4 programs based on
Python – SQL connectivity

3 Project (using concepts learnt in Classes 11


8
and 12)
4 Viva voce 3
6|Page
KENDRIYA VIDYALAYA SANGATHAN (DELHI REGION)
STUDENT SUPPORT MATERIAL
CLASS XII
SUBJECT: - COMPUTER SCIENCE (083)
REVISION OF CLASS XI
Some key features of Python Programming Language: -
 Interpreter based programming language: - Python is an interpreter-based programming
language which execute the source code line by line.
 Ease to code and read: - It is very easy to write the code in python and indented blocks also
make it easy to read.
 Free and Open Source: - Python programming language is available free to use for
commercial purposes.
 Portable: - The code written in Python can be executed on different
machine.  Object Oriented Support: - It supports both procedural and
OOPs.
 Dynamic typing: - Variable data type can be decided at runtime.
 Robust Standard library: - Extensive standard library available for anyone to
use. Different ways to run the python code: -
 Interactive Mode: - Interactive mode is used when a user wants to run one single line or one
block of code within command line known as python shell.

 Script Mode: - Script mode is used when a user is working with more than one single code or
block of code. The block of code is written within a text file with file extension “.py”

Indentation
 Indentation refers to the blank spaces at the beginning of a code line. Generally indentation
indicates the starting of a block of an if……else , if…..elif, for……, while……… or user
defined function started with the keyword “def”.
Comments
 In python programming language comments are a type of non-executable statement that is
used for documentation purpose. It is of two types: -
o Single line comment
o Multiline comment
7|Page
Single line comment: - Single line comment starts with the symbol “#”.
Multiline comment: - Multiline comments always enclosed with triple quotes i.e. ‘ “”” “”” ’

Python character set


 A character set is a set of valid characters supported by python programming
language.  Python supports all ASCII / Unicode characters that include:
 Alphabets: All capital (A-Z) and small (a-z) alphabets.
 Digits: All digits from 0-9.
 Special Symbols: Python supports all kinds of special symbols - " ' l ; : ! ~ @ # $
% ^`&*()_+–={}[]\.
 White Spaces: White spaces like tab space, blank space, newline, and
carriage return.
 Other: All ASCII and UNICODE characters are supported by Python that
constitutes the Python character set.
Python Tokens: - The smallest individual unit in a program is known as a Token or a lexical unit.
Python has following tokens:-
i. Keywords
ii. Identifiers (Names)
iii. Literals
iv. Operators
v. Punctuators
Keywords:- Python has a set of keywords that are reserved words and cannot be used as variable
names, or any other identifiers:-
S. No. Name of Keyword Description

1. And A logical operator


2. As To create an alias
3. Assert For debugging
4. class To define a class
5. Continue To continue to the next iteration of a loop 6. Def To
define a function
7. del To delete an object
8. elif Used in conditional statements, same as else if 9. Else Used in
conditional statements
10. Except Used with exceptions, what to do when an exception occurs 11. False
Boolean value, result of comparison operations 12. finally Used with exceptions, a
block of code that will be executed no matter if there is an exception or not
13. for To create a for loop
14. from To import specific parts of a module

8|Page
15. global To declare a global variable
16. if To make a conditional statement
17. import To import a variable
18. in To check if a value is present in a list, tuple etc. 19. is To test if
two variables are equal
20. lambda To create an anonymous function
21. None Represents a null value
22. nonlocal To declare a non-local variable
23. not A logical operator
24. or A logical operator
25. pass A null statement, a statement that will do nothing 26. raise To
raise an exception
27. return To exit a function and return a value
28. True Boolean value, result of comparison operations 29. try To make
a try...except statement
30. while To create a while loop
31. with Used to simplify exception handling
32. yield To return a list of values from a generator

Identifiers (Names):- Identifiers are the names given to different parts of the program viz
variables, objects, classes, functions, lists, dictionaries and so forth. Python is a case
sensitive language as it treats upper and lower-case characters differently.
The naming rules for Python identifiers are:-
 It must only be a non-keyword with no space in between.
 It must be made up of only letters, numbers, and underscore(_).
 It cannot begin with a number, although they can contain numbers.
The following are some valid identifiers:-
Name DATE8_3_4 Age _DS
_amount ADD14 T2Z0T _STU
The following are some invalid identifiers:-
N-ame contains special character – (hyphen) other than A-Z, a-z and _(underscore)
83Date Starting with a digit
break reserved word/ keyword
[Link] contains special character dot(.)
Literals:- Literals are the values supported by a python program and are often
referred to/ by an identifier. Python support following types of literals: -
 String Literals: - A string literal is a sequence of characters surrounded by
quotes (single, double or triple). String literals can either be single or multi-line
strings.

9|Page
Escape Sequences: - In strings, you can include non-graphic characters
through escape sequences. Escape sequences are given in following tables: -

 Numeric Literals: - A number represented in various forms is a numeric literal. o


Integer Literal: It includes both positive and negative numbers along with 0. It
doesn’t include fractional parts. It can also include binary, decimal, octal,
hexadecimal literal.
o Float Literal: It includes both positive and negative real numbers. It also
includes fractional parts. 99.62, 0.35E-7 are valid float literals.
o Complex Literal: It includes a+bj numeral, here a represents the real part
and b represents the complex part.
 Boolean Literals: - A Boolean literal in Python is used to represent one of the
two Boolean values i.e. True (Boolean true) or False (Boolean false).
 Special Literal None: - Python has one special literal, which is None literal and
is used to indicate absence of value.

Operators: - Operators are responsible for performing various operations in Python. The operators
are of two types Unary (Operates on single operand) and Binary Operators (operates on two
operands).
 Arithmetic Operators: Arithmetic operators are used with numeric values to
perform common mathematical operations:
Operators Name Example
+ Addition 30+90 gives 120
- Subtraction 90-30 gives 60

10 | P a g e
* Multiplication 40*10 gives 400
/ Division 12/3 gives 4.0
// Floor Division 10//3 gives 3
10.0 //3 gives 3.0
% Modulus 20%3 gives 2
** Exponentiation 4**2 gives 16

 Relational Operators: - These are used to compare two values and returns a True
or False.
Operator Name Example
== Equal to/ comparison 20==20 is True
!= Not Equal to 20!=20 is False
> Greater than 20>7 is True
< Less than 20<7 is False
>= Greater than or Equal to 20>=7 is True
<= Less than or Equal to 20<=20 is True

 Logical Operators: - Logical operators are generally used to combine two or more
conditions within if or loop and returns True or False.
Operator Description Example
and Returns True if both statements are True 20==20 and 30>10 It will return True 20==20 and
or Returns True if any or both the statements are True 30<10 It will return True

not Reverses the result not(22==22) is False

 Membership Operators: - Python’s membership operators test for membership in a


sequence such as string, list or tuple. There are two membership operators as
explained below: -
Operator Description Example
in Returns True if a sequence with the x = ["apple", "banana"]
specified value is present print("banana" in x)
in the object # returns True because a sequence with the value
"banana" is in the list

not in Returns True if a x = ["apple", "banana"]


sequence with the print("pineapple" not in x)
specified value is not # returns True because a
present in the object sequence with the value
"pineapple" is not in the list

 Identity Operators: - Identity operators are used to compare the objects, not if they
are equal, but if they are actually the same object, with the same memory location:
Operator Description Example
is Returns x = ["apple", "banana"]
True if both y = ["apple", "banana"]
variables z=x
are the print(x is z)
same # returns True because z is the same object
object as x print(x is y)
# returns False because x is not the same
object as y, even if they have the same
content print(x == y)
# to demonstrate the difference between "is"

11 | P a g e
and "==": this comparison returns True because
x is equal to y
is not Returns x = ["apple", "banana"]
True if both y = ["apple", "banana"]
variables z=x
are not the print(x is not z)
same # returns False because z is the same
object object as x
print(x is not y)
# returns True because x is not the same
object as y, even if they have the same
content print(x != y)
# to demonstrate the difference between "is
not" and "!=": this comparison returns False
because x is equal to y

 Operator Precedence: - In a mathematical or logical expression, the operator


precedence plays an important role to decide which operator will be executed first.
The following table elaborates their precedence.
Operator Remarks
( ) Even though ( ) is not an operator but it plays an important role in
deciding which part of the
expression should be evaluated first.
** The unique feature of ** is that it is the only operator that is evaluated
from right to left.
*, /, //, % All the four have same precedence. Thus, left most will be
executed first if all come in an expression.
+, - Both have same precedence.
== != > >= < <= is is not in not in All the relational, identity and membership operators
Not “Not” being a unary operator has precedence over the logical
operators “and/or”
And Have higher precedence over logical operator
“or”

 Punctuators: - Punctuators are symbols that are used in programming languages


to organize sentence structures, and indicates the rhythm and emphasis of
expressions, statements, and program structure.
Most common punctuators of Python programming language are:-
‘ “ # \ () [] {} @ , : . ` =
 Expressions: - An expression is defined as a combination of constants, variables,
and operators. An expression always evaluates to a value. A value or a
standalone variable is also considered as an expression but a standalone
operator is not an expression.
(i) 100 (iv) 3.0 + 3.14
(ii) num (v) 23/3 -5 * 7(14 -2)
(iii) num – 20.4 (vi) "Global" + "Citizen"
 Statement Flow Control: - The statement flow of control specifies that in what different the
statements of a program may be executed viz sequentially, selectively or iteratively. It may
be of three types: -
i. Sequential flow of control
ii. Selection flow of control
iii. Iteration flow of control
12 | P a g e
Sequential flow of control The Statement/s print("Number is Zero") elif(a>0):
statements execute sequentially else: print("Number is Positive") else:
one after another, as written in Statement/s print("Number is negative")
program. Program Output
x=10 30
Selection flow of control The y=20
statements execution depends print(x+y)
upon some conditions. It contains
decision making statements (if, elif,
else) Program Output
a=int(input("Enter any integer Enter any integer number: 5
if condition: number :"))
Statement/s if(a==0): Number is Positive
elif condition:

Iteration flow of control Program Output

The statements of a
program repeat for a
given number of times. It
can be of two types: -
1. while loop
2. for loop
Syntax of while loop: n=1
- while(condition): while(n<4): India India India
Statement/s print("India ", end=“ ")
n=n+1
Syntax of for loop: -
for value in sequence: for i in range(1,6):
Statement/s print(i, end=' ') 12345

Jump Statements Program Output


(break, continue, pass)
for i in range(1,11): 1 2 hello 4 6 7
Syntax if(i==3):
for val in sequence: print("hello", end=' ')
if (val== i): continue
break if(i==8):
if (val== j): break
continue if(i==5):
if (val== k): pass
pass else:
print(i, end=’ ‘);

 range () function in python: The range() function returns a sequence of numbers, starting
from 0 by default, and increment by 1 (by default), and stops before the specified number.
13 | P a g e

range() example Output sequence


range(10) 0 1 2 3 4 5 6 7 8 9
range(1,11) 1 2 3 4 5 6 7 8 9 10
range(1,11,2) 1 3 5 7 9
range(10,0,-1) 10 9 8 7 6 5 4 3 2 1

Questions (MCQ):
Q.1 Which one of the following is not a valid identifier?
a) true
b) __init__
c) 20Decades
d) My_var
Q.2 Which of the following keywords is a python operator?
a) for
b) break
c) is
d) else
Q.3 What will be the output of the operation print("\\\\\\") ?
a) \\\\\\
b) \\\
c) \\
d) Error
Q.4 What will be the output of the expression print(10+20*10//2**3-5)
a) 30
b) 40
c) 1005
d) 130
Q.5 Evaluate the expression print(20%-3)?
a) -1
b) -2
c) 2
d) Error
Q.6 What will be the result of the expression True or False and not True or True
a) True
b) False
c) None
d) Error
Q.7 What will be the output of the following program?
a = {'A':10,'B':20}
b = {'B':20, 'A':10}
print(a==b and a is b)

14 | P a g e
a) True
b) False
c) None
d) Error
Q.8 Which of the following statements is false for python programming language?
a) Python is free and Open source.
b) Python is statically typed.
c) Python is portable.
d) Python is interpreted.
Q9. Which of the following is valid arithmetic operator in Python:
(i) //
(ii) ?
(iii) <
(iv) And
Q10 Find and write the output of the following python code:
. x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")

Very Short answer type questions


Q1. What are the tokens in Python?
Q2. How are keywords different from identifiers?
Q3. What are literals in python? How many types of literals are allowed in
Python? Q4. How are string literals represented and implemented in Python?
Q5. What are operators? What is their function?
Q6. What are variables? How are they important for a program?
Q7. What is entry control loop?
Q8. What is exit control loop?
Q9. What is mutable data type?
Q10. What is immutable data type?
Short answer type questions
Q1. What is the difference between a keyword and an identifier?
Q2. What are literals in Python? How many types of literals are allowed in
python? Q3. What is None literal?
Q4. What are data types? What are python built-in data types?
Q5. What is the role of comment and indentation in a program?
Q6. What is a statement? What is the significance of an empty statement?
Q7. What do you mean by term iteration?
Q8. Rewrite the following code after removing all the syntax error (s):
30=T
for K in range (0,To):
IF k%4 == 0:
print(K*4)
Else:
print(K+3)
Q9. Write a program that asks the user to input number of seconds and then expresses it in terms
of minutes and seconds it contains.
Q10. How many types of strings are supported in Python?

15 | P a g e
Long answer type questions
Q1. Write a program to print one of the words negative, zero, or positive, according to whether
variable x is less than zero, zero or greater than zero, respectively.
Q2. Write a program that returns True if the input number is an even number, False otherwise. Q3.
Write a program that calculates and prints the number of seconds in a year. Q4. Write a program
that accepts two integers from the user and prints a message saying first number is divisible by
second number or not.
Q5. Write a program to calculate the factorial of any given number N.
Python String
 Python strings are a set of characters enclosed in single quotes, double quotes, or triple
quotes.  Python strings are immutable - Once a string is created, it cannot be changed. You
can create a new string with the desired modifications, but the original string remains
unchanged.  Python Strings are ordered: Strings maintain the order of characters in the
sequence.  This means that the characters in a string have a definite order, and this order will
not change.  Python Strings are iterable. You can iterate over the characters in a string using
loops like for loops or comprehensions.
 Characters in a String are indexable: Each character in a string can be accessed using an
index. Indexing starts from 0, so the first character of a string has an index of 0, the second
character has an index of 1, and so on.
String examples:

Accepting a string from user: We can use input() method to accept a string from the

user.
String operations:
 Concatenation: More than one string can be joined using the (+) operator to create
a new string.

 Replication: A string can be multiplied by a number to create replicated

string.
16 | P a g e
 Indexing: Each character of a string can be accessed using two types of indexing. o
Forward indexing: First character of a string has an index 0 and next has 1 and
so on.
o Reverse indexing: Last character of the string is having an index of -1 and last
but one has -2 and so on.
We can access any

element of the string using indexing.


 Slicing: A substring can be
acquired from
an existing string using the
slicing
operation.

 Traversal: We can traverse a string using iteration and specifically using for
loop. o Iterate using membership

o Iterate using indexing

 String Methods: Python has a few built-in and string library methods (also built-in) to
manipulate strings. Some of them as elaborated below with examples.
o Global Methods/ functions: These functions accept string as a parameter –
Syntax:- methodName(string)

17 | P a g e
o String Library Methods: These methods have the syntax: -
[Link]()
o Methods that return True or False:
isalnum() – Returns True is the string comprises of only alphabets and

digits
isalpha() – Returns True if all the characters are Alphabets

isdigit() – Returns True if all the characters are digits.

isspace() – Returns True if all the characters are spaces

isupper() – Returns True if all the characters are upper-case alphabets

islower() – Returns True if all the characters are lowercase alphabets

startswith(substr) – Returns True if a string starts with the given

substring.
endswith(substr) – Returns True if a string ends with the given

substring.
o Methods that return a number based on the requirement:
18 | P a g e
count(substr) – counts the occurrence of a substring inside a string.
The general format of this function is count(substr, start, stop) where
stop index is not included. Both start and stop are optional.
index(substr) – Returns the index of the first occurrence of a substring
inside a given String. The general format of this method is index(substr,
start, stop) where stop index is not included. Both start and stop are
optional.

find(substr) – Returns the index of the first occurrence of a substring inside a


given String. The general format of this method is find(substr, start, stop)
where stop index is not included. Both start and stop are optional. This is
same as index()
index(substr) find(substr)
This function throws a This function returns -1
ValueError if the if the substring is
substring is missing missing from the
from the string. string.

Python List

19 | P a g e
 Characteristics of List:-
 Ordered collection of objects - Lists maintain the order of elements as they are
inserted.
 Lists are mutable - Lists can be modified after creation. You can add, remove, or
modify elements freely.
 Heterogenous - Lists can contain elements of different data types. For example, a list
can contain integers, strings, floats, and even other lists.
 Dynamic - Lists in Python can grow or shrink in size dynamically. You can append new
elements, insert elements at specific positions, or remove elements as needed. 
Indexed - Elements in a list are indexed with integers starting from 0. This allows for
easy access to individual elements using their index.
 Nesting - Lists can contain other lists as elements, allowing for the creation of nested
data structures.
 Built-in Methods - Python lists come with built-in methods for various operations like
sorting, reversing, searching, etc., making them versatile for a wide range of tasks. 
Iterable - Lists can be used in iterations using loops (e.g., for loop)
 Slicing - Lists support slicing operations, allowing you to extract sub-list by specifying a
range of indices.

 List operations (concatenation, repetition, membership & slicing) :  Concatenation: - Python


allows us to join two or more lists using concatenation operator depicted by the symbol
+.
#list1 is list of first five odd integers
>>> list1 = [1,3,5,7,9]
#list2 is list of first five even integers
>>> list2 = [2,4,6,8,10]
#elements of list1 followed by list2
20 | P a g e
>>> list1 + list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
>>> list3 = ['Red','Green','Blue']
>>> list4 = ['Cyan', 'Magenta', 'Yellow' ,'Black']
>>> list3 + list4
['Red','Green','Blue','Cyan','Magenta', 'Yellow','Black']
 Repetition: - Python allows us to replicate a list using repetition operator depicted by
symbol *.
>>> list1 = ['Hello']
#elements of list1 repeated 4 times
>>> list1 * 4
['Hello', 'Hello', 'Hello', 'Hello']
 Membership: - Like strings, the membership operators in checks if the element is
present in the list and returns True, else returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'Green' in list1
True
>>> 'Cyan' in list1
False
 Slicing: - Like strings, the slicing operation can also be applied to
lists. >>> list1 = ['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
 Traversing a list using loops: - We can access each element of the list or traverse a list
using a for loop or a while loop.
o List Traversal Using for Loop:
>>> list1 = ['Red','Green','Blue','Yellow', 'Black']
>>> for item in list1:
print(item)
Output:
Red
Green
Blue
Yellow
Black
o List Traversal Using while Loop:
# creating a list
countries = ["USA", "CHINA", "BRAZIL", "TURKEY"]

# starting at 0 index
i=0

# using a while loop


while i < len(countries):
print(countries[i])

# giving an increment of 1 to i
i=i+1

21 | P a g e
Output:
USA
CHINA
BRAZIL
TURKEY
Python Tuple
 A tuple is an ordered sequence of elements of different data types, such as integer, float,
string, list or even a tuple. Elements of a tuple are enclosed in parenthesis (round brackets)
and are separated by commas. Like list and string, elements of a tuple can be accessed
using index values, starting from 0
o Indexing: - Elements of a tuple can be accessed in the same way as a list or string
using indexing and slicing.
o Tuple is Immutable: Tuple is an immutable data type. It means that the elements of a
tuple cannot be changed after it has been created. An attempt to do this would lead to
an error.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment
o Tuple operations:
 Concatenation: - Python allows us to join tuples using concatenation operator
depicted by symbol +. We can also create a new tuple which contains the
result of this concatenation operation.
>>> tuple1 = (1,3,5,7,9)
>>> tuple2 = (2,4,6,8,10)
>>> tuple1 + tuple2
#concatenates two tuples
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
 Repetition: - Repetition operation is depicted by the symbol *. It is used to
repeat elements of a tuple. We can repeat the tuple elements. The repetition
operator requires the first operand to be a tuple and the second operand to be
an integer only.
>>> tuple1 = ('Hello','World')
>>> tuple1 * 3
('Hello', 'World', 'Hello', 'World', 'Hello', 'World')
 Membership: - The in operator checks if the element is present in the tuple and
returns True, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' in tuple1
True
 Slicing: - Like string and list, slicing can be applied to tuples also.
#tuple1 is a tuple
>>> tuple1 = (10,20,30,40,50,60,70,80)
Python Dictionary
 Python dictionaries are collection of key value pairs enclosed in {}. Python dictionaries are un
ordered. Python dictionary keys are immutable (numbers, string, tuple). Python dictionary
values are mutable.
Dictionary Examples:
22 | P a g e

Dictionary Operations:
 Displaying Values for a given Key: We can use dictName[key] to get the

value.
 Adding a Key-Value pair to a dictionary: We can add a key-value pair to a dictionary
using the syntax dictName[key]=value. In case we are trying to add an existing key,
then the latest value will replace the old value of the existing key without adding a
new key value pair.

 Dictionary Methods: Like Strings and lists, dictionaries too have global and member
functions.
* Global functions: The global functions include len(), max(),
min(), sum() and

* Dictionary

Member Methods: These methods are called


using the syntax [Link]()
clear() – Removes all the elements from the dictionary and makes it empty. copy() – Creates
a copy of the existing dictionary.
get(key) – Returns the value for a given key.

23 | P a g e
keys() – Returns a view object containing the keys of the dictionary, that can be
converted to list using a list() method.

values() - Returns a view object containing the values of the dictionary, that can
be converted to list using a list() method.
items() - Returns a view object containing the key-value pairs as tuples of the

dictionary, that can be converted to list of tuples using a list()


method.
update() – Used to add the contents of one dictionary as key-value pairs in
another dictionary.

pop(key) – Removes a key-value pair from a dictionary and returns only the
value.

popitem() – Removes the last added key-value pair from the dictionary and returns a
tuple containing the removed key-value pair.

Questions (MCQ)
Q.1 Which is the correct form of declaration of dictionary?
(i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
(ii) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
(iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
(iv) Day={1’monday’,2’tuesday’,3’wednesday’]
Q.2 Identify the valid declaration of L:
L = [1, 23, ‘hi’, 6].
a) list
b) dictionary
c) array
d) tuple
24 | P a g e
Q.3 Suppose a tuple Tup is declared as Tup = (12, 15, 63, 80),
which of the following is incorrect?
a) print(Tup[1])
b) Tup[2] = 90
c) print(min(Tup))
d) print(len(Tup))
Q.4 What will be the output of the following python statement?
s = "HOME ALONE"
p = [Link]("O")
print(p[1][:2]+p[-1])
a) ALNE
b) MENE
c) MEONE
d) MEAL
Q.5 What is the output of print("hello".find('E'))?
a) 1
b) 2
c) -1
d) Error
Q.6 For the given list
d=[10,30,20,15,45,50,80,90]
what will be the output of the following slicing operation:
d[2:7:2]
a) [20,15,45]
b) [20, 45, 80]
c) [30, 15, 50]
d) [20, 45]
Q.7 What will be the output of the following?
d = {"A":10, "B":20, "C":30, "A":40}
print(d)
a) {"A":10, "B":20, "C":30, "A":40}
b) {"A":40, "B":20, "C":30}
c) {"A":50, "B":20, "C":30}
d) KeyError
Q.8 Given the lists L=[“H”, “T”, “W”, “P”, “N”]
Write the output of print(L[3:4])

Q9. If the following code is executed, what will be the output of the following code?
str="KendriyaVidyalayaSangathan"
print(str[8:16])
Q10. Write a statement in Python to declare a dictionary whose keys are 1,2,3 and
values are Apple, Mango and Banana respectively.

Very Short type Questions

Q1. What is the internal structure of Python String?


Q2. Discuss the utility and significance of list, briefly.
Q3. What is the difference between a list and tuple?
Q4. What is the difference between (30) and (30,)?
Q5. Why a dictionary is termed as an unordered collection of object?
Q6. Write a python script that traverses through an input string and print its characters in
different lines.
Q7. What do you mean by mutability? What does “in place” task mean?
25 | P a g e
Q9. What type of objects can be used as keys in dictionary?
Q10. Discuss the utility and significance of a tuple.

Short type Questions


Q1. What is indexing in context to python string? Why is it also called two-way
indexing? Q2. What is string slice? How is it useful?
Q3. Find and write the output of the following python code:
x=”abcdef”
i=”a”
while i in x:
print(i, end=” “)
Q4. How are lists different from strings when both are sequences?
Q5. What will be the output of the following code snippet?
values=[]
for i in range(1,4):
[Link](i)
print(values)

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


rec={“Name” : “Python”, “Age”:”20”}
r= [Link]()
print(id(r)==id(rec))
Q7. How are tuples different from lists when both are sequences?
Q8. How can you say that a tuple is an ordered list of objects?
Q9. How are dictionaries different from lists?
Q10. When are dictionaries more useful than lists?
Long answer type questions
Q1. Write a program to print all even elements available within a list L.
Q2. Write a program to find out and element’s index/position in a tuple WITHOUT using
index(). Q3. Write a program that checks for presence of a value inside a dictionary and
prints its key. info={‘Riya’: ‘CS’, ‘Mark’:’Eco’, ‘Ishpreet’: ‘Eng’, ‘Kamal’: ‘EVS’}
Q4. Write a program that creates a list of all integers less than 100 that are multiples of 3
or 5. Q5. Write a program to that creates a tuple storing firs 9 terms of Fibonacci Series.
Python Functions
Python Function: - Functions is a block of code that perform a task and is identified by its name. A
function can be executed by calling it. Writing the name of the function will call a function. Functions
are internally declared in a separate memory area. So, a function can declare variables with the
same as declared in the outer part of the program.
Type of function: - i. Built-in function (all functions defined by python min( ), max( ), len( )
etc, ii. User-defined functions (defined by the user)
Advantage of function: -
1. Reduces the size of the program
2. Improves reusability of code
3. Easy debugging
def keyword: - def keyword declares a user defined function followed by parameters and
terminated with a colon.
Return keyword: - Whenever the return keyword is executed inside a function it returns the control
back to its caller along with some value if passed explicitly. Writing return is not compulsory and we
can write as many return keywords as needed but only one return keyword is executed.

26 | P a g e
Actual parameters: - When we call a function and pass some values to the function. These passed
values are called actual parameters.
Formal parameters: - The parameters declared in the header part of the function is called formal
parameters or the values received by the functions from its caller is called formal parameters.
Default parameters: - It is formal parameters with the assignment of values. These values are used
if the caller does not provide value to that parameter. Remember default parameters are written
after positional parameters (whose position is fixed while calling a function).
def < name of the function> (formal parameters):
function body is always written in tab indentation
code here
code here
out of scope of function. The function call can be placed after this part.
Example: -
def myfunction(a,b,c=10) : #a, b and c is formal parameter and c is with default values
print(a,b,c)
return (a+b+c)
total = myfunction(10,20,30) # 10 20 and 30 are actual parameter.

Questions (MCQ)

Q.1 What is the default return value for a function that does not return any value exp
(Q)None
(ii) int
(iii) double
(iv) null
Q.2 Which of the following items are present in function header?
a) function name only
b) both function name and parameter only
c) parameter list only
d) return value
Q.3 Which of the following keywords marks the beginning of the function block?
a) func
b) define
c) def
d) function
Q.4 What is a variable defined outside all the functions referred to as ?
a) A static variable
b) A global variable
c) A local variable
d) An automatic variable
Q.5 What is the result of this code?
def print_double(x):
print(2**x)
print_double(3)
a) 8
b) 6
c) 4
d) 10
Q.6 A void function also returns a ____________ value to its caller.
Q.7 def fun2(list1):
for x in list1:

27 | P a g e
print([Link](),end=”#”)
fun2([‘Rajesh’,’Kumar’])
Q.8 Consider the following function headers. Identify the correct statement: -
1) def correct(a=1,b=2,c):
2) def correct(a=1,b,c=3):
3) def correct(a=1,b=2,c=3):
4) def correct(a=1,b,c):
Q9. What will be the output of the following code?
A=1
def f():
a=10
print(a)
Q10 Find and write the output of the following python code:
. a=10
def call():
global a
a=15
call()
print(a)

Very Short Answer Type Questions


Q.1. What do you mean by modularity?
Q.2. What is a function call?
Q.3. Name the three categories of functions.
Q.4. What is the role of an argument of a function?
Q.5. What are docstrings?
Q.6. What are docstring conventions?
Q.7. Name the constant available in math module.
Q.8. Write two ways in which you are able to use constant pi in your
programs. Q.9. What is a function?
Short Answer Type Questions
Q. 1. Find and write the output of the following Python code:
def fun(s):
k= len(s)
m=””
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+’bb’
print(m)
fun(‘school2@com’)

Q. 2. What do you understand by local and global scope of variables? How can you access a
global variable inside the function, if function has a variable with same name.
Q. 3. What are the differences between parameters and arguments?
Q. 4. What are default arguments?
Q. 5. What are keyword arguments?
Q. 6. What are the advantages of keyword arguments?
Q. 7. What are the advantages of dividing a program into modules.
28 | P a g e
Q. 8. Differentiate between Built-in functions and user defined functions.
Q. 9. Differentiate between Built-in functions and functions defined in modules. Q. 10. Write a
generator function Generates () that displays the square roots of numbers from 100 to n where n is
passed as an argument.
Long Answer Type Questions
Q. 1. List a type of arguments and explain any 2 type of arguments.
Q. 2. Write a method in Python to find and display the prime number between 2 to N. Pass N as
argument to the method.
Q. 3. Write a program that uses a function which take two string arguments and returns the string
comparison result of the two passed strings.
Q. 4. Write definition of a function
1. OddSum(Numbers) to add Odd values in the list Numbers.
2. EvenSum(Numbers) to add Even values in the list Numbers.
Q.5. Define a function overlapping () that takes two lists and returns true if they have at least one
member in common, False otherwise.
Q.6. Write a program for nth multiple of Fibonacci Series. Also show proper
documentation. Q. 7. Write a Python program to reverse a string.
Q.8. A function checkMain() defined in module [Link] is being used in two different
programs In program 1 as
[Link](3,’A’)
and in program 2 as
checkMain(4,’Z’).
Why are the functions call statements different in each program?
Q. 9. Write a python program to find simple interest using a user defined function with parameters
and with return value.
Q. 10. Explain any three string functions with example?

EXCEPTION HANDLING IN PYTHON


Introduction: - Exception in python is nothing but a run time error due to which the program will
stop the execution. On the other hand, exceptions are raised when some internal events occur
which change the normal flow of the program.
Here are some of the most common types of exceptions in Python: -
 SyntaxError:- This exception is raised when the interpreter encounters a syntax error
in the code, such as a misspelled keyword, a missing colon, or an unbalanced
parenthesis.
 TypeError:- This exception is raised when an operation or function is applied to an
object of the wrong type, such as adding a string to an integer.
 NameError:- This exception is raised when a variable or function name is not found in
the current scope.
 IndexError:- This exception is raised when an index is out of range for a list, tuple, or
other sequence types.
 KeyError:- This exception is raised when a key is not found in a dictionary. 
ValueError:- This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when the string does
not represent a valid integer.
 AttributeError:- This exception is raised when an attribute or method is not found on
an object, such as trying to access a non-existent attribute of a class instance.
 IOError: - This exception is raised when an I/O operation, such as reading or writing a
file, fails due to an input/output error.

29 | P a g e
 ZeroDivisionError: - This exception is raised when an attempt is made to divide a
number by zero.
 ImportError: - This exception is raised when an import statement fails to find or load a
module.
Example: -
Here in this code a s we are dividing the ‘marks’ by zero so a error will occur known as
‘ZeroDivisionError’

marks = 10000
a = marks / 0
print(a)

Output: -

In the above example raised the ZeroDivisionError as we are trying to divide a number
by 0. Note: Exception is the base class for all the exceptions in Python.

Try and except Statement – Catching Exceptions


Try and except statements are used to catch and handle exceptions in Python. Statements
that can raise exceptions are kept inside the try clause and the statements that handle the
exception are written inside except clause.
Example: Here we are trying to access the array element whose index is out of bound and
handle the corresponding exception.

A = [1, 2, 3]
try:
print (“Second element = “, a[1])
print (“Fourth element = “(a[3]))
except:
print (“An error occurred”)

In the above example, the statements that can cause the error are placed inside the try
statement (second print statement in our case). The second print statement tries to access the
fourth element of the list which is not there and this throws an exception. This exception is then
caught by the except statement.
Finally Keyword in Python
Python provides a keyword finally, which is always executed after the try and except blocks.
The final block always executes after the normal termination of the try block or after the try
block terminates due to some exception.

30 | P a g e

Example:
The code attempts to perform integer division by zero, resulting in a ZeroDivisionError. It
catches the exception and prints “Can’t divide by zero.” Regardless of the exception, the
finally block is executed and prints “This is always executed.”
try:
k = 5//0
print(k)
except ZeroDivisionError:
print (“Can’t divide by zero”)
finally:
print (‘This is always executed’)
Output:
Can’t divide by zero
This is always executed
Questions (MCQ)
Q.1 What is the purpose of the try block in Python error handling?
a) To define the block of code where an exception may occur
b) To catch and handle exceptions that occur within the block
c) To ensure that the code executes without any errors
d) To terminate the program if an exception occurs
Q.2 Which keyword is used to catch exceptions in Python?
a) try
b) catch
c) except
d) handle
Q.3 What is raised when a Python program encounters an error during execution?
a) Error
b) Exception
c) Fault
d) Bug
Q.4 Which of the following is NOT a standard Python exception?
a) KeyError
b) ValueException
c) IndexError
d) TypeError

31 | P a g e
Q.5 What does the finally block in Python error handling ensure?
a) It ensures the code within it will always execute, regardless of whether an
exception occurs or not.
b) It ensures the program will terminate if an exception occurs.
c) It ensures that the program will skip executing the code if an exception occurs.
d) It ensures that only the code within the finally block will execute if an exception
occurs.
Q.6 What is the output of the following code?
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero")
finally:
print("Finally block")
a) Division by zero
Finally block
b) Finally block
c) Division by zero
d) ZeroDivisionError
Q.7 Which of the following keywords is used to handle the exception block in Python?
a) hand
b) rescue
c) except
d) catch
Q8. Which of the following is NOT a common built-in exception in Python?
a) KeyError
b) FileNotFoundError
c) IndexError
d) SyntaxError
Q9. Which statement is true about handling exceptions in Python?
a) An exception handler can catch exceptions raised by functions it calls.
b) An exception handler cannot catch exceptions raised by functions it
calls. c) An exception handler only catches exceptions raised in the
same block. d) An exception handler can only catch exceptions of the
same type.
Q10 What is the purpose of the finally block in Python error
. handling? a) To handle exceptions
b) To raise exceptions
c) To ensure that certain code will always be executed
d) To terminate the program

32 | P a g e
FILE HANDLING

• Till now we have run programs on console , which run for a short period of time and give some
output and after that their data is disappeared. And when we again run those programs then we have
to use new data.
•This is because the data is entered in primary memory which is temporary memory and its data is
volatile.
•If we want to save the output, so that it can be used later [Link] use the concept of File Handling.
•The meaning of File I/O (input-output) is to transfer the data from Primary memory to secondary
memory and vice-versa.

DATA FILE
A File is a collection of characters in which we can perform read and write functions. And also
we can save it in secondary storage. It contains data pertaining to a specific application, for
later use.
The data files can be stored in the following ways: -
1. Text file
2. Binary file
3. CSV(Comma-separated values) file

STEPS IN DATA FILE HANDLING

1. OPEN FILE : Open the file for reading or writing by specifying filename and file opening
mode.
2. READ/WRITE : Once the file is open process the file as required
3. CLOSE FILE : Close the file after processing

OPENING A FILE
A file can be opened for – read, write or append data
Syntax:
Fileobject = open(“filename” , opening_mode)
Note: Default opening mode is read
f = open("[Link]") # opening mode not specified default file opening mode is read
Here ‘f’ is the file object/file handle/file pointer which holds reference to the file.
The disk file [Link] is loaded into memory and its reference is linked to ‘f’ object. Now onwards
the python program will access the data file “[Link]” through ‘f’ object. Here “[Link]” is
stored in

33 | P a g e
the same folder where .py file is stored otherwise if the file stored in any other folder then filename
is specified with full path.
f=open("d:\\pyprograms\\[Link]" , “r”) # filename with full path
File opening modes
CLOSING A FILE
The close method of file object closes the file object i.e. releases the file. Python automatically closes
a file when the reference object of a file is reassigned to another file.
[Link]( )
TEXT FILES
 Text file stores information in ASCII or UNICODE character. Data is stored as a character for
example the word computer will take 8 bytes, 123.45 will take 6 bytes.
 In text file each line is terminated with an EOL(End of Line) character.
 Some translation takes place when this EOL character is read or written. This EOL character is ‘\n’
or ‘\r’ or combination of both.
Reading data from Text file
1. read( ): reads and returns the entire data stored in the file, starting from current cursor position
up to the end of the file. The returned data forms one string.
2. read( n ): reads and returns n number of characters from the file starting from current cursor
position. The returned data forms one string
3. readline( ): reads and returns only one line from file, starting from current cursor position up to end
of line character. The returned data forms one string. A line is considered as a sequence of character
up to new line character(EOL).
4. readlines( ): reads and returns all the lines from the file starting from current cursor position in
the form of list of strings. Where each lines forms one string.
 Every file maintains a file pointer which tells the current position in the file where read/write
operation will take place.
 Each time read/write operation is performed two things happen o read/write operation is
performed at the current cursor position in the file. o File pointer moves forward by the
specified number of bytes.
 While reading if no data is left in the file, then a blank string is returned.
# program 1: Read data from text file using read()
f=open("[Link]")
data=[Link]() # read entire data starting from 1st character
34 | P a g e
print("first read::",data)
data=[Link](3) # Will return a blank list as End Of File has reached because of first read
stmt print("second read::",data)
data=[Link](5) # Will return a blank list as End Of File has already reached
print("third read::", data)
[Link]()

# program 2: Read data from text file using readlines()


read all the lines from file in the form of list of lists where each list represents a line in the
file f=open("[Link]")
data=[Link]()
print(data)
[Link]()
# program 3: display data using file object
f=open("[Link]")
for i in f:
print(i)
[Link]()
PROGRAMS RELATED TEXT FILES
# Progarm 4: DISPLAY TOTAL NO OF CHARACTERS, WORDS
f=open("[Link]" , "r")
d=[Link]()
c=len(d)
str=[Link]() # to convert a string into list of strings
w=len(str)
print("No of characters= ",c)
print("No of words= ",w)
[Link]()

# Progarm 5: COUNT AND DISPLAY TOTAL NO OF OCCURENCE OF


WORD 'and' file=open("[Link]" , "r")
w=0
data=[Link]()
for d in data:
str=[Link]() # to convert a string into list of strings
for s in str:
if s=="and":
w=w+1
print("word 'and' found in the file: ", w," times")
[Link]()
# Progarm 6: TO COUNT TOTAL NUMBER OF WORDS STARTING WITH
'I' or 'i' file=open("[Link]" , "r")
d=[Link]()
str=[Link]()
w=0

35 | P a g e
for word in str:
if word[0]=='I' or word[0]=='i':
w=w+1
print("Total number of words starting with I or i : ",w)
[Link]()

# Progarm 7: DISPLAY LINES STARTING WITH 'I' OR 'H'


file=open("[Link]" , "r")
l=0
d=[Link]()
for data in d:
if data[0]=='I' or data[0]=='H':
print(data)
[Link]()

# Progarm 8: Define a function copytext() to copy all the lines from sample .txt that are ending
with ‘a or ‘A’ to a new file [Link]
def copytext():
f1=open("[Link]")
f2=open("[Link]", 'w')
list=[ ]
data=[Link]()

for line in data:


s=len(line)-2 # last character is at size -1 index and we have to check 2nd last
character
if line[s]=='a' or line[s]=='A':
[Link](line)

[Link](list)

[Link]()
[Link]()

f=open("[Link]" , "r")
print([Link]())
[Link]()

WRITING DATA INTO TEXT FILE


# Progarm 9: Using \n to separate data
f=open("[Link]" , "w")
[Link]("INDIA\n")
[Link]("NEW DELHI\n")
[Link]("end")
print("Data written to file")
[Link]()
36 | P a g e
# Progarm 10: Accepting data from user
f=open("[Link]" , "w")
text=input("Enter Subject name:")
[Link](text)
[Link]("\n")
mm=80
[Link](str(mm)) #numeric data is converted to string
[Link]()

# Progarm 11: Opening file in append mode and enter some data to
it. n=input("enter name of file") # Accept file name from the user
f=open(n , "a")
for i in range(3):
t=input("enter name:")
[Link](t)
[Link]("\n")
[Link]()

f=open("[Link]","r")
print([Link]())
[Link]()
>>>write() function cannot be used for writing sequence i.e. list, tuple
etc >>> writelines() is used to write sequence of strings to a file

# Program 12: Writing data using writelines ()


f=open("[Link]","w")
l=["neem " , "tulsi " , "mint "]
[Link](l)
[Link]()
f=open("[Link]","r")
print([Link]())
[Link]()

# Progarm 13: CREATE A FILE BY COPYING THE CONTENTS OF FILE


[Link] TO [Link]
f1=open("[Link]")
f2=open("[Link]", 'w')
d=[Link]()
[Link](d)
[Link]()
[Link]()

37 | P a g e
# Progarm 14: Delete all the lines from the file [Link] which are not starting with 'H' or
'I' import os
f1=open("[Link]")
f2=open("[Link]", 'w')
d=[Link]()
for l in d:
if l[0]=='H' or l[0]=='I':
[Link](l)
[Link]()
[Link]()
[Link]("[Link]") #remove file [Link]
[Link]("[Link]","[Link]") # rename [Link] to [Link]
f=open("[Link]","r")
print([Link]())
[Link]()
BINARY FILE
 It stores information in the same format as in the memory, thus no translation
occur.  There is no delimiter for a new line.
 Binary files are faster and easier for a program to read and write than text files.  Data in
binary files cannot be directly read it can be read only through python program for the same. 
These files can represent the actual content such as image, audio, video, compressed versions of other
files, executable files, etc.

The tell() Function


The tell() method of python tells us the current position of the cursor within the file.

The seek() Function


The seek(offset, from) method changes the current file position.
If from is 0, the beginning of the file to seek. If it is set to 1, the current position is used. If it is set
to 2 then the end of the file would be taken as seek position.
The offset argument indicates the number of bytes to be moved.

Example Code :
f = open("[Link]", 'wb')
line = ‘G20 Presidency\nOne Earth, One Family, One Future'
[Link](line)
[Link]()
f = open("[Link]", 'rb+') print([Link]())
print([Link](7)) # read seven characters print([Link]())
print([Link]())
print([Link]())
[Link](9,0) # moves to 9 position from beginning
print([Link](5))
[Link](4, 1) # moves to 4 position from current location
print ([Link](5))
[Link](-5, 2) # Go to the 5th byte before the end
print([Link](5))
[Link]()
38 | P a g e
The Pickle Module :
We know that Python considers everything as an object. So, all data types including list, tuple,
dictionary, etc. are also considered as objects. During execution of a program, we may require
to store current state of variables so that we can retrieve them later to its present state. To
save any object structure along with data, Python provides a module called Pickle. The module
Pickle is used for serializing and de-serializing any Python object structure.

Pickling is a method of preserving food items by placing them in some solution, which
increases the shelf life. In other words, it is a method to store food items for later consumption.

Serialization is the process of transforming data or an object in memory (RAM) to a stream of


bytes called byte streams. These byte streams in a binary file can then be stored in a disk or in
a database or sent through a network. Serialization process is also called pickling.

De-serialization or unpickling is the inverse of pickling process where a byte stream is


converted back to Python object.

The pickle module deals with binary files. Here, data are not written but dumped and similarly,
data are not read but loaded. The Pickle Module must be imported to load and dump data. The
pickle module provides two methods - dump() and load() to work with binary files for pickling
and unpickling, respectively.

The dump() method:


This method is used to convert (pickling) Python objects for writing data in a binary file. The file
in which data are to be dumped, needs to be opened in binary write mode (wb).

Syntax of dump() is as follows:


dump(data_object, file_object)
where data_object is the object that has to be dumped to the file with the file handle named
file_object. For example, following Program writes the record of a student (roll_no, name,
gender and marks) in the binary file named [Link] using the dump(). We need to close
the file after pickling.

#Pickling data in Python


import pickle listvalues=[1,"Geetika",'F', 26]
fileobject=open("[Link]", "wb")
[Link](listvalues,fileobject)
[Link]()
The load() method
This method is used to load (unpickling) data from a binary file. The file to be loaded is
opened in binary read (rb) mode. Syntax of load() is as follows:
Store_object = load(file_object)
Here, the pickled Python object is loaded from the file having a file handle named file_object and is
stored in a new file handle called store_object. The following program demonstrates how to read
data from the file [Link] using the load().
#Unpickling data in Python
import pickle
39 | P a g e
print("The data that were stored in file are: ")
fileobject=open("[Link]","rb")
objectvar=[Link](fileobject)
[Link]()
print(objectvar)
Output of Program:
The data that were stored in fi le are:
[1, 'Geetika', 'F', 26]

#Program 1: Writing data into a binary file


import pickle
emp=[ ] # create an empty list
f=open("[Link]" , "wb") #open file for writing in binary mode
# to append data(i.e. to add more records, instead of 'w' write 'a'
ans='y'
while ans=='y': # loop will run till value of ans is 'y'
eno=int(input("Enter employee number:"))
name=input("Enter employee name:")
sal=int(input("Enter salary:"))
[Link]([eno,name,sal]) #emp is created as list of lists by appending list to it
ans=input("Want to enter more records-press 'y':")
[Link](emp, f) #write list emp to file using file object f
[Link]()
>>>>>the list will be created and stored in file in the following
form >>>>>[ [1, 'gopi', 100786], [5, 'hina', 90675], [7, 'tia',
90876] ]

# Program 2: Reading data from file


import pickle
emp=[ ]
f=open("[Link]","rb")
emp=[Link](f) #returns data as list of lists each list represent one record
print(emp)[Link]()

# Program 3: searching a record from file


import pickle
emp=[ ]
f=open("[Link]" , "rb")
e=int(input("enter employee no you want to search:"))
emp=[Link](f)
found=0
for d in emp:
if d[0]==e:
print(d)
found=1
break
if found==0:
print("record not found")
[Link]()

40 | P a g e
Program 4: Record modification in binary file
import pickle
emp=[ ]
f=open("[Link]" , "rb")
emp=[Link](f)
print("Contents before modification\n",emp)
e=int(input("\nenter employee no you want to modify:"))
found=0
for d in emp:
if d[0]==e:
d[2]=d[2]+1000
found=1
break
if found==0:
print("record not found")
[Link]()
f=open("[Link]","wb")
[Link](emp,f)
[Link]()
e=[ ]
f=open("[Link]","rb")
e=[Link](f) #returns data as list of lists each list represent one record
[Link]()
if found==1:
print("Contents after modification\n",e)

# Program 5: Deleting record in binary file


import pickle
f=open("[Link]","rb")
emp=[ ]
emp=[Link](f)
[Link]()
print("Contents before deletion",emp)
f=open("[Link]","wb")
e=int(input("enter employee no you want to delete:"))
l=[ ]
found=0
for d in emp:
if d[0]!=e:
[Link](d)
else:
found=1
if found==0:
print("record not found")
41 | P a g e
[Link](l,f)
[Link]()
e=[ ]
f=open("[Link]","rb")
e=[Link](f) #returns data as list of lists each list represent one record
[Link]()
if found==1:
print("Contents after deletion",e)

Absolute and Relative path


The absolute path is the full path to some place on your computer.
For example:
C:/users/admin/docs/[Link]
The relative path is the path to some file/folder with respect to the current working directory

Display name of current `working directory:


import os
D=[Link]()
print(D)
It will display a string containing the path of the current working directory
OUTPUT:
'C:\\Users\\TNINE\\AppData\\Local\\Programs\\Python\\Python36-32'

CSV File:
CSV (Comma Separated Values) format is one of the most simple and common ways to store
data in tabular form. Each record consists of one or more fields separated by commas. To
represent a CSV file, it must be saved with the .csv file extension. It is a file format for data
storage which looks like a text file. The information is organized with one record in each line
and each field is separated by comma.
● It is a plain text file that contains the comma-separated data.
● These files are often used for exchanging data between different applications. ● CSV
files are usually created by programs that handle huge amounts of data. They are used to
export data from spreadsheets (ex:- excel file) and databases (Ex:- Oracle, MySQL). It
can be used to import data into a spreadsheet or a database.

CSV File Characteristics:


• One line for each record
• Comma separated fields
• Space-characters adjacent to commas are ignored
• Fields with in-built commas are separated by double quote characters.
When Use CSV:
• When data has a strict tabular structure
• To transfer large database between programs
• To import and export data to office applications.
• To store, manage and modify shopping cart catalogue
42 | P a g e
Why Use CSV Files? / Advantages of CSV Files:
• CSV is faster to handle.
• CSV is easy to generate.
• CSV is human readable and easy to edit manually.
• CSV is simple to implement and parse.
• CSV is processed by almost all existing applications.
CSV Files Disadvantages:
• No standard way to represent binary data.
• There is no distinction between text and numeric values.
• Poor support of special characters and control characters.
• CSV allows to move most basic data only. Complex configurations cannot
be imported and exported this way.
• Problems with importing CSV into SQL (no distinction between NULL and quotes)

Python CSV Module:


● CSV Module is available in Python Standard Library.
● The CSV module contains classes that are used to read and write tabular
form of data into CSV format.
● To work with CSV Files, programmer have to import CSV Module.

Working with csv file: csv files are used to store a large number of variables or data. They
are incredibly simplified spreadsheets. Each line in a csv file is a data record.

(i) Read from CSV File:


Using [Link](): To read data from csv files, you must use the reader()
function to generate a reader object. This function returns a reader object
which is an iterator of lines in the csv file.
Syntax: [Link]()
(ii) [Link] (): The [Link](file object) function returns a writer object that
converts the user’s data into delimiter string.

(iii) Write into a CSV File using [Link](): To write an existing file, you must
first open the file in one of writing modes (w, a or r+) first. then writerow()
function is used to write items in a sequence (list, tuple or string) separating
them by comma.

(iv) Writerows():If we need to write the content of 2-Dimensional list into csv file , instead
of using writerow() function many times, we can write use [Link]()method. Example:-

# writerow()
import csv
row=['Nikhil', 'CEO', '2', '9.0']
f=open("[Link]", 'w')
w_obj = [Link](f)
w_obj.writerow(row)
[Link]()

43 | P a g e
# writerows()
import csv
rows = ['Nikhil','CEO','2','9.0'],
['Sanchit','CEO','2','9.1']]
f=open("[Link]",'w')
w_obj = [Link](f)
w_obj.writerows(rows)
[Link]()
# reader()
import csv
f=open("[Link]",'r')
r_obj = [Link](f)
for data in r_obj:
print(data))
[Link]()

If we consider the [Link] file given below in the CSV file structure the output of the above
code will be:

Name, DOB, City


Ram, 12-Jul-2001, Delhi
Mohan, 23-Jan-2005, Delhi
Suraj, 17-Dec-2002, Kolkata

## OUTPUT:
['Name', 'DOB', 'City']
['Ram', '12-Jul-2001', 'Delhi']
['Mohan', '23-Jan-2005', 'Delhi']
['Suraj', '17-Dec-2002', 'Kolkata']

EXERCISE

MCQ:
1. ____ file format are faster and easier for a program to read and write than other file
format. a. Text file b. Binary file c. Doc file d. None of the above
Answer b. Binary file
2. The command for opening a file in Python file handling is .
a. open() b. update() c. both a) and b) d. None of the above
Answer a. open()
3. The command for closing a file in Python file handling is .
a. close() b. closing() c. object() d. None of the above
Answer ⟵ a. close()
4. text file mode is used to read data from file.
a. ‘r’ b. ‘rb’ c. ‘r+’ d. None of the above
Answer a. ‘r’
5. text file mode is used to append data in the file using file handling. a. ‘w’
b. ‘ab’ c. ‘a’ d. None of the above
Answer c. ‘a’
6. Out of the followings which mode is used for both reading and writing in binary format in file?
44 | P a g e
a) wb b) wb+ c) w d) w+
Ans: b) wb+
7. Which of the following is not true about binary files?
a) Binary files are store in terms of bytes
b) When you open binary file in text editor will show garbage values
c) Binary files represent ASCII value of characters
d) All of the above
Ans: c) Binary files represent ASCII value of characters

8. What is the difference between wb and wb+ mode?


a) wb mode is used to open binary file in write mode and wb+ mode open binary file both for
read and write operation.
b)In wb mode file open in write mode and wb+ in read mode
c) File pointer is at beginning of file in wb mode and in wb+ at the end of
file d)No difference
Ans: a) wb mode is used to open binary file in write mode and wb+ mode open binary file both for
read and write operation.

9. The pickle module in Python is used for:


a) Serializing any Python object structure b) De-serializing Python object structure c)
Both a and b d) None of these
Ans: c) Both a and b
10. Which method is used to convert Python objects for writing data in binary
file? a) write() b) load() c) store() d) dump()
Ans: d) dump()
11. seek() function is used for .

a) positions the file object at the specified location.


b) It returns the current position of the file object
c) It writes the data in binary file
d) None of these
Ans: a) positions the file object at the specified location.

12. Which is not the valid mode for binary files?


a) r b) rb c) wb d) wb+
Ans: a) r

(ASSERTION AND REASONING based questions) Mark the correct choice as:
i. Both A and R are true and R is the correct explanation for A
ii. Both A and R are true but R is not the correct explanation for A
iii. A is True but R is False
iv. A is false but R is True
1. Assertion (A): A binary file stores the data in the same way as stored in the
memory. Reason (R): Binary file in python does not have line delimiter
Ans: ii. Both A and R are true but R is not the correct explanation for A

2. Assertion(A): an open file can be close using close() function.


Reason(R): sometimes the data written onto files is held in memory until the file is
closed. Ans: i. Both A and R are true and R is the correct explanation for A

3. Assertion(A): [Link]() function is used to store the object data to the file.
45 | P a g e
Reason(R): [Link]() function is used to retrieve pickled data.
Ans: ii. Both A and R are true but R is not the correct explanation for A

4. Assertion(A): The seek(offset,from) method changes the current file position. Reason(R): If
from is 0, the beginning of the file to seek. If it is set to 1, the current position is used. If it is set to
2 then the end of the file would be taken as seek position. The offset argument indicates the
number of bytes to be moved.
Ans: i. Both A and R are true and R is the correct explanation for A

5. Assertion(A): ab+ mode is used for both appending and reading binary files and move
file pointer at end.
Reason(R): ab+ mode, if the file does not exist, it does not create a new file for reading and
writing. Ans: iii. A is True but R is False

Short Answer Type Questions ( 2-Marks Questions )


1. Identify the error in the following code:
import pickle
data=[‘one’, 2, [3, 4, 5]]
with open(‘[Link]’, ‘rb’) as f:
[Link](data, f)
Ans: The file is opened in read mode and dump() function tries to write onto file, hence there is
error line 3.
Correct code : with open(‘[Link]’, ‘wb’) as f:
2. Any recipe uses some ingredients. Write a program to store the list of ingredients in a binary
file [Link] .
Ans: import pickle
ingredients= [‘cucumber’, ‘pumpkin’, ‘carrot’, ‘peas’]
with open(‘[Link]’, ‘wb’) as fout:
[Link](ingredient, fout)

3. A binary file “[Link]” has structure [rollno, name, marks]. Write a user defined
function insertRec() to input data for a student and add to [Link].
Ans:
import pickle def insertRec():
f=open(‘[Link]’,’ab’)
rollno = int (input(‘Enter Roll Number :’))
name=input("Enter Name :")
marks = int(input(‘Enter Marks :’))
rec = [rollno, name, marks ]
[Link]( rec, f )
[Link]()

4. Considering the following definition of dictionary MULTIPLEX, write a method in python


to search and display all the content in a pickled file [Link], where MTYPE key of
the dictionary is matching with the value ‘Comedy’.
MULTIPLEX = {‘MNO’ : , ‘MNAME’: , ‘MTYPE’: }
Ans:
import pickle def search():
file=open('[Link]', 'rb') try:
while True:
46 | P a g e
MULTIPLEX=[Link](file)
if(MULTIPLEX['MTYPE']=='Comedy'):
print(MULTIPLEX)
except EOFError:
[Link]()
5 What will be the output of following code:
import pickle
names=['First', 'Second', 'Third', 'Fourth', 'Fifth']
lst=[ ]
for i in range(-1, -5, -1):
[Link](names[i])
fout= open('[Link]', 'wb')
[Link](lst, fout)
[Link]()
fin= open('[Link]', 'rb')
nlist=[Link](fin)
[Link]()
print(nlist)
Ans: ['Fifth', 'Fourth', 'Third', 'Second']
SA-2(3-Marks Questions)
1. A binary file “[Link]” has structure [rollno, name, marks]. Write a function
searchRollNo( r ) in python which accepts the student’s rollno as parameter and searches the
record in the file “[Link]” and shows the details of student i.e. rollno, name and marks (if
found) otherwise shows the message as ‘No record found’.
Ans:
def searchRollNo( r ):
f=open("[Link]","rb")
flag = False
while True:
try:
rec=[Link](f)
if rec[0] == r :
print(rec[‘Rollno’])
print(rec[‘Name’])
print(rec[‘Marks])
flag == True
except EOFError:
break
if flag == False:
print(“No record Found”)
[Link]()

2. A binary file “[Link]” has structure (admission_number, Name, Percentage). Write


a function countrec() in Python that would read contents of the file “[Link]” and
display the details and total number of those students whose percentage is above 75.
Ans:
import pickle
def CountRec():
f=open("[Link]","rb")
num = 0 try:
while True:
rec=[Link](f) if rec[2] > 75:
47 | P a g e
print(rec[0], rec[1], rec[2])
num = num + 1
except:
[Link]()
return num
A binary file named “[Link]” has some records of the structure [EmpNo, EName, Post, Salary].
Create a binary file “[Link]” that stores the records of employees and display them one by one.
Also display the records of all those employees who are getting salaries between 25000 to
30000. Ans:
import pickle
f1 = open('[Link]','rb')
try:
while True:
e = [Link](f1)
print(e)
except:
[Link]()
f1 = open('[Link]','rb')
try:
while True:
e = [Link](f1)
if(e[3]>=25000 and e[3]<=30000):
print(e)
except:
[Link]()
3. A binary file “[Link]” has structure [BookNo, Book_Name, Author, Price]. Write a function
CountRec(Author) in Python which accepts the Author name as parameter and count and
return number of books by the given Author are stored in the binary file “[Link]”. Ans:
import pickle
def CountRec(Author):
f=open("[Link]","rb") num = 0
try:
while True:
rec=[Link](f)
if Author==rec[2]:
num = num + 1
except:
[Link]()
return num

4. Consider a binary file [Link] having records in the form of dictionary. E.g {eno:1,
name:”Rahul”, sal: 5000} write a python function to display the records of above file for those
employees who get salary between 25000 and 30000.
Ans:
import pickle
def search():
f=open(“[Link]”,”rb”)
while True:
try:
d=[Link](f)
if(d[‘sal’]>=25000 and d[‘sal’]<=30000):
print(d)
48 | P a g e
except EOFError:
break
[Link]()

Case Study Based Question-1


Ramesh loves programming. He joined an institute for learning. He is learning python. He
learned all the python concepts like strings, lists, tuple, dictionaries etc. but he wants to learn file
handling in python. He is trying to learn binary file handling. His teacher gave him partial code to
write and read data from [Link] having structure empno, name, salary. Help Ramesh to
complete the code:

# statement 1
def addrecords():
fw= #statement 2
dict={}
ch=’y’
while ch==’y’:
eno=int(input(“enter employee number”))
nm= input(“enter employee name”)
sal=int(input(“enter employee salary”))
dict={‘empno’:eno,’name’:nm,’salary’:sal}
# statement 3
ch=input(“add more record”)
[Link]()
# function to display records
def display():
dict={}
fr= # statement 4
dict= # statement 5
[Link]()
print(“data :”,dict)
Answer questions (i)-(v) based on above case study
(i). Help Ramesh to import the module to perform binary file operation in statement
1. a) csv b) random c) pickle d) file
Ans: c) pickle

(ii). Which statement is used from the following for statement 2 to open the binary file in
write mode?
a) open(“[Link]”,’w’) b) open(“[Link]”,’wb’)
c) open(“[Link]”,’w+’) d) open(“[Link]”,’r’)
Ans: b) open(“[Link]”,’wb’)

(iii). Which statement is used from the following for statement 3 to write dictionary data
created in above code, namely dict, is written in binary file [Link] file?
a) [Link](dict,fw) b) [Link](dict,fw)
c) [Link](dict,fw) d) [Link](dict)
Ans: a) [Link](dict,fw)

(iv). Which statement is used from the following for statement 4 to open the binary file in
read mode?
a) open(“[Link]”,’r’) b) open(“[Link]”,’r+’)
c) open(“[Link]”,’a’) d) open(“[Link]”,’rb’)
49 | P a g e
Ans: d) open(“[Link]”,’rb’)

(v). Complete statement 5 to read data in dictionary namely dict from the opened binary
file? a) dict=[Link](fr) b) dict=[Link](fr)
c) [Link](dict,fr) d) none of these
Ans: b) dict=[Link](fr)

Case Study Based Question-2


Mohit, a student of Class 12th, is learning CSV File Module in Python. During examination, he has
been assigned an incomplete Python code (shown below) to create a CSV File ‘[Link]’
(content shown below). Help him in completing the code which creates the desired CSV File.
CSV File
1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4,RAVI,XII,A
5,ASHISH,XII,A

Incomplete Code
import _______________________________________________________ #Statement 1
fh = open( , , newline=‘ ’) #Statement 2
data = [ ]
stuwriter = csv. #Statement 3
header = [‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’]
[Link](header)
for i in range(5):
roll_no = int(input(“Enter Roll Number : ”))
name = input(“Enter Name : ”)
class = input(“Class : ”)
section = input(“Enter Section : ”)
rec = [ ] #Statement 4
[Link](rec)
stuwriter. (data) #Statement 5
[Link]()

Answer the questions from the above mentioned program:


(i) Identify the suitable code for blank space in line marked as Statement
1. (a) csv file (b) CSV (c) csv (d) Csv
Ans: (c) csv
(ii) Identify the missing code for blank space in line marked as Statement 2. (a)
“[Link]”,“w” (b) “[Link]”,“w” (c) “[Link]”,“r” (d) “[Link]”,“r” Ans: (b)
“[Link]”,“w”
# It opens a file [Link] in write mode because append( ) method is using. (iii) Choose the
function name (with argument) that should be used in the blank space of line marked as
Statement 3.
(a) reader(fh) (b) reader(MyFile) (c) writer(fh) (d) writer(MyFile) Ans: (c) writer(fh)
#csv. writer is used to insert data to the CSV file.
(iv) Identify the suitable code for blank space in line marked as Statement 4.
(a)‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’ (b) ROLL_NO, NAME, CLASS,
SECTION (a)‘roll_no’,‘name’,‘class’,‘section’ (d) roll_no,name,class,section (b)Ans:
(d) roll_no,name,class,section
50 | P a g e
(v)Choose the function name that should be used in the blank space of line marked as
Statement 5 to create the desired CSV file?
(a) dump( ) (b) load( ) (c) writerows( ) (d) writerow( ) Ans: (c) writerows( )
#writerows() writes each sequence in a list as a comma separated line of items in file.

DATA STRUCTURE ( STACK)


Stack: A stack is a data structure whose elements are accessed according to the Last-In First-
Out (LIFO) principle. This is because in a stack, insertion and deletion of elements can only take
place at one end, called top of the stack. Consider the following examples of stacks:
1. Ten glass plates placed one above another. (The plate that is kept last must be taken
out first). 2. The tennis balls in a container. (You cannot remove more than one ball at a
time) 3. A pile of books.
4. Stack of coins
The Significance of Stack Top : If we want to remove any coin from the stack, the coin on the top of
the stack has to be removed first. That means, the coin that In the above picture coins are kept one
above the other and if any additional coin is to be added, it can be added only on was kept last in
the stack has to be taken out first.
Note: Stack Work on LIFO (Last In First Out) principle.
Operations on Stack :
We can perform two operations on stack are: Push and Pop

Push (Add/Insert): Adding an element in stack is called Push operation.


When the stack is empty, the value of top is Basically, an empty stack is initialized with an invalid
subscript. Whenever a Push operation is performed, the top is incremented by one and then the
new value is inserted on the top of the list till the time the value of top is less than or equal to the
size of the stack.
The algorithm for Push operation on a stack:
1. Start 2. Initialize top with -1 3. Input the new element
4. Increment top by one. 5. Stack[top]=new element. 6. Print “Item inserted” 7. Stop

Pop (Removing (deleting) an element from the stack.


Removing existing elements from the stack list is called pop operation. Here we must check if the
stack is empty by checking the value of top. If the value of top is -1, then the stack is empty and
such a situation is called Underflow. Otherwise, Pop operation can be performed in the stack. The
top is decremented by one if an element is deleted from the list.
The algorithm for pop operation is as follows:
1. Start.
2. If the value of top is -1 go to step 3 else go to step 4
[Link] “Stack Empty” and go to step 7
4. Deleted item =Stack[top]
5. Decrement top by 1
6. Print “Item Deleted”.
7. Stop
Traversal in a stack: Traversal is moving through the elements of the stack. If you want to
display all the elements of the stack, the algorithm will be as follows:
1. Start
2. Check the value of top. If top=-1 go to step 3 else go to step 4
[Link] “Stack is Empty” and go to step7
4. Print the top element of the stack
5. Decrement top by 1
51 | P a g e
6. If top=-1 go to step 7 else go to step 4
7. Stop

Stack implementation using list with function definition


import sys
def Push(stack):
N=int(input("enter no of record you want to ADD"))
for i in range(N):
data=input("enter name") [Link](data)
def Pop(stack
if(stack==[]):
print("stack is empty")
else:
N=int(input("enter no of record you want to DELETE"))
for i in range(N):
print("elements to be deleted",[Link]())
def display(stack):
if(stack==[]):
print("no element for deletion")
else:
top=len(stack)-1
for i in range(top,-1,-1):
print(stack[i])
s=[]
while(True):
print("MENU \n 1-PUSH in STACK \n 2-POP \n 3-DISPLAY \n [Link] \
n") ch=int(input("enter your choice 1-4"))
if(ch==1):
Push(s)
print("elemnets in stack after push operation",s)
if(ch==2):
Pop(s)
print("element in stack after pop",s)
if(ch==3):
display(s)
if(ch==4):
print("Thank You")
exit()

Check Your Progress :


MCQ:-
[Link] end we use in stack to perform Push and Pop
operation? A. Front B. Rear C. Top D. Sop
2. Which principle followed by Stack?
A. FIFO B. LIFO C. FIOF D. TIPO
3. Which operation take place by stack?
A. Push B. Pop C. Traversal D. All of these
4. Which method we use to add an element in stack using list?
A. insert B. append C. add D. None of these 5. When we
delete an element, the value of top will be
A. increment B. decrement C Both A&B D. None of these
ANSWERS: 1. C 2. A 3. D 4.B 5. B 52 | P a g e
TRUE/FALSE:
[Link] stands for Last in First Out.
2. We can perform Pop operation if stack is empty.
3. if size of stack is 5 we can Push 6 element in stack.
4. len() method used to find the size of stack.
5. Stack is a linear data structure.
ANSWERS: 1. T 2. F 3. F 4.T 5. T
Q1. Julie has created a dictionary containing names and marks as key value pairs of 6 students.
Write a program, with separate user defined functions to perform the following operations: - 
Push the keys (name of the student) of the dictionary into a stack, where the corresponding
value (marks) is greater than 75.
 Pop and display the content of the stack.
For example: If the sample content of the dictionary is as follows:
R={“OM”:76, “JAI”:45, “BOB”:89, “ALI”:65, “ANU”:90, “TOM”:82}
The output from the program should be: TOM ANU BOB OM

ANSWER:
R={'OM':76, 'JAI':45, 'BOB':89, 'ALI':65, 'ANU':90, 'TOM':82}
def PUSH(S,N):
[Link](N)
def POP(S):
if S!=[ ]:
return [Link]( )
else:
print('Underflow')
ST=[ ]
for k in R:
if R[k]>=75:
PUSH(ST,k)
while True:
if ST!=[ ]:
print (POP(ST), end=' ')
else:
break
Q2. Alarm has a list containing 10 integers. You need to help him create a program with separate
user defined functions to perform the following operations based on this list.
 Traverse the content of the list and push the even numbers into a stack.
 Pop and display the content of the stack.
For Example: If the sample content of the list is as follows:
N=[12,13,34,56,21,79,98,22,35,38]
Sample output of the code should be: 38 22 98 56 34 12 ANSWER:
N=[12,13,34,56,21,79,98,22,35,38]
def PUSH(S,N):
[Link](N)
def POP(S):
if S!=[ ]:
return [Link]( )
else:
print('Underflow')
ST=[ ]
for k in N:
53 | P a g e
if k%2==0:
PUSH(ST,k)
while True:
if ST!=[ ]:
print(POP(ST), end=" ")
else:
break
Q3. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list push all
numbers divisible by 5 into a stack implemented by using a list. Display the stack if it has at
least one element, otherwise display appropriate error message.
ANSWER:
s=[25,40,27,34 ]
def PUSH( Arr, value):
for x in range(0, len(Arr)):
if(Arr[x]%5--0):
[Link](Arr[x])
if(len(s)==0):
print("Empty stack")
else:
print(s)
Q4 . Write functions in python for Push(List) and for PopS(List) for performing Push and Pop
operations with a stack of list containing integers.
ANSWER:
List=[1,2,3]
def PushS(List):
N=int(input('Enter Integer'))
[Link](N)
def PopS(List):
if (List==[]):
print('UnderFlow!!')
else:
print('Deleted Value: ',[Link]())
PushS(List)
print(List)
PopS(List)

Q5 . A list, NList contains following record as list elements: [City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the following user defined
functions in Python to perform the specified operations on the stack named travel. 
Push_element(NList): It takes the nested list as an argument and pushes a list object containing
name of the city and country, which are not in India and distance is less than 3500 km from Delhi.
 Pop_element(): It pops the objects from the stack and displays them. Also, the function should
display “Stack Empty” when there are no elements in the stack.
ANSWER:
travel=[]
def Push_element(NList):
for L in NList:
if(L[1] != 'India' and L[2]<3500):
[Link]([L[0],L[1]])
def Pop_element():
if travel !=[]:
print(POP(ST),end=" ")
else:
print(“stack empty”)
break 54 | P a g e
DATABASE CONCEPTS
1. DATABASE: A Database is defined as an organized collection of interrelated data that
serves many applications.
2. DATABASE MANAGEMENT SYSTEM: A Database Management System (DBMS) is a
general purpose software system that facilitates the process of defining, constructing and
manipulating databases for various applications.
3. NEED FOR DBMS
1) Helps store data in a structured manner.
2) Query the Database(i.e. ask questions about the data)
3) Sort and Manipulate the Data in the Database
4) Validate the Data Entered and check for inconsistencies
5) Produce Flexible Reports
4. ADVANTAGES OF DBMS
1) Elimination of Data Redundancy/Duplication
2) Data Consistency
3) Sharing of Data
4) Reduced Programming Effort
5) Improved Data Integrity
6) Privacy and Security
7) Improved backup and recovery system
8) Economical
5. TYPES OF DBMS
1) Hierarchical DBMS
2) Network Based DBMS
3) Object Based DBMS
4) Relational DBMS
DIFFERENT DATA MODELS
A data model refers to a set of concepts to describe the structure of a database, and certain
constraints (restrictions) that the database should obey. The four data model that are used for
database management are:
[Link] data model
2. Hierarchical data model
3. Network data model
4. Object Oriented data model
In Relational data model, the data is organized into tables (i.e. rows and columns). These
tables are called relations.
RELATIONAL MODEL TERMINOLOGY
1. Relation : A table storing logically related data is called a Relation.
2. Tuple : A row of a relation is generally referred to as a tuple.
3. Attribute : A column of a relation is generally referred to as an
attribute. 4. Degree : This refers to the number of attributes in a relation.
5. Cardinality : This refers to the number of tuples in a relation.
55 | P a g e
KEYS IN A DATABASE
1. PRIMARY KEY – An Attribute or a set of Attributes, which uniquely identifies each tuple in the
Relation is known as Primary Key.
2. CANDIDATE KEY – An Attribute or a set of Attributes that has the ability to uniquely identify
each tuple in the Relation is known as a Candidate Key.
3. ALTERNATE KEY – All the Candidate Keys which were not chosen to be Primary Key are also
known as Alternate Keys.
4. FOREIGN KEY - An Attribute or a Set of Attributes in one relation which refer to the Primary
Key of any other Relation is known as the Foreign Key of the Relation. They are used to
establish relationships between Tables.
REFERENTIAL INTEGRITY: A referential integrity is a system of rules that a DBMS uses to
ensure that relationships between records in related tables are valid, and that users don’t
accidentally delete or change related data. This integrity is ensured by foreign key.
Tips to Remember regarding Keys in a Database
One can always relate the Keys in a Relation to be like the Representatives of Each Political
Party during an Election.
 All representatives are those who promise to uniquely identify the problems of each
voter in the country. They are the Candidates for the Election. In a similar way,
Candidate Keys can uniquely identify each tuple.
 After the Elections One Candidate among all the Candidates are elected as the Prime
Minister of the Country. Similarly, any one of the Candidate Keys which has been
chosen by the Database Developer to uniquely identify each tuple is the Primary Key
of the Relation.
 All those Candidates who could not become the Prime Minister, become the member of
the Opposition. Similarly, all the Candidate Keys which were not chosen to be Primary
Key are also known as Alternate Keys of the Relation.
 The Prime Minister of the Country often sends Foreign Ministers to represent the Prime
Minster in other countries. Similarly, a Foreign Key are attributes in a relation which
refers to the Primary Key of some other Relation.

MIND MAP
56 | P a g e

Check Your Progress:

MULTIPLE CHOICE QUESTIONS


Question 1: What is a database?
(A) A collection of organized data (B) A software program used to manage data (C)
A hardware device used to store data (D) All of the above
Answer: (A)
Question 2: What are the benefits of using a database?
(A) Improved data organization and efficiency (B) Reduced data redundancy
(C) Improved data integrity (D) Improved data security (E) All of the above
Answer: (E)
Question 3: What is the relational data model?
(A) A type of database model that stores data in tables
(B) A type of database model that stores data in hierarchies
(C) A type of database model that stores data in networks
(D) All of the above
Answer: (A)
Question 4: What is a relation in the relational data model?
(A) A table (B) A row in a table (C) A column in a table (D) None of the above
Answer: (A)
Question 5: What is an attribute in the relational data model?
(A) A column in a table (B) A row in a table (C) A table (D) None of the above
Answer: (A)
Question 6: What is the domain of an attribute?
(A) The set of possible values that the attribute can take
(B) The name of the attribute
(C) The data type of the attribute (D) None of the above
Answer: (A)
Question 7: What is the degree of a relation?
(A) The number of attributes in the relation (B) The number of rows in the relation
(C) The number of tables in the relation (D) None of the above Answer:(A)
Question 8: What is the cardinality of a relation?
(A) The number of attributes in the relation (B) The number of rows in the relation
(C) The number of tables in the relation (D) None of the above Answer: (B)
Question 9: What is a key in the relational data model?
(A) A set of attributes that uniquely identifies a tuple in a relation
(B) A set of attributes that is used to sort the tuples in a relation
(C) A set of attributes that is used to filter the tuples in a relation
(D) None of the above
Answer: (A)

57 | P a g e
Question 10: What is a foreign key in the relational data model?
(A) A set of attributes in one relation that references the primary key of another
relation (B) A set of attributes in one relation that references the candidate key of
another relation (C) A set of attributes in one relation that references the foreign key
of another relation (D) None of the above
Answer: (A)

ASSERTION REASONING QUESTIONS

Question 1:
Assertion (A): A database is a collection of organized data.
Reason (R): A database can be used to store a wide variety of data types, including text,
numbers, images, and videos.
Answer: Both (A) and (R) are correct and (R) is the correct explanation of
(A). Question 2:
Assertion (A): The relational data model is a type of database model that stores data in
tables.
Reason (R): The relational data model is the most popular type of database model used
today.
Answer: Both (A) and (R) are correct and (R) is not the correct explanation of
(A). Question 3:
Assertion (A): A relation in the relational data model is a set of tuples.
Reason (R): A tuple is a column in a table.
Answer: Assertion (A) is True and Reason (R) is False.
Question 4:
Assertion (A): A foreign key in the relational data model is a set of attributes in one relation
that references the primary key of another relation.
Reason (R): Foreign keys are used to establish relationships between tables.
Answer: Both (A) and (R) are correct and (R) is the correct explanation of (A).
Question 5:
Assertion (A): A candidate key in the relational data model is a set of attributes that
uniquely identifies a tuple in a relation.
Reason (R): A primary key is a candidate key that is chosen to be the unique identifier for
tuples in a relation.
Answer: Both (A) and (R) are correct and (R) is the correct explanation of (A).

TRUE FALSE QUESTIONS


1: A database is a collection of organized data. (True)
2: The relational data model is a type of database model that stores data in hierarchies.
(False) 3: A relation in the relational data model is a row in a table. (False)
4: A foreign key in the relational data model is a set of attributes in one relation that references
the primary key of another relation. (True)
5: A candidate key in the relational data model is a set of attributes that can uniquely identifies a
row in a table. (True)
58 | P a g e
SHORT ANSWER QUESTIONS (2 MARKS)
Q1 Mention the various advantages of DBMS.
Ans. The following are some of the advantages of DBMS:-
1. Elimination of Data Redundancy/Duplication
2. Data Consistency
3. Sharing of Data
4. Reduced Programming Effort etc.
Q2. What is the difference between an attribute and tuple?
Ans. The columns of the table are known as Attributes and the rows in the table which store the
record is known as tuples.
Q3. Define Degree and Cardinality.
Ans. DEGREE OF A RELATION – The total number of Attributes in a relation is known as the
Degree of the Relation.
CARDINALITY OF A RELATION – The total number of Tuples / Records in a relation (excluding
the Top Row, which contains the Attribute Headers) is known as the Cardinality of the Relation.
Q4. Given a Table Employee (EID, EName, Department, Salary). The Table contains details of 10
Employees. A User inserts 4 more Employee records. 2 Employees resign and their data are
deleted from the table. The developer also adds a Gender Column to the table. What is the Degree
and Cardinality of the Table? Also mention which column can be used as a Primary Key. Ans.
Degree – 5 and Cardinality – 12 , Primary Key – EID
Q5. Differentiate between Primary Key and Foreign Key.
Ans. An Attribute or a set of Attributes, which uniquely identifies each tuple in the Relation is
known as Primary Key whereas an Attribute or a Set of Attributes in one relation which refer to
the Primary Key of any other Relation is known as the Foreign Key of the Relation. They are
used to establish relationships between Tables. There can only be 1 Primary Key however, there
can be multiple Foreign Keys from multiple Tables.

SHORT ANSWER QUESTIONS (3 MARKS)


[Link] 3 Limitations of DBMS.
Ans. The following are three Limitations of DBMS:-
[Link] Cost – DBMS requires various software, hardware and highly intelligent people, for
operating and maintaining the database system, which adds cost.
[Link] Failure – If Database is corrupted due to power failure or any other reason, our
valuable data may be lost.
[Link] Quality – With increased number of users directly accessing data from a
Database, there are enormous opportunities for data damage.

MYSQL

It is freely available open source Relational Database Management System (RDBMS) that uses
Structured Query Language(SQL). In MySQL database , information is stored in Tables. A single
MySQL database can contain many tables at once and store thousands of individual records.

SQL (Structured Query Language)

SQL is a language that enables you to create and operate on relational databases, which are sets
of related information stored in tables.

59 | P a g e
CLASSIFICATION OF SQL STATEMENTS

SQL commands can be mainly divided into following categories:


1. Data Definition Language(DDL) Commands
Commands that allow you to perform task, related to data
definition e.g; ∙ Creating, altering and dropping.
∙ Granting and revoking privileges and roles.
∙ Maintenance commands.
2. Data Manipulation Language(DML) Commands
Commands that allow you to perform data manipulation e.g., retrieval, insertion, deletion
and modification of data stored in a database.

3. Transaction Control Language(TCL) Commands


Commands that allow you to manage and control the transactions e.g.,
∙ Making changes to database, permanent
∙ Undoing changes to database, permanent
∙ Creating savepoints
∙ Setting properties for current transactions.

MySQL ELEMENTS

1. Literals 2. Datatypes 3. Nulls 4. Comments

LITERALS
It refer to a fixed data value. This fixed data value may be of character type or numeric type.
For example, ‘replay’ , ‘Raj’, ‘8’ , ‘306’ are all character literals.
Numbers not enclosed in quotation marks are numeric literals. E.g. 22 , 18 , 1997 are all
numeric literals. Numeric literals can either be integer literals i.e., without any decimal or be
real literals i.e. with a decimal point e.g. 17 is an integer literal but 17.0 and 17.5 are real
literals.

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 Data Type


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 Data Type
60 | P a g e
1. date – used to store date in YYYY-MM-DD format.
2. time – used to store time in HH:MM:SS format.
String Data Types
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.
DIFFERENCE BETWEEN CHAR AND VARCHAR DATA TYPE

[Link]. Char Datatype Varchar Datatype


1. It specifies a fixed length character String. It specifies a variable length character string.
2. When a column is given datatype as When a column is given datatype as
CHAR(n), then MySQL ensures that all VARCHAR(n), then the maximum size a
values stored in that column have this value in this column can have is n bytes.
length i.e. n bytes. If a value is shorter Each value that is stored in this column
than this length n then blanks are added, store exactly as you specify it i.e. no blanks
but the size of value remains n bytes. are added if the length is shorter than
maximum length n.

NULL VALUE
If a column in a row has no value, then column is said to be null , or to contain a null. You should
use a null value when the actual value is not known or when a value would not be meaningful.
COMMENTS
Comments are used to explain sections of SQL statements, or to prevent execution of SQL
statements. Comments begins from a # character to the end of the line or from a -- sequence to
the end of the line.

DATABASE COMMNADS

1. VIEW EXISTING DATABASE


To view existing database names, the command is :
SHOW DATABASES ;
2. 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 ;
3. ACCESSING DATABASE
For accessing already existing database, we write :
USE <databasename> ;
e.g. to access a database named Student , we write command as :
USE Student ;
4. 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 ;
61 | P a g e
DROP DATABASE Student;
5. VIEWING TABLE IN DATABASE
In order to view tables present in currently accessed database, command is:
SHOW TABLES ;

CREATING TABLES IN MYSQL


- Tables are created with the CREATE TABLE command. When a table is created, its columns are
named, data types and sizes are supplied for each column.
Syntax of CREATE TABLE command is :
CREATE TABLE <table-name>
( <column name> <data type> ,
<column name> <data type> ,
………
<column name> <data type> ) ;
E.g. in order to create table EMPLOYEE given below :
ECODE ENAME GENDER GRADE GROSS

We write the following command :


CREATE TABLE employee
( ECODE integer ,
ENAME varchar(20) ,
GENDER char(1) ,
GRADE char(2) ,
GROSS integer ) ;
INSERTING DATA INTO TABLE
- The rows are added to relations(table) using INSERT command of SQL. Syntax of INSERT
is : INSERT INTO <tablename> [<column list>] VALUES ( <value1> , <value2> , …..) ;
e.g. to enter a row into EMPLOYEE table (created above), we write
command as: INSERT INTO employee VALUES (1001 , ‘Ravi’ , ‘M’ , ‘E4’ ,
50000);
OR
INSERT INTO employee (ECODE , ENAME , GENDER , GRADE , GROSS) VALUES(1001 ,
‘Ravi’ , ‘M’ , ‘E4’ , 50000);

ECODE ENAME GENDER GRADE GROSS


1001 Ravi M E4 50000

In order to insert another row in EMPLOYEE table , we write again INSERT


command : INSERT INTO employee VALUES (1002 , ‘Akash’ , ‘M’ , ‘A1’ , 35000);
62 | P a g e
ECODE ENAME GENDER GRADE GROSS

1001 Ravi M E4 50000


1002 Akash M A1 35000

INSERTING NULL VALUES - To insert value NULL in a specific column, we can type NULL
without quotes and NULL will be inserted in that column. E.g. in order to insert NULL value in
ENAME column of above table, we write INSERT command as :
INSERT INTO EMPLOYEE VALUES (1004 , NULL , ‘M’ , ‘B2’ , 38965 ) ;
ECODE ENAME GENDER GRADE GROSS

1001 Ravi M E4 50000

1002 Akash M A1 35000


1004 NULL M B2 38965

SIMPLE QUERY USING SELECT COMMAND


- The SELECT command is used to retrieve information from a table. Syntax of SELECT
command is :
SELECT <column name>,<column name> FROM <tablename> WHERE <condition name>
; SELECTING ALL DATA
- In order to retrieve everything (all columns) from a table, SELECT command is used
as : SELECT * FROM <tablename> ;
e.g. In order to retrieve everything from Employee table, we write SELECT command
as : SELECT * FROM Employee;
EMPLOYEE
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 NULL M B2 38965

SELECTING PARTICULAR COLUMNS


EMPLOYEE
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 Neela F B2 38965
1005 Sunny M A2 30000
1006 Ruby F A1 45000
1009 Neema F A2 52000

- A particular column from a table can be selected by specifying column-names with


SELECT command. E.g. in above table, if we want to select ECODE and ENAME
column, then command is :
SELECT ECODE , ENAME FROM EMPLOYEE ;
E.g.2 in order to select only ENAME, GRADE and GROSS column, the
command is : SELECT ENAME , GRADE , GROSS FROM EMPLOYEE ;
63 | P a g e
SELECTING PARTICULAR ROWS
We can select particular rows from a table by specifying a condition through WHERE clause
along with SELECT statement. E.g. In employee table if we want to select rows where Gender
is female, then command is :
SELECT * FROM EMPLOYEE WHERE GENDER = ‘F’ ;
E.g.2. in order to select rows where salary is greater than 48000, then command
is : SELECT * FROM EMPLOYEE WHERE GROSS > 48000 ;
ELIMINATING REDUNDANT DATA
The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement. For
example SELECT GENDER FROM EMPLOYEE ;
Gender
M
M
F
M
M
F

SELECT DISTINCT(GENDER) FROM EMPLOYEE ;

DISTINCT(GENDER)
M
F

VIEWING STRUCTURE OF A TABLE


- If we want to know the structure of a table, we can use DESCRIBE or DESC
command, as per following syntax : DESCRIBE | DESC <tablename> ;
e.g. to view the structure of table EMPLOYEE, command is :
DESCRIBE EMPLOYEE ;
OR
DESC 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> ; e.g. In output, suppose we want to display ECODE column as
EMPLOYEE_CODE in output , then command is :
SELECT ECODE AS “EMPLOYEE_CODE” FROM EMPLOYEE ;
CONDITION BASED ON A RANGE
- The BETWEEN operator defines a range of values that the column values must fall in to 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
64 | P a g e
WHERE GROSS BETWEEN 40000 AND 50000 ;
Output will be :
ECODE ENAME GRADE
1001 Ravi E4
1006 Ruby A1

CONDITION BASED ON A LIST


- To specify a list of values, IN operator is used. The IN operator selects value that match
any value in a given list of values. E.g.
SELECT * FROM EMPLOYEE WHERE GRADE IN (‘A1’ , ‘A2’);
Output will be :
ECODE ENAME GENDE R GRADE GROSS

1002 Akash M A1 35000


1006 Ruby F A1 45000
1005 Sunny M A2 30000
1009 Neema F A2 52000

- The NOT IN operator finds rows that do not match in the list.
E.g. SELECT * FROM EMPLOYEE
WHERE GRADE NOT IN (‘A1’ , ‘A2’);
Output will be :
ECODE ENAME GENDE R GRADE GROSS

1001 Ravi M E4 50000


1004 Neela F B2 3896
5

CONDITION BASED ON PATTERN MATCHES


- LIKE operator is used for pattern matching in SQL. Patterns are described using two special
wildcard characters:
1. percent(%) – The % character matches any substring.
2. underscore(_) – The _ character matches any 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%’ ;
Output will be :

e.g. to display details of employee whose second character in name is ‘e’.

SELECT * FROM EMPLOYEE WHERE ENAME LIKE ‘_e%’ ;


Output will be :
ECODE ENAME GENDE R GRADE GROSS

1004 Neela F B2 38965


1009 Neema F A2 52000

65 | P a g e
e.g. to display details of employee whose name ends with ‘y’.

SELECT * FROM EMPLOYEE WHERE ENAME LIKE


‘%y’ ; Output will be :
ECODE ENAME GENDE R GRADE GROSS

1005 Sunny M A2 30000


1006 Ruby F A1 4500
0

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 ;
e.g.
STUDENT
Roll_No Name Marks
1 ARUN NULL
2 RAVI 56
4 SANJAY NULL

to display the names of those students whose marks is NULL, we use the
command : SELECT Name
FROM EMPLOYEE
WHERE Marks IS NULL ;
Output will be :
Name
ARUN
SANJAY

SORTING RESULTS
Whenever the SELECT query is executed , the resulting rows appear in a predecided
order. The ORDER BY clause allow sorting of query result. The sorting can be done
either in ascending or descending order, the default is ascending.

The ORDER BY clause is used as :


SELECT <column name> , <column name>…. FROM <tablename>
WHERE <condition> ORDER BY <column name> ;
e.g. to display the details of employees in EMPLOYEE table in alphabetical order, we use
command :
SELECT * FROM EMPLOYEE ORDER BY ENAME ;
Output will be :
ECODE ENAME GENDER GRADE GROSS
1002 Akash M A1 35000
1004 Neela F B2 38965
1009 Neema F A2 52000
1001 Ravi M E4 50000
1006 Ruby F A1 45000
1005 Sunny M A2 30000

66 | P a g e
e.g. display list of employee in descending alphabetical order whose salary is greater than
40000. SELECT ENAME FROM EMPLOYEE WHERE GROSS > 40000 ORDER BY
ENAME desc ;
Output will be :
ENAME
Ravi
Ruby
Neema

MODIFYING DATA IN TABLES


you can modify data in tables using UPDATE command of SQL. The UPDATE command
specifies the rows to be changed using the WHERE clause, and the new data using the SET
keyword. Syntax of update command is :
UPDATE <tablename> SET <columnname>=value , <columnname>=value WHERE
<condition> ; e.g. to change the salary of employee of those in EMPLOYEE table having
employee code 1009 to 55000.
UPDATE EMPLOYEE SET GROSS = 55000 WHERE ECODE = 1009 ;
UPDATING MORE THAN ONE COLUMNS
e.g. to update the salary to 58000 and grade to B2 for employees whose employee code is
1001. UPDATE EMPLOYEE SET GROSS = 58000, GRADE=’B2’ WHERE
ECODE = 1009 ;
OTHER EXAMPLES
e.g.1. Increase the salary of each employee by 1000 in the EMPLOYEE
table. UPDATE EMPLOYEE SET GROSS = GROSS +100 ;
e.g.2. Double the salary of employees having grade as ‘A1’ or ‘A2’ .
UPDATE EMPLOYEE SET GROSS = GROSS * 2
WHERE GRADE=’A1’ OR GRADE=’A2’ ;
e.g.3. Change the grade to ‘A2’ for those employees whose employee code is 1004 and name
is Neela.
UPDATE EMPLOYEE SET GRADE=’A2’
WHERE ECODE=1004 AND GRADE=’NEELA’ ;
DELETING DATA FROM TABLES
To delete some data from tables, DELETE command is used. The DELETE command
removes rows from a table. The syntax of DELETE command is :
DELETE FROM <tablename> WHERE <condition> ;
For example, to remove the details of those employee from EMPLOYEE table whose grade
is A1. DELETE FROM EMPLOYEE WHERE GRADE =’A1’ ;
TO DELETE ALL THE CONTENTS FROM A TABLE
DELETE FROM EMPLOYEE ;
So if we do not specify any condition with WHERE clause, then all the rows of the table will
be deleted. Thus above line will delete all rows from employee table.

DROPPING TABLES
The DROP TABLE command lets you drop a table from the database. The syntax of DROP
TABLE command is :

67 | P a g e
DROP TABLE <tablename> ;
e.g. to drop a table employee, we need to write :
DROP TABLE employee ;
Once this command is given, the table name is no longer recognized and no more commands
can be given on that table.
After this command is executed, all the data in the table along with table structure will be
deleted. [Link]. DELETE COMMAND DROP TABLE COMMAND 1 It is a DML command. It
is a DDL Command.
2 This command is used to delete only rows of
data from a table
This command is used to delete all the data of the
table along with the structure of the table. The table is
no
longer recognized when this command gets executed.
3 Syntax of DELETE Syntax of DROP command is :
command is: DELETE DROP TABLE <tablename> ;
FROM <tablename>
WHERE <condition> ;

ALTER TABLE COMMAND


The ALTER TABLE command is used to change definitions of existing tables. (adding
columns, deleting columns etc.). The ALTER TABLE command is used for :
1. adding columns to a table
2. Modifying column-definitions of a table.
3. Deleting columns of a table.
4. Adding constraints to table.
5. Enabling/Disabling constraints.

ADDING COLUMNS TO TABLE


To add a column to a table, ALTER TABLE command can be used as per following
syntax: ALTER TABLE <tablename> ADD <Column name> <datatype>
<constraint> ;
e.g. to add a new column ADDRESS to the EMPLOYEE table, we can write
command as : ALTER TABLE EMPLOYEE ADD ADDRESS VARCHAR(50);
A new column by the name ADDRESS will be added to the table, where each row
will contain NULL value for the new column.
ECODE ENAME GENDER GRADE GROSS ADDRESS 1001 Ravi M E4
50000 NULL 1002 Akash M A1 35000 NULL 1004 Neela F B2 38965 NULL
1005 Sunny M A2 30000 NULL 1006 Ruby F A1 45000 NULL
1009 Neema F A2 52000 NULL

However if you specify NOT NULL constraint while adding a new column, MySQL adds the new
column with the default value of that datatype e.g. for INT type it will add 0 , for CHAR types, it
will add a space, and so on.
e.g. Given a table namely Testt with the following data in it.
Col1 Col2
1A
2 G

68 | P a g e
Now following commands are given for the table. Predict the table contents after each of the
following statements:
(i) ALTER TABLE testt ADD col3 INT ;
(ii) ALTER TABLE testt ADD col4 INT NOT NULL ;
(iii) ALTER TABLE testt ADD col5 CHAR(3) NOT NULL ;
(iv) ALTER TABLE testt ADD col6 VARCHAR(3);

MODIFYING COLUMNS

Column name and data type of column can be changed as per following syntax : ALTER TABLE
<table name> CHANGE <old column name> <new column name> <new datatype>; If Only
data type of column need to be changed, then

ALTER TABLE <table name> MODIFY <column name> <new datatype>;


[Link] table EMPLOYEE, change the column GROSS to SALARY.
ALTER TABLE EMPLOYEE CHANGE GROSS SALARY INTEGER;
e.g.2. In table EMPLOYEE , change the column ENAME to EM_NAME and data type from
VARCHAR(20) to VARCHAR(30).
ALTER TABLE EMPLOYEE CHANGE ENAME EM_NAME VARCHAR(30);
[Link] table EMPLOYEE , change the datatype of GRADE column from CHAR(2) to
VARCHAR(2). ALTER TABLE EMPLOYEE MODIFY GRADE VARCHAR(2);
DELETING COLUMNS
To delete a column from a table, the ALTER TABLE command takes the following

form : ALTER TABLE <table name> DROP <column name>;

e.g. to delete column GRADE from table EMPLOYEE, we will write :


ALTER TABLE EMPLOYEE DROP GRADE ;

ADDING/REMOVING CONSTRAINTS TO A TABLE


ALTER TABLE statement can be used to add constraints to your existing table by using it in
following manner:
TO ADD PRIMARY KEY CONSTRAINT
ALTER TABLE <table name> ADD PRIMARY KEY (Column name);
e.g. to add PRIMARY KEY constraint on column ECODE of table EMPLOYEE , the
command is : ALTER TABLE EMPLOYEE ADD PRIMARY KEY (ECODE) ;

TO ADD FOREIGN KEY CONSTRAINT


ALTER TABLE <table name> ADD FOREIGN KEY (Column name) REFERENCES
Parent Table (Primary key of Parent Table);
REMOVING CONSTRAINTS
- To remove primary key constraint from a table, we use ALTER TABLE command
as : ALTER TABLE <table name> DROP PRIMARY KEY ;
- To remove foreign key constraint from a table, we use ALTER TABLE command
as : ALTER TABLE <table name> DROP FOREIGN KEY ;
INTEGRITY CONSTRAINTS/CONSTRAINTS
69 | P a g e
- A constraint is a condition or check applicable on a field(column) or set of
fields(columns). - Common types of constraints include :

[Link]. Constraints Description


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 CHECK Makes sure that all values in a
column satisfy certain criteria 5 PRIMARY KEY Used to uniquely identify a row in
the table
6 FOREIGN KEY Used to ensure referential integrity of the data

NOT NULL CONSTRAINT


By default, a column can hold NULL. It you not want to allow NULL value in a column, then
NOT NULL constraint must be applied on that column. E.g.
CREATE TABLE Customer
( SID integer NOT NULL,
Last_Name varchar(30) NOT NULL,
First_Name varchar(30)
);
Columns SID and Last_Name cannot include NULL, while First_Name can include NULL.

An attempt to execute the following SQL statement,


INSERT INTO Customer VALUES (NULL , ‘Kumar’ , ‘Ajay’);
will result in an error because this will lead to column SID being NULL, which violates the
NOT NULL constraint on that column.

DEFAULT CONSTRAINT
The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value. E.g.
CREATE TABLE Student ( Student_ID integer , Name varchar(30) , Score integer DEFAULT 80);
When following SQL statement is executed on table created above:
INSERT INTO Student

10 Ravi 80
VALUES (10 , ‘Ravi’ );
no value has been provided for score field.

UNIQUE CONSTRAINT
Then table Student looks like the following:
Student_ID Name Score
score field has got the default value

The UNIQUE constraint ensures that all values in a column are distinct. In other
words, no two rows can hold the same value for a column with UNIQUE constraint.
e.g.
CREATE TABLE Customer
( SID integer Unique , Last_Name varchar(30) , First_Name varchar(30) ) ; Column SID

has a unique constraint, and hence cannot include duplicate values. So, if the

70 | P a g e
table already contains the following rows :
SID Last_Name First_Name
1 Kumar Ravi
2 Sharma Ajay
3 Devi Raj

The executing the following SQL statement,


INSERT INTO Customer VALUES (‘3’ , ‘Cyrus‘ , ‘Grace’) ;
will result in an error because the value 3 already exist in the SID column, thus trying to
insert another row with that value violates the UNIQUE constraint.

CHECK CONSTRAINT
- The CHECK constraint ensures that all values in a column satisfy certain conditions. Once
defined, the table will only insert a new row or update an existing row if the new value
satisfies the CHECK constraint. e.g.
CREATE TABLE Customer ( SID integer CHECK (SID > 0), Last_Name varchar(30) ,
First_Name varchar(30) ) ;
So, attempting to execute the following statement :
INSERT INTO Customer VALUES (-2 , ‘Kapoor’ , ‘Raj’);
will result in an error because the values for SID must be greater than 0.

PRIMARY KEY CONSTRAINT


- A primary key is used to identify each row in a table. A primary key can consist of one or
more fields(column) on a table. When multiple fields are used as a primary key, they are
called a composite key.
- You can define a primary key in CREATE TABLE command through keywords PRIMARY
KEY. e.g.
CREATE TABLE Customer ( SID integer NOT NULL PRIMARY KEY,
Last_Name varchar(30) , First_Name varchar(30) ) ;
Or
CREATE TABLE Customer ( SID integer, Last_Name varchar(30) ,
First_Name varchar(30), PRIMARY KEY (SID) ) ;
- The latter way is useful if you want to specify a composite primary key, e.g.
CREATE TABLE Customer ( Branch integer NOT NULL, SID integer NOT
NULL , Last_Name varchar(30) , First_Name varchar(30),
PRIMARY KEY (Branch , SID) ) ;
FOREIGN KEY CONSTRAINT
- Foreign key is a non key column of a table (child table) that draws its values from
primary key of another table(parent table).
- The table in which a foreign key is defined is called a referencing table or child table.
A table to which a foreign key points is called referenced table or parent table.

71 | P a g e
e.g.
TABLE: STUDENT Parent Table
ROLL_NO NAME CLASS Primary key

1 ABC XI

TABLE: SCORE
ROLL_NO MARKS
1 55
2 83

2 DEF XII Child Table 3 90


3 XYZ XI
Here column Roll_No is a foreign key in table SCORE(Child Table) and it is drawing
its values from Primary key (ROLL_NO) of STUDENT table.(Parent Key).
CREATE TABLE STUDENT
( ROLL_NO integer NOT NULL PRIMARY KEY ,
NAME VARCHAR(30) , CLASS VARCHAR(3) );
CREATE TABLE SCORE
( ROLL_NO integer , MARKS integer ,
FOREIGN KEY(ROLL_NO) REFERNCES STUDENT(ROLL_NO) ) ;

* Foreign key is always defined in the child table.


Syntax for using foreign key
FOREIGN KEY(column name) REFERENCES Parent_Table(PK of Parent Table);

REFERENCING ACTIONS
Referencing action with ON DELETE clause determines what to do in case of a DELETE occurs
in the parent table. Referencing action with ON UPDATE clause determines what to do in case of
a UPDATE occurs in the parent table.

Actions:
1. CASCADE : This action states that if a DELETE or UPDATE operation affects a
row from the parent table, then automatically delete or update the matching
rows in the child table i.e., cascade the action to child table.
2. SET NULL : This action states that if a DELETE or UPDATE operation affects a row from
the parent table, then set the foreign key column in the child table to NULL.
3. NO ACTION : Any attempt for DELETE or UPDATE in parent table is not allowed.
4. RESTRICT : This action rejects the DELETE or UPDATE operation for the parent
table.

Q: Create two tables


Customer(customer_id, name)
Customer_sales(transaction_id, amount , customer_id)
Underlined columns indicate primary keys and bold column names indicate foreign key.
Make sure that no action should take place in case of a DELETE or UPDATE in the parent
table. 72 | P a g e
Sol : CREATE TABLE Customer (
customer_id int Not Null Primary Key ,
name varchar(30) ) ;

CREATE TABLE Customer_sales


( transaction_id Not Null Primary Key ,
amount int , customer_id int ,
FOREIGN KEY(customer_id) REFERENCES Customer (customer_id) ON
DELETE NO ACTION ON UPDATE NO ACTION );

Q: Distinguish between a Primary Key and a Unique key in a table.

[Link]. PRIMARY KEY UNIQUE KEY


1. Column having Primary key can’t contain NULL Column having Unique Key can contain NULL
value value

2. There can be only one primary key Many columns can be defined as
inTable. Uniquekey
Q: Distinguish between ALTER Command and UPDATE command of SQL.

[Link]. ALTER COMMAND UPDATE COMMAND 1. It is a DDL Command It is


a DML command
2. It is used to change the definition of existing It is used to modify the data values present in the
table, i.e. adding column, deleting column, etc. rows of the table.

3. Syntax for adding column in a Syntax for using UPDATE


table: ALTER TABLE command: UPDATE <Tablename>
<tablename> SET <Columnname>=value
ADD <Column name><Datatype> ; WHERE <Condition> ;

AGGREGATE / GROUP FUNCTIONS


Aggregate / Group functions work upon groups of rows , rather than on single row, and return
one single output. Different aggregate functions are : COUNT( ) , AVG( ) , MIN( ) , MAX( ) ,
SUM ( )
Table : EMPL

EMPNO ENAME JOB SAL DEPTNO


8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 5643 20
8912 SUR NULL 3000 10

1. AVG( )
This function computes the average of given data. e.g.
SELECT AVG(SAL) FROM EMPL ;

73 | P a g e

Output 2. COUNT( )
AVG(SAL) 6051.6

This function counts the number of rows in a given column.


If you specify the COLUMN name in parenthesis of function, then this function returns
rows where COLUMN is not null.
If you specify the asterisk (*), this function returns all rows, including duplicates and
nulls. e.g. SELECT COUNT(*) FROM EMPL ;
Output
COUNT(*)
5
e.g. SELECT COUNT(JOB) FROM EMPL ;
Output

COUNT(JOB)
4
3. MAX( )
This function returns the maximum value from a given column or
expression. e.g. SELECT MAX(SAL) FROM EMPL ;
Output
MAX(SAL)
9870
4. MIN( )
This function returns the minimum value from a given column or
expression. e.g. SELECT MIN(SAL) FROM EMPL ;

MIN(SAL)
2985
Output
5. SUM( )
This function returns the sum of values in given column or expression.
e.g. SELECT SUM(SAL) FROM EMPL ;

SUM(SAL)
30258
Output

GROUPING RESULT – GROUP BY


The GROUP BY clause combines all those records(row) that have identical values in a particular
field(column) or a group of fields(columns).
GROUPING can be done by a column name, or with aggregate functions in which case the
aggregate produces a value for each group.
Table : EMPL
EMPNO ENAME JOB SAL DEPTN
O

74 | P a g e
8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 20
5643

e.g. Calculate the number of employees in each grade.


SELECT JOB, COUNT(*) FROM EMPL GROUP
BY JOB ;
Output
JOB COUNT(*)
CLERK 1
SALESMAN 2
MANAGER 1
[Link] the sum of salary for each department.
SELECT DEPTNO , SUM(SAL) FROM EMPL GROUP BY DEPTNO ;
Output
DEPTNO SUM(SAL)
10 2985
20 15513
30 8760

e.g.3. find the average salary of each department.

Sol:
** One thing that you should keep in mind is that while grouping , you should include
only those values in the SELECT list that either have the same value for a group or
contain a group(aggregate) function. Like in e.g. 2 given above, DEPTNO column has
one(same) value for a group and the other expression SUM(SAL) contains a group
function.
NESTED GROUP
- To create a group within a group i.e., nested group, you need to specify multiple fields
in the GROUP BY expression. e.g. To group records job wise within Deptno wise,
you need to issue a query statement like:
SELECT DEPTNO, JOB, COUNT(EMPNO) FROM EMPL GROUP BY
DEPTNO, JOB ;
Output
DEPTNO JOB COUNT(EMPNO)
10 CLERK 1
20 SALESMAN 1
20 MANAGER 1
30 SALESMAN 1

PLACING CONDITION ON GROUPS – HAVING CLAUSE


- The HAVING clause places conditions on groups in contrast to WHERE clause that
places condition on individual rows. While WHERE conditions cannot include
aggregate functions, HAVING conditions can do so.
- e.g. To display the jobs where the number of employees is less than 2, -
SELECT JOB, COUNT(*) FROM EMPL GROUP BY JOB HAVING
COUNT(*) < 2 ;
75 | P a g e
Output
JOB COUNT(*)
CLERK 1
MANAGER 1

JOIN
A Join is a Query that combine rows from two or more tables. In a join Query, more than one
tables are listed in FROM Clause.
The function of combining data from multiple tables is called joining.
Joins are used when we have to select data from multiple tables is called joining. Join are used
to extract data from two tables, when we need a relationship between certain columns in these
tables.
There are different kind of SQL joins
1) Equi Join: Equi Join is a simple SQL join condition that uses equal sign as comparison
operator. Syntax
Select col1,col2,col3 from table1 and table2 Where table1.col1=table2.col1
2) Natural Join
The Natural Join is a type of equi join and it structured in such a way that, columns with
same name of associated tables will appear only once.
Syntax
Select * from table1 NATURAL JOIN table2.
In this no need to give the joining condition. It will automatically make the condition based on
the common column in both the tables.
TRANSACTION CONTROL COMMANDS (TCL)
The TCL of MySQL consists of following commands :

1. BEGIN or START TRANSACTION – marks the beginning of a transaction.


2. COMMIT – Ends the current transaction by saving database changes and starts a new
transaction. 3. ROLLBACK – Ends the current transaction by discarding database changes and
starts a new transaction.
4. SAVEPOINT – Define breakpoints for the transaction to allow partial
rollbacks. 5. SET AUTOCOMMIT – Enables or disables the default auto
commit mode

MIND MAP

76 | P a g e
Ch

eck Your Progress :


MCQ
1.
In a table STUDENT in MySQL database, an attribute NAME of data type VARCHAR(20)
has the value “ASEEMA SAHU”. Another attribute SUBJECT of data type CHAR(10)
has value “CS”. How many characters are occupied by attribute
NAME and attribute SUBJECT respectively?
A. 11, 10
B. 11, 2
C. 12, 3
D. 20, 10
2. Identify the MySQL Commands that belongs to DML category :
A. ALTER
B. DROP
C. DELETE
D. CREATE
3. Consider the following Statements :
Statement – 1 : UNIQUE constraint ensures that all the values in a column are
distinct / unique.
Statement – 2 : MySQL is an open-source relational database management
system. A. Only Statement-1 is True
B. Only Statement-2 is True
C. Both Statements are True.
D. Both Statements are False.
4. Fill in the blank:
___________________________ are used to define the different structures
in a database. A. Data Definition Language (DDL) Statement

77 | P a g e
B. Data Manipulation Language (DML) Statement
C. Transaction Control Statement
D. Session Control Statement
5. Naresh wants to create an attribute for admission number. Which will be the most
suitable data type for admission number which can accommodate admission numbers
with 4 digits ?
A. VARCHAR(2)
B. CHAR(3)
C. INT
D. DATE
6. “The column which can uniquely identify each row or record in a
table.” The above Statement refers to which constraints in MySQL ?
A. NOT NULL
B. UNIQUE
C. PRIMARY KEY
D. DEFAULT
7. Identify the Statement which is NOT CORRECT ?
A. It is mandatory to define constraint for each attribute of a table.
B. Constraints are certain types of restrictions on the data values that an attribute
can have.
C. Constraints are used to ensure the accuracy and reliability of data.
D. It is not mandatory to define constraint for each attribute of a table.
8. Choose the correct MySQL statement to create a database named
TARGET100. A. CREATE TARGET100;
B. CREATE DATABASE TARGET100;
C. CREATE DATABASES TARGET100;
D. Database TARGET100 is not a valid database name. Hence, it cannot be
created. 9. Prapti is presently working in the database SUBJECT. She wants to change
and go to the database RECORD. Choose the correct statement in MySQL to go to the
database RECORD.
A. GO TO DATABASE RECORD;
B. USE DATABASE RECORD;
C. CHANGE DATABASE RECORD;
D. USE RECORD;
10. Smiti has entered the following statements in MySQL. But it shows an error as
mentioned below. Help her to identify the reason for such error ?
mysql> CREATE TABLE PRACTICAL(
-> SUBJECT VARCHAR(20),
-> MARKS INT,
-> ROLL INT,
-> NAME VARCHAR(30));
mysql> ERROR 1046 (3D000): No database selected
A. She has to first USE an available database or create a new database and then
USE it. B. Wrong syntax for CREATE TABLE
C. Wrong data type declaration
D. PRACTCAL named table already exists.
ASSERTION – REASONING
Q.11, 12, 13, 14 and 15 are ASSERTION(A) AND REASONING(R) based
questions. Mark the correct choice as
A. Both A and R are true and R is the correct explanation for A
B. Both A and R are true and R is not the correct explanation for A
C. A is True but R is False
D. A is false but R is True

78 | P a g e
11 A table REMEDIAL is created with following attributes, datatype and
constraints: The first record inserted in the table REMEDIAL successfully is as
follows :
Field Datatype Constraints
SNAME VARCHAR(20) NOT NULL
ROLL INT UNIQUE
FEES FLOAT
ADMN INT PRIMARY KEY

SNAME ROLL FEES ADMN


AZAD SARKAR 10 3500 4585

12 Assertion(A): The MySQL statement :


INSERT INTO REMEDIAL (ROLL, FEES, ADMN) VALUES (11, 1800, 4986);
will generate an ERROR and record will not be inserted.
Reasoning(R):
Field 'SNAME' cannot be an empty or NULL value as the Constraint assign is NOT
NULL. 13. Assertion(A): The MySQL statement :
INSERT INTO REMEDIAL VALUES ('PAROMITA DOGRA', 10, 3000, 5500);
will generate an ERROR and record will not be inserted.
Reasoning(R): Duplicate entry '10' for the field 'ROLL'. The Constraint assign is
UNIQUE which restricts the duplicate entry.
14. Assertion(A): The MySQL statement :
INSERT INTO REMEDIAL VALUES ('NEHA JAIN', 25, 3500, 4585);
will generate an ERROR and record will not be inserted.
Reasoning(R): Duplicate entry '3500' for the field 'FEES'.
15. Assertion(A): The MySQL statement :
INSERT INTO REMEDIAL VALUES ('NEHA JAIN', 25, 3500, 4585);
will generate an ERROR and record will not be inserted.
Reasoning(R): Duplicate entry '4585' for the field ADMN. The Constraint assign is
PRIMARY KEY which restricts the duplicate entry.
True False: State True or False for Q.16 to Q20:
16.
MySQL is an open-source relational database management system.
17.
All Candidate Keys are Primary Keys but all Primary keys are not Candidate Keys.
18. MySQL statement to delete a table STUDENT from the database
SCHOOL is DELETE TABLE STUDENT;
19. ALTER TABLE statement is used to make changes in the structure of a table like
adding, removing or, changing datatype of column(s).
20. DDL (Data Definition Language) includes SQL statements such as, CREATE
TABLE, ALTER TABLE and DROP TABLE.
Short Answer Type Questions
21. Write MySQL statements for the following:
i. To create a database named SCHOOL.
ii. To create a table named REMEDIAL based on the following
specification: Field Datatype Constraints
SNAME VARCHAR(20) NOT NULL
ROLL INT UNIQUE
FEES FLOAT
ADMN INT PRIMARY KEY
22. Mr. Kareem Sen has just created a table named “STUDENT” containing columns
SNAME, SUBJECT and FEES. After creating the table, he realized that he has
forgotten to add a PRIMARY KEY column in the table. Help him in writing an SQL
command to add a PRIMARY KEY column ADMN of integer type to the table
Employee.

79 | P a g e
23.
Zenith is working in a database named SCHOOL, in which she has created a table
named “STUDENT” containing columns ADMN, SNAME, GENDER and CATEGORY.
After creating the table, she realized that the attribute, GENDER has to be deleted
from the table and a new attribute FEES of data type FLOAT has to be added. This
attribute FEES cannot be left blank. Help Zenith to write the commands
to complete both the tasks.
24.
(i) State one difference between DDL and DML statements in MySQL.
(ii) Write the MySQL statement to delete the database named
“SCHOOL”.
25. Categorize the following commands as DDL or DML: INSERT, UPDATE, ALTER,
DROP

80 | P a g e

You might also like