12 Computer Science
12 Computer Science
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
NETWORKS
91-113
8. SAMPLE QUESTION PAPER - I 114- 121
3|Page
Computer Science (2024-25) CLASS XII Code No. 083
Computer Science- Class XII
1. Learning Outcomes
2. Distribution of Marks:
3 Database Management 20 25 20
Total 70 110 70
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.
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)
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
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. ‘ “”” “”” ’
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: -
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
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
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
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
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 = " ")
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.
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
Traversal: We can traverse a string using iteration and specifically using for
loop. o Iterate using membership
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
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.
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.
# starting at 0 index
i=0
# 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
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
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.
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)
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?
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.
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
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]()
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 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]()
[Link](list)
[Link]()
[Link]()
f=open("[Link]" , "r")
print([Link]())
[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
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.
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.
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.
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)
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.
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.
(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:
## 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
(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
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
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. 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]()
# 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)
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:
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
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)
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).
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 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
MySQL ELEMENTS
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
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
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
DISTINCT(GENDER)
M
F
- 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
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 :
65 | P a g e
e.g. to display details of employee whose name ends with ‘y’.
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.
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
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> ;
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
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
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.
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
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.
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.
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
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
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
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
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 :
MIND MAP
76 | P a g e
Ch
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
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