0% found this document useful (0 votes)
54 views149 pages

SUPPORTING

The syllabus for Computer Science (2024-25) covers prerequisites, learning outcomes, and a detailed distribution of marks across three units: Computational Thinking and Programming, Computer Networks, and Database Management. Key topics include Python programming concepts, file handling, data structures, networking fundamentals, and SQL database management. Students are expected to apply these concepts through theoretical and practical assessments.

Uploaded by

nivvu2007
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)
54 views149 pages

SUPPORTING

The syllabus for Computer Science (2024-25) covers prerequisites, learning outcomes, and a detailed distribution of marks across three units: Computational Thinking and Programming, Computer Networks, and Database Management. Key topics include Python programming concepts, file handling, data structures, networking fundamentals, and SQL database management. Students are expected to apply these concepts through theoretical and practical assessments.

Uploaded by

nivvu2007
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
You are on page 1/ 149

Syllabus

Computer Science (2024-


25)
1. Prerequisites CLASS XII Code No. 083
Computer Science- Class
XI
2. 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.

3. Distribution of Marks:

Unit No. Unit Name Marks Periods


Theory Practicals
1 Computational Thinking and 40 70 50
Programming – 2
2 Computer Networks 10 15 ---

3 Database Management 20 25 20

Total 70 110 70

4. 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
●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, Packetswitching)
● 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 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
INDEX
S. No. Name of Topic

1 Revision of Python Covered in Class- XI

2 Function and Exception Handling

3 File Introduction and Text File

4 Binary File

5 CSV File

6 Data Structure

7 Computer Networks

8 Database Management and Mysql

9 Interface of Python with Mysql

10 Sample Question Paper-1

11 Sample Question Paper-2

12 Sample Question Paper-3


Unit : 1 Review of Class - 11
Introduction to Python Programming
Python features: Language

 Interpreter based programming language: Line by line execution of Source code.


 Free and Open source: Source code is available free of cost. Free to use
for commercial purposes.
 Portable: Same code can be used for different machines.
 Object Oriented Support: Supports both procedural and OOPs.
 Extensible: Python code can be written in other languages.
 Dynamically typed: Variable datatype can be decided at runtime.
 Robust Standard Library: Extensive standard library available for anyone to use.
 Easy to code and read: Simple syntax, indented blocks make it easy to read and
code. Coding modes in python:
 Interactive mode: Interactive mode is used when a user wants to run one single line or
one block of code. In interactive mode, commands typed at the IDL prompt are executed
when the Enter key is pressed.
 Script mode: Script mode is where you put a bunch of commands into a file (a script),
and then tell Python to run the file. Script mode runs your commands sequentially.
Indentation:
 Indentation refers to the spaces at the beginning of a code line. Where in other
programming languages the indentation in code is for readability only, the indentation in
Python is very important. Python uses indentation to indicate a block of code.
Python Comments:
 Comments are statements in python code that are ignored by the interpreter.
 Comments can be used to explain Python code.
 Comments can be used to make the code more readable.
 Single line comments: These are the statements that start with #

 Multiline comments: Since Python will ignore string literals that are not assigned to a
variable, you can add a multiline string (triple quotes) in your code, and place your
comment inside it:
Python character set:
 A character set is a set of valid characters acceptable by a programming language in
scripting.
 Python supports all ASCII / Unicode characters that include:
o Alphabets: All capital (A-Z) and small (a-z) alphabets.
o Digits: All digits from 0-9.
o Alphabets: All capital (A-Z) and small (a-z) alphabets.
o Special Symbols: Python supports all kinds of special symbols - " ' l ; : ! ~ @ # $
%^`&*()_+–={}[]\.
o White Spaces: White spaces like tab space, blank space, newline, and carriage
return.
o Other: All ASCII and UNICODE characters are supported by Python that
constitutes the Python character set.
Python Tokens:
 A token is the smallest individual unit in a python program.
 All statements and instructions in a program are built with tokens.
 Token Types:
o Keywords: Keywords are reserved by python environment and cannot be used
as identifier. There are 35 keywords in python. You may try to use the following
code to get a list of keywords supported in your python version.

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
o Identifier: Identifiers are the names given to any variable, function, class, list,
methods, etc. for their identification. Python is a case-sensitive language, and it
has some rules and regulations to name an identifier. Here are the rules.
 An Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an
underscore( _ ).
 It can have digits but cannot start with a digit.
 An identifier can’t be a keyword.
 My_name, init , Seven10 are valid examples.
 20dollers, my.var, True are invalid examples.
o Literals: Literals are the values stored in program memory and are often referred
to by an identifier.
 String Literals: The text written in single, double, or triple quotes
represents the string literals in Python.

 Escape characters: To insert characters that are illegal in a


string, use an escape character. An escape character is a
backslash \ followed by the character you want to insert.
Some of the escape characters are as under:
Escape Character Result
Single Quote
\" Double Quote
\\ Backslash
\n New Line
\t Tab
\b Back space
 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+bi numeral, here a represents
the real part and b represents the complex part.
 Boolean Literal: Boolean literals have only two values in Python.
These are True and False.
 Special (None) Literal: Python has a special literal ‘None’. It is used
to denote nothing, no values, or the absence of value.
 Collection Literal: Literals collections in python includes list, tuple,
dictionary, and sets.
o Operators: Operators are responsible for performing various operations in
Python. The operators are of two types Unary (Operates on single operand)
and Operators that operates on two operands (binary).
o Arithmetic Operators: Arithmetic operators are used with numeric
values to perform common mathematical operations:
Operators Name Example
+ Addition 10+20 gives 30
- Subtraction 20-10 gives 10
* Multiplication 30*2 gives 60
/ Division 12/3 gives 4.0
// Floor Division 10//3 gives 3
10.0//3 gives 3.0
% Modulus 10%4 gives 2
** Exponentiation 3**2 gives 9
o Assignment Operators: Assignment operators are used to assign
values to variables:
Operator Example Equivalent
= n = 10 n = 10
+= n+=10 n=n+10
-= n-=10 n=n-10
*= n*=10 n=n*10
/= n/=10 n=n/10
//= n//=10 n=n//10
**= n**=10 n=n**10
%= n%=10 n=n%10

o Relational Operators: These are used to compare two values and


returns a True or False answer.
Operator Name Example
== Equal to 10 == 10 is True
!= Not Equal to 10 != 10 is False
> Greater Than 10 > 5 is True
< Less Than 5 < 10 is False
>= Greater than or Equal 10>=5 is True
to
<= Less than or Equal to 5 <=10 is True
o Logical Operators: They are generally used along with Relational
Operators to extend their scope. However, python allows them to be
used independently.
Operator Description Example
And Returns True if both statements 10 > 20 and 30 <40
are true will return False
Or Return True if one or both the 10 > 20 or 30<40
statements are True will return True
Not Reverses the result not True is False
o Membership Operator: Membership operators are used to test if a
sequence is presented in an object/collection:
Operator Description Example
In Returns True if a sequence with 10 in [5,10,20] will
the specified value is present in return True
the object
not in Returns True if a sequence with 20 not in [5,10,15]
the specified value is not present will return True
in the object
o Identity Operator: The Identity operator returns true only if two
objects occupy the same memory location.
Operator Description Example
Is Returns True if both [10,20,30] is [10,20,30]
variables are the same object will return False since
both occupy different
memory locations even if
they are equal
is not Returns True if both 10 is not 10 will return
variables are not the same False since both are same
object objects
o There are other operators like the Bitwise operators and lambda
operator (function) - These are not in syllabus.
o 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 roe 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
+, - They are next
== != > >= < <= is is not in All the relational, identity and
not in membership operators
Not Not being a unary operator has
precedence over and/or
And Have higher precedence over or
Or Lowest precedence

Some Interesting operations using operators that are often asked in Examinations:
Expression Output Explanation
2**3**2 512 Since ** is evaluated from
right to left, first 3**2 is
evaluated to 9 and 2**9
evaluated 512
10 or 20 10 If the first operand of an “or”
expression is true, return the
first operand. Otherwise,
evaluate and return the second
operand.
0 or 10 10 0 is False and hence second
operand is returned.
10 and 20 20 If the first operand of an
“and” expression is false,
return the first operand.
Otherwise, evaluate and return
the second operand.
Note: Any value is interpreted as “false” for the above purposes if it is 0, 0.0, None, False, or an
empty collection. Otherwise, it is interpreted as “true” for the above purposes. So, 10 and 20,
being nonzero numbers, are “true.”
25 % -4 -3 Python evaluates the
modulus with negative
numbers using the formula:
(a//b) * b + a%b == a
25//-4 gives -7 with floor
division.
-7 * -4 gives 28.
Hence a%b must be -3 to
make the expression
correctly equate to 25.
Note: The sign of the result
is always that of the divisor.

Questions:
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 of 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)
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.
Flow of Control in Python
 Python supports sequential flow of control.
 Python supports branching flow of control using if, elif and else blocks.
 Python supports iteration control using for loop and while
loop. Python if, elif and else blocks:
 Python uses the relational and logical operators along with if and elif to create
conditional blocks that executes a set of python statements depending on the truth value
of the condition.
 The beginning of a block starts from the next line just after the : symbol and the block is
indented.

if block

elif block

else block

 There could be a nested if construct as the following program shows:

Nested if block

With respect to the CBSE examination the students should thoroughly understand the construct
of if, elif, else and often a question comes where you need to identify the errors in each
program.
Q. Re-write the following program after removing errors, if any, and underline all the
corrections made.
a = input("Enter a number:")
b = int(input("Enter a number:"))
if a = b:
a+b=a
else
b=b+a
print(a,b)
Hint: There are four errors in the program
Python for loop:
 Python for loop is used to iterate a set of python statements till a counter reaches its
limit.

 Python for loop can also be used to iterate over a collection object (List, tuple)/ iterable
(string, dictionary) using membership operators.

 Python while loop is used in situations where we have no idea as when the loop is going
to end since there are no counters.

 range() function in python: The range() function returns a sequence of numbers,


starting from 0 by default, and increments by 1 (by default), and stops before a specified
number.

range(start, stop, step)

Step can be +ve or -


ve
Start can be +ve or
-ve
Stop can be +ve or
-ve but is never
reached.

range() example Output sequence


range(10) 0123456789
range(1,11) 1 2 3 4 5 6 7 8 9 10
range(1,11,2) 13579
range(10,0,-1) 10 9 8 7 6 5 4 3 2 1
 break statement in a loop: The break statement stops the loop iteration and exits
from the loop.

The loops exits if the


number n is divisible
by any number
between to and half
of the number

 continue statement: Whenever a continue statement is encountered in a loop the


remaining statements after the continue statement are not executed and the loop
enters next iteration.

The continue
statement will not print
any number that is odd

 else block in loop: The else block in a loop is executed when the break statement is
not encountered inside the loop.

The loop else will be


encountered only for a
prime number since
break will not get
executed during any
iterations

Students are advised to go through the above content since various operations involving the
python data structures, user defined functions, data file handling and database interaction will
require a thorough understanding of iteration. In CBSE examination you may not get a direct
question from this topic except for a few MCQ or Assertion-Reasoning based question.
The following question is an 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, and R is not the correct explanation for A
iii) A is True but R is False
iv) A is false but R is True
Q. ASSERTION: In python loop else block will be executed if the loop successfully
terminates after complete iteration.
REASON: A python loop else block will not execute if a break statement is encountered
in a loop.
Q. ASSERTION: A continue statement in a loop is mandatory.
REASON: A continue statement will skip the remaining statements in the loop after it is
encountered.
Python Strings
 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 acquire a string from user.

The string
inside an
input() method
is a prompt

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 a replicated string.


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

Str[start:stop:step]

Stop is
not
reached.

 Traversal: We can traverse a string using iteration and specifically using for loop.
o Iterat
e 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: These methods accept string as a parameter –
methodName(string)

o String Library Methods: These methods have the syntax


string.methodName()

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

 Methods that return a number based on the requirement:


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.

The first M is
not included
since the start
index is 2

The first M and


the last M are
not included
since the start
index is 2 and
stop is 10

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.

The first M is
not included
since the start
index is 2 and
hence the
index value of
the next M is 6

The start is
7 hence first
two M’s are
not included.

find(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. This is same as index()
index(substr) find(substr)
This function throws a ValueError This function returns -1 if the
if the substring is missing from substring is missing from the
the string. string.

 Methods that modify an existing string and returns a new string:


capitalize(): Converts the first character of a string to upper case and
all other alphabets to lower case. Incase the first character is not an
Alphabet, only the remaining alphabets will be converted to lower
case.

title(): Converts all the first characters of each word of a string to


upper case, in case they are alphabets. The remaining alphabets are
converted to lower case.

replace(oldsubstr, newsubstr): Replaces all the first parameter with


the second parameter and returns a new string.
upper(): Converts all the lowercase alphabets in a string to upper case
and returns a new string.

lower(): Converts all the uppercase alphabets in a string to lowercase


and returns a new string.

 Methods that create a new object from an existing string:


partition(substr): Returns a tuple with three elements from a
string where the middle element is the substring.

split() – Returns a list with a sequence of substrings by eliminating all


the spaces and newlines from the existing string.

split(substr): Returns a list with a sequence of substrings by


eliminating all the occurrences of the substring from the existing
string.
Observe that all the A are removed because of the above method call
and since there is no character after the last A, an empty string is
introduced.
Questions:
Q.1 What will be the output of the following python statement?
s = "HOME ALONE"
p = s.split("O")
print(p[1][:2]+p[-1])
a) ALNE
b) MENE
c) MEONE
d) MEAL
Q.2 What will be the output of the following python code?
s="finaL eXam"
print(s.title())
a) FinaL Exam
b) Final Exam
c) FinaL exam
d) Error
Q.3 What is the output of print("hello".find('E'))?
a) 1
b) 2
c) -1
d) Error
Q.4 Which of the following statements is False for a python String?
a) Python Strings are immutable objects.
b) Python Strings can be accessed using indexing.
c) Python Strings cannot be empty.
d) We can get a substring from an existing string using slicing.
Q.5 What will be the correct output of the following string operation?
"MALAYALAM".partition("MA")
a) ("MA","LAYAL", "AM")
b) ("","MA","LAYALAM")
c) ("MA","LAYALA","AM")
d) ("MALAYAL","AM","")
Q.6 Which of the following statements will generate an
error? st = "PYTHON"
t = st*5 Statement(1)
u = st[0] + "M" Statement(2)
st[0] = "K" Statement(3)
st = st + st Statement(4)
a) Statement(1)
b) Statement(2)
c) Statement(3)
d) Statement(4)
Q.7 What will be the output of the following python statement?
s = "MONGO"
print(sorted(s))
a) "GMNOO"
b) ["GMNOO"]
c) ["G","M","N","O","O"]
d) Error
Q.8 What will be the output of the following string operations:
s="Python is osome good"
i) print(s.index('o',13,20))
ii) print(s[2:4]+s[14])

Python 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 sublists by specifying
a range of indices.
List Examples:

Accepting a list from User: eval() method can be used along with input() method to acquire a
list from the console.

List Operations: Like a String, python lists also support operations like Concatenation,
Replication, indexing, slicing and iteration. The only difference is that we can modify the
elements of a list using indexing, slicing and index-based iteration. In this study material we
shall see this component of python list that makes it unique mutable data structure.
 Indexing of nested lists:
Changing list elements using indexing: We can change the elements of a list using indexing
and assignment operation.

 Changing the list elements using slicing: We can change the replace the contents of
a list using slicing too. Given below are some interesting examples.

Observe here that the slice 2:2


is not removing any element
from the list, but inserting the
elements of the new list in the
given index 2

Observe here that the slice 2:3


is removing element 5 from the
list and inserting the elements
of the new list in the given
index 2

 Changing list elements using index-based iteration: We can modify the elements of
a list using index-based iteration.

 Deleting elements of a list using del command: del command may be used to
delete one or more than one element of a list either using indexing or using slicing.

Note: Deleted elements using del command cannot be retrieved back.


 List Methods: Python has a few built-in and list library methods (also built-in) to
manipulate lists. Some of them as elaborated below with examples:
o Global Methods: These methods accept string as a parameter –

methodName(list)
o List member methods: These methods have the format
listName.methodName()
clear() – Removes all the elements from a list and makes the list empty.

copy() – Creates a copy of the existing list and both list occupy different
memory locations.

append() – Adds an element to the end of an existing list

extend() – Individually appends the contents of one list to another list

insert() – Inserts an element to a given index. The remaining elements are


automatically shifted to the right.
pop() – Removes and returns the last element from the existing list.

pop(index) – Removes and returns the element from the given index.

remove(element): Removes the element from the given list without returning the
element. Return a ValueError is the element is not in the list.

count(element) – Counts and returns the number of occurrences of the given


element.

Note: Unlike count() in String there is only one parameter to count() in list.
index(element, start) – Returns the index of the first occurrence of the given
element from the list.

If the start index is not given, the index() returns the index of first occurrence
only.
sort() – Sorts the list in ascending order. Unlike sorted() this method sorts the
same list and does not return a new list.
reverse() – Reverses the list based on value (ASCII value)

Questions:
Q.1 What will be the output of the following list operations?
data = [10,20,30,[40,50,60],[70,80]]
a) print(data[3]+data[-1])
print(data[-2][-2])
Q.2 What will be the output of the following python program:
data = [10,20,30, 60,70]
data[3:3]=[40,50]
print(data)
data.pop(3)
print(data)
data.extend([10,20])
print(len(data))
Q.3 Ganga is learning to use python Lists. Help her to get the answers of the following
operations based on the given list:
data = [10,20,30]
data[1:3]=[5,10]
print(data)
data.extend([3,4])
x =data.count(10)
print(data[x:])
data.sort()
print(data)
print(data.pop(2))
Q.4 Write a python program that accepts a list of integers from user and creates a new list
from the existing list containing all the numbers that have three or more digits.
Eg: for existing list [10,100, 99,200,1000] the new list should be [100,200,1000]
Q.5 Write a python program that accepts a list of countries from user and prints all the
countries whose number of alphabets is more than 5.
Q.6 Write a python program that accepts a list of integers from user and prints all the
integers that have 8 as the last digit.
Eg: for the list [10, 28, 8, 86, 98] the program should print 28 8 98
Q.7 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]

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:

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.

See here that the


latest value is
updated for the
existing key A
 Dictionary Methods: Like Strings and lists, dictionaries too have global and
member functions.
o Global functions: The global functions include len(), max(), min(), sum() and

sorted()
o Dictionary Member Methods: These methods are called using the
syntax dictName.methodName()
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.

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() – Reoves the last added key-value pair from the dictionary and returns
a tuple containing the removed key-value pair.

fromkeys(key-seq, value) – Returns a dictionary containing the keys as the


element of the sequence(list, tuple) and a single optional value.

setdefault(key, value) – Returns the value for the key if the key is in the
dictionary, else adds the key-value pair to the dictionary.
Questions:
Q.1 Which of the following statements is False for a python dictionary?
a) Dictionary Keys can be created using another dictionary.
b) Dictionary values can be a dictionary.
c) Dictionary Values are mutable.
d) dict() function can be used to create a dictionary.
Q.2 What will be the output of the following program?
d={'A':10,'B':20,'C':30,'D':40}
del d['C']
print(d)
x = d.popitem()
print(x)
Questions 3 is an 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, and R is not the correct explanation for A
iii) A is True but R is False
iv) A is false but R is True
Q.3 ASSERTION: A python dictionary remains the same even if we interchange the position
of key-value pairs.
REASONING: Dictionaries are un-ordered collection of key-value pairs.
Q.4 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.5 Sapna wants to understand the concept of methods in a dictionary. Help her to find the
answers of the following operations on a python dictionary:
d = {'M':10, 'N':20, 'O':30, 'P':40}
r = d.popitem()
print(r)
x = d.pop('N')
print(x)
print(list(d.keys()))
d.setdefault('X',60)
print(d)
Q.6 Write a python program that increases the values by 10 for the dictionary alphabets as
keys and numbers as values where ever the key is a vowel.
Python Tuples
 Python tuples are a collection of objects enclosed in ().
 Python tuples are immutable.
 Python tuples are ordered.
 Python tuples are indexed like lists and strings.
 Python tuples may contain heterogenous elements.
 Python tuples can be nested.
Tuple examples:

Tuple operations: Like string and lists tuples too have concatenations, replication, indexing,
slicing and iteration operation. We are not going to discuss them here since you can follow the
list and strings to learn and practice them.
Tuple methods: Tuples have a few global methods and only two member methods.
o Global Methods – tuple(), min(), max(), len(), sum() and sorted(). We
shall discuss here only the sorted() method.

o Tuple member methods:


index(element) – Like lists tuple too returns the index of the first occurrence of
the element.
count(element) – Counts the occurrences of an element from a tuple as we have
learned in lists.

Python Functions
Python Function:- Functions is a block of code that 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 :- Build in function ( all functions defined by python min() max() ,
lent() etc, User-defined functions ( defined by the user )
Advantage of function :- (i) Reduces the size of the program (ii) improves reusability
of code
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.
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 not default parameters.
def << name of the >> (formal parameters ) : function body is always writer
in tab indentation
code hare
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 12 and 30 are actual parameter.

Q. Write a function findbig that take 2 integers as parameters and returns the largest
value.
def findbig(a,b):
if a>b:
return a
else:
return b
x,y=5,10
bigvalue=findbig(x,y)

Practice questions:

(i) def fun2(name,age):


print(age,name)
func2(25,”Ramesh”) Ans :- Ramesh, 25

(ii) def fun3(a,b,c):


return a+1,b+2,c+3 #if more than 1 values are returned than it
will be as tuple
t=fun3(10,20,30)
print(t) Ans:- (11,12,33 )
(iii) def fun2(list1):
for x in list1:
print(x.upper(),end=”#”)
fun2([‘Rajesh’,’Kumar’]) Ans:- RAJESH # KUMAR
(iv) def fun2(num1,num2):
for x in range(num1,num2):if x
%4==0:
print(x,end=’ ‘)
fun2(10,20) Ans:- 10 12 16 18
(v) def prog(email):
for x in email.split(“.”):
if x.isalpha():
print(“alphabet”)
elif x.isdigit():
print(“digit”)
elif x.isupper():
print(“upper”)
else:
print(“all the best”)
prog(“rajesh.123.yahoo”)

Ans :- AlphabetDigit
Alphabet
(vi) def check(x,y):
if x != y:
return x+5
else:
return y+10
print(check(10,5)) Ans :- 15
TEXT FILE HANDLING
Key points:
Data File- A file is a sequence of bytes on the disk/permanent storage where a group of related data
is stored. File handling in Python enables us to create, update, read, and delete the files stored on the
file system through our python program.
Data File handling takes place in the following order.
1- Opening a file.
2- Performing operations (read, write) or processing data.
3- Closing the file.
Types of files in Python:
Python allows us to create and manage three types of data files.
1- Text file
2- Binary file
3- CSV file
Text file: A text file is simply a sequence of ASCII or Unicode characters.A line is a sequence of
characters, stored on permanent storage. In a text file, each line is terminated by a special character,
known as End Of Line (EOL). Text file can be created using any text editor. Ex. Myfile.txt.
Binary file: A binary file stores the data in the same way as stored in the memory. The .exe files, mp3 file,
image files, word documents are some of the examples of binary files. We can’t read a binary file using a
text editor.
CSV file: CSV (Comma Separated Values) is a file format for data storage which looks like a text file. The
information is organized with one record on each line and each field is separated by comma
CSV File (Comma-
Aspect Text File Binary File
Separated Values)
Stores tabular data in plain
Format Contains plain text Contains binary data
text
Content Human-readable Not human-readable Human-readable
Character
ASCII, UTF-8 Not applicable ASCII, UTF-8
Encoding
Data is stored as lines of Data is stored as sequences Data is organized into rows
Structure
text of binary bytes and columns
Suitable for storing textual Suitable for storing non- Ideal for storing structured
Usage
data textual data tabular data
Example File
.txt .jpg, .mp3, .exe .csv
Extensions
1. Opening a Text File
 Use the open() function to open a text file.
 Syntax: file_object = open("filename.txt", mode)
 Replace "filename.txt" with the name of the text file and mode with the desired file open mode.
2. Text File Modes
 'r': Read mode. Opens a file for reading only. Raises an error if the file does not exist.
 'r+': Read and Write mode. Opens a file for both reading and writing.
 'w': Write mode. Opens a file for writing only. Creates a new file if it does not exist. Truncates
the file if it exists.
 'w+': Write and Read mode. Opens a file for reading and writing. Creates a new file if it does
not exist. Truncates the file if it exists.
 'a': Append mode. Opens a file for appending data. Creates a new file if it does not exist.
 'a+': Append and Read mode. Opens a file for appending data and reading. Creates a new file if
it does not exist.
3. Closing a Text File
 Always close a file after operations to release system resources.
 Use the close() method on the file object: file_object.close().
4. Opening a File Using with Clause
The with statement ensures that the file is properly closed after its suite finishes executing.
Syntax:
with open("filename.txt", mode) as file_object:
# Perform file operations
5. Writing/Appending Data to a Text File
 Use the write() method to write data to a file.
The write() function will write the content in the file without adding any extra characters.
file_name.write(content)
 Use the writelines() method to write a sequence of lines to a file.
file_name.writelines(sequence_of_lines)
 If the file is opened in write mode ('w' or 'w+'), it will overwrite existing content.
 If the file is opened in append mode ('a' or 'a+'), new data will be added to the end of the file.
6. Reading from a Text File
 Use the read() method to read the entire contents of a file as a single string if value of n is not
given else it will read n characters from the current position.
File_object.read([n])
 Use the readline() method to read a single line from the file.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes.
 Use the readlines() method to read all lines from the file into a list.
7. seek() and tell() Methods
seek() method is used to position the file object at a particular position in a file. The syntax of
seek() is:
file_object.seek(offset [, reference_point])
In the above syntax, offset is the number of bytes by which the file object is to be moved.
reference_point indicates the starting position of the file object. That is, with reference to which
position, the offset has to be counted. It can have any of the following values:
0 - beginning of the file
1 - current position of the file
2 - end of file
By default, the value of reference_point is 0, i.e. the offset is counted from the beginning of the file.
For example, the statement fileObject.seek(5,0) will position the file object at 5th byte position
from the beginning of the file.
tell() method returns the current file position. This function returns an integer that specifies the
current position of the file object in the file. The position so specified is the byte position from the
beginning of the file till the current position of the file object. The syntax of using tell() is:
file_object.tell()

Questions:
S.No. 1 Mark Questions Answers
1. What is the extension of regular text files? A
a).txt b).dat
c).ppt d) .doc
2. Which files can be opened in human readable form? B
a) binary files b) text files
c) Both a and b d)None
3. What is the default mode in which text file is opened? B
a)write b)read
c)append d)None
4. Which statement is correct for opening the file? C
a) f=open(“c:\\data.txt”,”r”)
b) f=open(r”c:\data.txt”,”r”)
c) Both a
and b d)None
5. Which of the following mode cannot be used for opening the text file? D
a) ’r’ b)’w+’
c)’a’ d)’rb+’
6. Which is correct way of closing the text file? A
a)f.close() b)close(f)
c) Both a and b d)None
7. Which statement is correct to read n bytes from text file using f as file A
object?
a)f.read(n) b)f.readline(n)
c)Both a and b d)None
8. Which of the following function is used to read all the lines of the text C
file?
a)readline() b)read()
c)readlines() d)readit()
9. What is the return datatype of read () function? A
a)string b)List
c)Tuple d)Dictionary
10. What is the return datatype of readlines() function? B
a)string b)List
c)Tuple d)Dictionary
11. Which function is used to write group of characters on to the text file? B
a)writegroup() b)write()
c)writechar() d)writeall()
12. Which function is used to write List of strings on to the text file? C
a)writelist() b)writeline()
c)writelines() d)writeall()
13. In which mode text file should be opened to add the data at the end to the C
text file?
a)’r’ b)’w’
c)’a’ d)’b’
14. Which of the following command can be used to open the text file in C
writing as well as reading mode?
a)f=open(“c:\data.txt”,’r’) b)f=open(“c:\data.txt”,’w+’)
c)f=open(c:\\data.txt”,’w+) d) f=open(“c:\\data.txt”,’w’)
15. hich of the following statements is true regarding the opening modes of a A
file?
a) While opening a file for reading, if the file does not exist, an error
occurs.
b) While opening a file for writing ,if the file does not exist, an error
occurs.
c) While opening a file for reading, if the file does not exist, a new file is
created.
d) None of the above.
16. State True or False True
“csv files are special text files”
17. State True or False True
“text files are slower in processing as they requires translation of special
characters”
18. Assertion(A): File opened in’ w’ mode always places the cursor at the A
beginning of the file and never generates an error.
Reason(R): ‘w’ mode creates the file even if the file doesn’t exist.

a) Both A and R are true and R is the correct explanation of A.


b) Both A and R are true but R is not the correct explanation of A.
c) A is true but R is false.
d) R is true but A is false.
19. Assertion(A):Text file contains data in human readable form. C
Reason(R): It executes faster than any other type of the file.

a) Both A and R are true and R is the correct explanation of A.


b) Both A and R are true but R is not the correct explanation of A.
c) A is true but R is false.
d) R is true but A is false.
20. Assertion(A): read()and readline() are used to read the data from the text B
file.
Reasoning(R): readlines() function is used to read all lines from the file
in the form of a List.

a) Both A and R are true and R is the correct explanation of A.


b) Both A and R are true but R is not the correct explanation of A.
c) A is true but R is false.
d) R is true but A is false.
2 Mark questions
1. What is the difference between read() and readline() function of text files?
Ans The read() function read specified number of n bytes. If n is not specified, read the entire
file.
e.g. s=f.read(10) #read 10 bytes
s= f.read() # read the entire file

The readline() function read a single line. If n is specified , read n bytes from the file.
e.g. p=f.readline() # read single line
p=f.readline(7) # read 7 bytes from the file

2. What is the difference between readlines() and readline() function used with the text file?
Ans The function readlines() read all the lines of the text file and store them as elements of
the List.
e.g. s= f.readlines() # all lines of text file will be read and store in list s

The function readline() will read a single line from the text file and if n is specified as
the argument, read n bytes from the file.
e.g. p=f.readline() # read single line
p=f.readline(7) # read 7 bytes from the file

3. Name the functions used to write data on the text files. Explain
Ans The two functions write() and writelines() are used to write data on the text files.
a)write()- This function writes a group of characters on to the text file.
e.g. s=”Computer Science”
f.write(s) # It will write string s to the file using file object f

b) writelines()- This function write strings in List as Lines to the file.


e.g. f.writelines(L) # It will write strings in List L as lines in the file using file pointer f.

4. What is the difference between ‘w’ and ‘a’ mode used while opening a text file?
Ans When ‘w’ mode is used while opening the text file , it opens the file in write mode and
places the cursor at the beginning of the file and truncates the data of the file. And if file
doesn’t exist ,it creates the file.

Whereas when ‘a’ mode is used while opening the file, it opens the file in append mode and
places the cursor at the end of the file for adding the data at the end. Here also file is created
, if file doesn’t exist.
5. What is the difference between ‘r+’ mode and ‘w+’ mode used while opening the text file?
Ans With both the modes reading and writing operations can take place, but difference is that if
file is opened using ‘w+’ mode, file is created if file doesn’t exist, whereas if file is opened
using ‘r+’ mode, error is raised if file doesn’t exist.
6. If the focus.txt file contains the following text:

Mindfulness, cognitive training, and a healthy lifestyle may help sharpen your focus.

Find the output of the following code:

F=open(“focus.txt”,’r’)
S=F.read(11)
print(S)
F.close()
Mindfulness
Ans
7. Find the output of the following code:

F=open(“focus.txt”,’r’)
S= F.readline()
print(S)
T=F.readline()
print(T)
F.close()

Ans Mindfulness, cognitive training, and a healthy lifestyle may help


sharpen your focus

8. Find the output of the following code:

F=open(“focus.txt”,’r’)
L= F.readlines()
for a in L:
print(a.upper())
F.close()

Ans MINDFULNESS, COGNITIVE TRAINING, AND A HEALTHY LIFESTYLE MAY HELP

SHARPEN YOUR FOCUS

9. Find the output of the following code:

F=open(“focus.txt”,’a+’)
S= “ sleep reduces stress hormones that can be harmful to the brain”
F.write(S)
F.seek(0) # bring cursor to the beginning of the file
L=F.readlines()
print(L)
F.close()

Ans ['Mindfulness, cognitive training, and a healthy lifestyle may help\n', 'sharpen your focus
sleep reduces stress hormones that can be harmful to the brain']

10. Find the output of the following code:

F=open(“wish.txt”, ’w’)
F.write(“Day”)
F.close()

If the file contains “Good” before execution, what will be the contents of the file after
execution of the above code.

Ans After execution, file will contain “Day” only as previous data will be truncated by write
operation over the file.

3 Marks questions
1. Write a program to read text file story.txt and count number of lines starting with
letter ‘A’ or ‘a’.

Ans F=open("story.txt",'r')
count=0
L=F.readlines()
for i in L:
if i[0]=='A' or i[0]=='a':
count=count+1
print("no. of lines starting with a=",count)
F.close()

2. Write a program to read the file data.txt and count number of uppercase, lowercase
in it.

Ans F=open("data.txt",'r')
u=0
l=0
s=F.read()
for i in s:
if i.isupper():
u=u+1
if i.islower():
l=l+1
print("Number of uppercase characters=",u)
print("Number of lowercase characters=",l)
F.close()
3. Write a program to read the file data.txt and count number of spaces in it.

Ans F=open("data.txt",'r')
space=0
s=F.read()
for i in s:
if i.isspace():
space=space+1
print("Number of spaces=",space)
F.close()
4. Write a program to read the file hash.txt and display the number characters up to
first #.

Ans F=open("hash.txt",'r')
count=0
s=F.read()
for i in s:
if i!='#':
count=count+1
else:
break
print("Number of characters up till # =",count)
F.close()
5. Write a program to read the file alphabet.txt and display all the lines in uppercase.
Ans F=open("alphabet.txt",'r')
L=F.readlines()
for i in L:
print(i.upper())
F.close()
6. Write a program to read the file data.txt and count number of lines present in it.

Ans F=open("data.txt",'r')
L=F.readlines()
print("Number of lines in the file=",len(L))
F.close()
7. Write a program to read the file data.txt and display only the digits present in it.

Ans F=open("data.txt",'r')
s=F.read()
for letter in s:
if letter.isdigit():
print(letter)
F.close()
8. Write a program to read the file story.txt and display second last line of the file.

Ans F=open("story.txt",'r')
L=F.readlines()
print(L[-2])
F.close()
9. Write a program to read the file article.txt and count occurrences of words “the” in
the file.

Ans F=open("article.txt",'r')
count=0
s=F.read()
L=s.split()
for word in L:
if word=="the":
count=count+1
print("No. of occurences of word the=",count)
F.close()
10. Write a program to read the file letter.txt and display those words which has less
than or equal to four characters.

Ans F=open("story.txt",'r')
s=F.read()
L=s.split()
for word in L:
if len(word)<=4:
print(word)
F.close()

4 Marks questions
1 Write python statements for opening the following files. Also, write the Python
statements to open the following files:
a) a text file “example.txt” in both read and write mode
b) a text file “bfile.dat” in write mode
c) a text file “try.txt” in append and read mode
d) a text file “btry.dat” in read only mode.

Ans (a) F = open(‘example.txt’,”r+”)


(b) F = open(“bfile.dat” , “w”)
(c) F = open(‘try.txt’ , “a”)
(d) F = open(‘btry’ , ’r’)
2 (i) What is the difference between the following set of statements (a) and (b):
a) P =
open(“practice.txt”,”r”)
P.read(10)
b) with open(“practice.txt”, “r”) as P:
x = P.read()

Ans Set of statements (a) would read the file “practice.txt” and returns a string that
contains first 10 characters of the text file.
Set of statements (b) will read the text file “practice.txt” and returns a string that
contains entire contents of the text file.
(ii) Write a command(s) to write the following lines to the text file named hello.txt.
Assume that the file is opened in append mode.
“ Welcome my class”
“It is a fun place”
“You will learn and play”

Ans F = open(“TFILE.txt”, ‘a’)


L = [“ Welcome my class” , “It is a fun place” , “You will learn and play”]
F.writelines(L)
F.close()
3 Write a method/function COUNTLINES_ET() in python to read lines from a text
file REPORT.TXT, and COUNT those lines which are starting either with ‘E’
and starting with ‘T’ respectively. Display the Total count separately.

Ans def COUNTLINES_ET():


f=open(“REPORT.TXT”)
d=f.readlines()
le=0
lt=0
for i in d:
if i[0]==’E:
le=le+1
elif i[0]==’T’:
lt=lt+1
print(“no of line start with”,le)
print(“no of line start with”,lt)
4 Write a function filter(oldfile, newfile) that copies all the lines of a text file
“source.txt” onto “target.txt” except those lines which starts with “@” sign.

Ans def filter(oldfile, newfile):


f1 = open("oldfile","r")
f2 = open(“newfile”,”w”)
while True:
text= f1.readline()
if len(text) ==0:
break
if text[0] == ‘@’:
continue
f2.write(text)
f1.close()
f2.close()
5 (i) Write a user defined function countwords() to display the total number of words
present in the file from a text file “Quotes.Txt”.

Ans def countwords():


s = open("Quotes.txt","r")
f = s.read()
z = f.split ()
print ("Total number of words:", len(z))
(ii) Write a function COUNT_AND( ) in Python to read the text file “STORY.TXT”
and count the number of times “AND” occurs in the file. (include AND/and/And in
the counting)

Ans def COUNT_AND( ):


count=0
file=open(‘STORY.TXT','r')
line = file.read()
word = line.split()
for w in word:
if w.upper() ==’AND’:
count=count+1
print(count)
file.close()

5 Marks questions
1 (i) Differentiate between Text files and Binary files.
Ans Text file: A text file is simply a sequence of ASCII or Unicode characters.A line is a
sequence of characters, stored on permanent storage. In a text file, each line is
terminated by a special character, known as End Of Line (EOL). Text file can be
created using any text editor. Ex. Myfile.txt.
Binary file: A binary file stores the data in the same way as stored in the
memory. The .exe files, mp3 file, image files, word documents are some of the
examples of binary files. We can’t read a binary file using a text editor.
(ii) Write a method COUNTWORDS() in Python to read data from text file
‘ARTICLE.TXT’ and display the count of words which ends with a vowel.
For example, if the file content is as follows:
An apple a day keeps you healthy and wise
The COUNTWORDS() function should display the output as:
Total words which ends with vowel = 4
Ans def COUNTWORDS():
fil = open('ARTICLE.TXT' , 'r')
data = fil.read()
words = data.split()
count = 0
for w in words:
if w[-1] in 'aeiouAEIOU':
count += 1
fil.close()
print('Total words which ends with vowel =',count)
2 (i) Explain seek() and tell() methods.
Ans seek() method is used to position the file object at a particular position in a file.
The syntax of seek() is:
file_object.seek(offset [, reference_point])
For example, the statement fileObject.seek(5,0) will position the file object at 5th
byte position from the beginning of the file.
tell() method returns the current file position. This function returns an integer that
specifies the current position of the file object in the file. The position so specified
is the byte position from the beginning of the file till the current position of the file
object. The syntax of using tell() is:
file_object.tell()
(ii) Write a function COUNT() in Python to read from a text file ‘rhym.txt' and display
the count of words in each line.
Example: If the content of ‘rhym.txt’ is as follows:
Jack and jill
Went up the hill
To enjoy
Then the COUNT() function should display output as:
Line 1 : 3
Line 2 : 4
Line 3 : 2

Ans def COUNT():


fil = open('rhym.txt')
lines = fil.readlines()
c=1
for l in lines:
words = l.split()
print('Line',c,':',len(words))
c = c+1
fil.close()
3 (i) Differentiate between w+ and a+ file modes.
Ans
Parameter w+ Mode a+ Mode
Opens a file for reading
Opens a file for reading and
Description and appending (creates
writing (truncate file).
file if not exists).
Points at the beginning of the Points at the end of the
File Pointer file after opening. file after opening.
Overwrites existing content Appends new data to the
Write Operation with new data. end of the file.
Reads from the beginning of the Reads from the beginning
Read Operation file. of the file.
Truncates the file to zero length Does not truncate the file;
File Truncation
if it exists. preserves existing content.
Creates a new file if it does not
Creates a new file if it
Creation
exist. does not exist.
Useful for scenarios
Useful for scenarios where
where data needs to be
existing content needs to be
Usage appended to an existing
overwritten or a new file needs
file without losing the
to be created.
existing content.
(ii) Write a function WE_WORDS() in Python to read from a text file ‘TEXT.TXT’ and
display the count of words which starts with ‘WE’.
Example: If the content of ‘TEXT.TXT’ is as follows:
WE MUST WELCOME ALL WEATHER FROM
WEST
Then the WE_WORDS() function should display output as:
TOTAL WORDS STARTING WITH WE = 4
Ans
def WE_COUNT():
fil =
open('TEXT.TXT') data
= fil.read()
words = data.split()
count = 0
for w in words:
if w.startswith('WE'):
count = count + 1
print('TOTAL WORDS STARTING WITH WE=',count)
fil.close()
4 (i) What will be the return datatype of the following methods:
read()
readlines()

Ans read() – String


readlines() – List
(ii) A pre-existing text file data.txt has some words written in it. Write a python
function displaywords() that will print all the words that are having length greater
than 3.
Example:
For the fie content:
A man always wants to strive higher in his life He wants to be perfect.
The output after executing displayword() will be: Always wants strive higher life
wants perfect

Ans def displaywords():


f = open('data.txt','r')
s = f.read()
lst = s.split() for x in lst:
if len(x)>3:
print(x, end=" ")
f.close()
5 (i) Explain the use of seek() method.

Ans seek() method is used to position the file object at a particular position in a file.
The syntax of seek() is:
file_object.seek(offset [, reference_point])
In the above syntax, offset is the number of bytes by which the file object is to be
moved. reference_point indicates the starting position of the file object. That is,

with reference to which position, the offset has to be counted. It can have any of
the following values:
0 - beginning of the file
1 - current position of the file
2 - end of file
By default, the value of reference_point is 0, i.e. the offset is counted from the
beginning of the file.
(ii) A pre-existing text file info.txt has some text written in it. Write a python function
countvowel() that reads the contents of the file and counts the occurrence of
vowels(A,E,I,O,U) in the file.

Ans def countvowels():


f = open('info.txt', 'r')
s = f.read()
count = 0
for x in s:
if x in 'AEIOU':
count+=1
print(count) f.close()

BINARY FILE HANDLING IN PYTHON

Binary files store data in the binary format (that is, in the form of 0’s and 1’s) which is understandable by
the machine. So when we open the binary file in our machine, it decodes the data and displays it in a
human-readable format. It is important to note that the binary file contents can be displayed correctly using
only specialized applications that can read binary data. If we open any binary file using a normal text
editor like a notepad, we may see strange characters.
Examples of binary files include files stored with the extension of .dat, .doc, .docx, .mp4, etc. As you may
relate now, these files can be opened correctly using specific applications only, that are different for each
file extension. Try opening any of these binary files using notepad, and observe the magic (file opens but
with unreadable contents). In this chapter of binary file handling, we'll learn to create such files (in their
simple forms), modify its contents and display its contents properly.

Binary File Modes:


File mode governs the type of operations (read/write/append) that is possible in the opened file. It refers to
how the file will be used once it's opened.

File Mode Description:


rb: Read Only: Opens existing file for read operation
wb: Write Only: Opens file for write operation. If the file does not exist, the file is created. If a file
exists, it overwrites data.
ab: Append: Opens file in write mode. If a file exists, data will be appended at the end.
rb+: Read and Write: File should exist, Both read and write operations can be
performed. wb+: Write and Read: File created if it does not exist, If file exists, file is
truncated.
ab+: Write and Read: File created if does not exist, If file exists data is truncated.

Writing data to a Binary File:


Pickle is a special python package (module) that is used to generate data in binary format. Pickle comes
with few methods like load() and dump( ) to read and write data in binary format.

Pickle Module: Python Pickle is used to serialize and deserialize a python object structure. Any object on
python can be pickled so that it can be saved on disk.

Pickling: Pickling is the process whereby a Python object hierarchy is converted into a byte stream.

Unpickling: A byte stream is converted into object


hierarchy.

To use the picking methods in a program, we have to import the pickle module using import keyword.

Example:
import pickle #don’t write pickel

In this module, we shall discuss two of its useful functions, which are:
i. dump( ) : To store/write the object data to the file.
ii. load( ) : To read the object data from a file and return the object data.

Syntax:
Write the object to the file:
pickle.dump(List_name, file-object ) #To write a list object into a binary file

Read the object from a file:


pickle.load(file-object)

Example:

import pickle
list =[ ] # empty list
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"roll":roll,"name":sname} # create a dictionary
list.append(student) # add dictionary as element in list
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
file = open("student.dat","wb")#open file in binary & write mode
pickle.dump(list, file) #imp: first data, then file handle
file.close( )

OUTPUT:
Enter student Roll No:1201
Enter student Name :Anil
Want to add more record(y/n)
:y Enter student Roll No:1202
Enter student Name :Sunil
Want to add more record(y/n)
:n

Read data from a Binary File:


To read the data from a binary file, we have to use the load( ) function of the pickle module.
Example:

import pickle
file = open("student.dat",
"rb") list = pickle.load(file)
print(list)
file.close( )

OUTPUT:
[{'roll': '1201', 'name': 'Anil'}, {'roll': '1202', 'name': 'Sunil'}]

To update a record in Binary File:


Locate the record to be updated by searching for it. Make changes in the loaded record in memory. Write
back onto the file at the exact location of the record.

import pickle
roll = input('Enter roll number whose name you want to update in binary file :')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = [ ]
for x in list:
if roll in x['roll']:
found = 1
x['name'] = input('Enter new name: ')
lst.append(x)
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Updated")
else:
print('roll number does not exist')
file.close( )
OUTPUT:
Enter roll number whose name you want to update in binary file :1202
Enter new name: Harish
Record Updated

Deleting a record from binary file:

import pickle
roll = input('Enter roll number whose record you want to delete:')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found = 1
if found ==
1:
file.seek(0)
pickle.dump(lst, file)
print("Record Deleted ")
else:
print('Roll Number does not exist')
file.close( )

OUTPUT:
Enter roll number whose record you want to delete:1201
Record Deleted

Searching a record in a binary file:


import pickle
roll = input('Enter roll number that you want to search in binary file :')
file = open("student.dat", "rb")
list = pickle.load(file)
file.close( )
for x in list:
if roll in x['roll']:
print("Name of student is:",
x['name']) break
else:
print("Record not found")

OUTPUT:
Enter roll number that you want to search in binary file :1202
Name of student is: Harish

tell( ) and seek( ) methods:

tell( ): It returns the current position of cursor in file.

Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
print(fout.tell( ))
fout.close( )

Output:
15

seek(offset, reference_point): Change the cursor position by bytes as specified by the offset, from the
reference point.
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
fout.seek(5)
print(fout.tell( ))
fout.close( )

Output:
5

1 Mark Questions

1. The process of converting byte stream back to the original structure is known as
a. Picklingb. b. Unpickling c. Packing d. Zipping

2. Which file mode is used to handle binary file for reading.


a. rb b. rw c. r d. w

3. Which of the following is not a correct statement for binary files?


a. Easy for carrying data into buffer b. Much faster than other file systems
c. Characters translation is not required d. Every line ends with new line character ‘\n’

4. Which one of the following is correct statement?


a. import – pickle b. pickle import c. import pickle d. All the above

5. Which of the following file mode opens a file for append or read a binary file and moves the files
pointer at the end of the file if the file already exist otherwise create a new file?
a. a b. ab c. ab+ d. a+

6. Which of the following file mode opens a file for reading and writing both as well as overwrite the
existing file if the file exists otherwise creates a new file?
a. w b. wb+ c. wb d. rwb
7. Mr Sharma is working on a binary file and wants to write data from a list to a binary file. Consider list
object as l1, binary file sharma_list.dat, and file object as f. Which of the following can be the correct
statement for him?
a. f = open(‘sum_list’,’wb’); pickle.dump(l1,f)
b. f = open(‘sum_list’,’rb’); l1=pickle.dump(f)
c. f = open(‘sum_list’,’wb’); pickle.load(l1,f)
d. f = open(‘sum_list’,’rb’); l1=pickle.load(f)

8. Every file has its own identity associated with it. This is known as:
a. icon b. extension c. format d. file type

9. EOL in a file stands for :


a. End of Lines b. End of Line c. End of List d. End of Location

10. Which of the following file types allows you to store large data files in the computer memory?
a. Binary Files b. Text Files c. CSV Files d. None of these

2 Marks Questions

1. Write a program in python to write and read structure, dictionary to the binary file.

2. BINARY file is unreadable and open and close through a function only so what are the advantages of
using binary file

3. Write a statement to open a binary file name sample.dat in read mode and the file sample.dat is placed in
a folder ( name school) existing in c drive.

4. When do you think text files should be preferred over binary files?

5. Consider a binary file employee.dat containing details such as empno:ename:salary (separator ':') write a
python function to display details of those employees who are earning between 20000 and 30000(both
values inclusive)
6. Differentiate between pickle.load() and pickle.dump() methods with suitable examples.

7. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].Write a user defined
function CreateFile() to input data for a record and add to Book.dat

8. A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write a function
countrec() in Python that would read contents of the file “STUDENT.DAT” and display the details of
those students whose percentage is above 75.

9. A binary file “Store.dat” has structure [ItemNo, Item_Name, Company, Price]. Write a function
CountRec(Company) in Python which accepts the Company name as parameter and count and return
number of Items by the given Company are stored in the binary file “Store.dat”.

10. A binary file “Store.dat” has structure [ItemNo, Item_Name, Company, Price]. Write a function
AddRecord() which accepts a List of the record [ItemNo, Item_Name, Company, Price] and appends in the
binary file “Store.Dat”.

3 Marks Questions

1. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].


i. Write a user defined function CreateFile() to input data for a record and add to “Book.dat” .
ii. 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 “Book.dat”

2. A binary file “SCHOOL.DAT” has structure [Roll_Num, Name, Percentage]


i) Write a function Count_Rec() in Python that would read contents of the file “SCHOOL.DAT” and
display the details of those students whose percentage is below 33.
ii) Write a function Disp_Rec(alphabet) in Python that would read contents of the file “SCHOOL.DAT”
and display the details of those students whose name begins with the alphabet as passed as parameter to
the function.

3. A binary file “STOCK.DAT” has structure [ITEMID, ITEMNAME, QUANTITY, PRICE]. Write a user
defined function MakeFile( )to input data for a record and add to Book.dat.

4. Write a function GetPrice(ITEMID) in Python which accepts the ITEMID as parameter and returns
PRICE of the Item stored in Binary file STOCK.DAT.
5. A binary file “EMPLOYEE.DAT” has structure (EMPID, EMPNAME, SALARY). Write a function
CountRec( ) in Python that would read contents of the file “EMPLOYEE.DAT” and display the details of
those Employees whose Salary is above 20000.

6. A binary file “EMPLOYEE.DAT” has structure (EMPID, EMPNAME, SALARY). Write a function to
display number of employees having Salary more than 20000.

7. A binary file named “EMP.dat” has some records of the structure [EmpNo, EName, Post, Salary], Write
a user-defined function named NewEmp() to input the details of a new employee from the user and store it
in EMP.dat.

8. Write a user-defined function named SumSalary(Post) that will accept an argument the post of
employees & read the contents of EMP.dat and calculate the SUM of salary of all employees of that Post.

9. A binary file named “TEST.dat” has some records of the structure [TestId, Subject, MaxMarks,
ScoredMarks] Write a function in Python named DisplayAvgMarks(Sub) that will accept a subject as an
argument and read the contents of TEST.dat.

10. Write a python program to search and display the record of the student from a binary file “Student.dat”
containing students records (Rollno, Name and Marks). Roll number of the student to be searched will be
entered by the user.

5 Marks Questions
1. A binary file “student.dat” has structure [rollno, name, marks].
i. Write a user defined function insertRec() to input data for a student and add to student.dat.
ii. Write a function searchRollNo(r) in Python which accepts the student’s rollno as parameter and
searches the record in the file “student.dat” and shows the details of student i.e. rollno, name and marks (if
found) otherwise shows the message as ‘No record found’.

2. Write a python program to create binary file dvd.dat and write 10 records in
it: Dvd id,dvd name,qty,price
Display those dvd details whose dvd price is more than 25.
CSV FILES
A CSV (Comma-Separated Values) file is a plain text file format used to store tabular data, where each
line represents a row, and each value within a row is separated by a comma or other delimiter.
A CSV file (Comma Separated Values file) is a type of plain text file that uses specific structuring to
arrange tabular data.,
CSV File operations in Python Files in the CSV format can be imported to and exported from programs
that store data in tables, such as Microsoft Excel or OpenOffice Calc. •
WHY USE CSV?
• The extensive use of social networking sites and their various associated applications requires
the handling of huge data.
But the problem arises as to how to handle and organize this large unstructured data?
• The solution to the above problem is CSV.
Thus, CSV organizes data into a structured form and, hence, the proper and systematic organization of this
large amount of data is done by CSV.
Since CSV file formats are of plain text format, it makes it very easy for website developers to create
applications that implement CSV.
• The several advantages that are offered by CSV files are as follows:
– CSV is faster to handle.
– CSV is smaller in size.
– CSV is easy to generate and import onto a spreadsheet or database.
– 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 stands for “comma separated values”.
Each line in a file is known as data/record. Each record consists of one or more fields, separated by
commas (also known as delimiters), i.e., each of the records is also a part of this file. Tabular data is stored
as text in a CSV file. The use of comma as a field separator is the source of the name for this file format. It
stores our data into a spreadsheet or a database.
CSV File operations in Python
• For working with CSV files in Python, there is an inbuilt module called
CSV. It is used to read and write tabular data in CSV format.
• To perform read and write operations with CSV file, we must import CSV module.
CSV module can handle CSV files correctly regardless of the operating system on which the files were
created.
• Along with this module, open() function is used to open a CSV file and return file object. We load
the module in the usual way using import:–
1) import csv
• Like other files (text and binary) in Python, there are two basic operations that can be carried out on
a CSV file:
– 1. Reading from a CSV file
– 2. Writing to a CSV file
2) Opening and closing of CSV File

# Open the CSV file in write mode


file = open('data.csv', 'w', newline='')
# Perform operations on the file, such as writing data
file.write("Name, Age, City\n")
file.write("Alice, 25, New York\n")
file.write("Bob, 30, San Francisco\n")

# Close the file to free up system resources


file.close()
•Reading from a CSV File

• Reading from a CSV file is done using the reader object.


The CSV file is opened as a text file with Python’s built-in open()function, which returns a file object.
This creates a special type of object to access the CSV file (reader object), using the reader()
function.
•The reader object is an iterable that gives us access to each line of the CSV file as a list of fields. We
can also use next() directly on it to read the next line of the CSV file, or we can treat it like a list in a for
loop to read all the lines of the file (as lists of the
file’s fields).
• Let us enter the student details in spreadsheet and save this file as shown.
• Next step is to open the Notepad and enter the data for student.csv, which will be the equivalent for

student.xls.
In student.csv (notepad) file, the first line is the header and remaining lines are the data/ records. The
fields are separated by comma. In general, the separator character is called a delimiter, and the comma is

not the only one used. Other popular delimiters include the tab (\t), colon (:) and semi-colon (;) characters.

Program to read the contents of “student.csv” file

Every record is stored in reader object in the form of a List. We first open the CSV file in READ mode.
The file object is named f. The file object is converted to csv.reader object. The reader object is used to
read records as lists from a csv file. Iterate through all the rows using a for loop. row is nothing but a list
containing all the field values

Writing to CSV FILE

STEPS:

1. import csv library.


2. Define a filename and Open the file using open().
3. Create a csvwriter object using csv.writer().
4. Write the header.
5. Write the rest of the data.
Writer Objects:
csvwriter.writerow(row)
Write the row parameter to the writer’s file object
csvwriter.writerows(rows)
Example code to demonstrate use of writer objects:
import csv
# Data to be written to the CSV file
data_single_row = ['Name', 'Age', 'Grade']
data_multiple_rows = [ ['Alice', 20, 'A'],['Bob', 22, 'B'] ['Charlie', 21, 'C']]
# Writing data using writerow()
with open('students.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(data_single_row) # Write a single row
writer.writerow(['David', 23, 'B']) # Write another single
row
# Writing data using writerows()
with open('students.csv', 'a', newline='') as file: # Use 'a' to append to the existing
file writer = csv.writer(file)
writer.writerows(data_multiple_rows) # Write multiple rows at once
 We first define the data to be written to the CSV file as a list of lists (data).
 Using writerow(), we write each row of data to the CSV file one by one.
 Then, using writerows(), we append additional rows of data to the CSV file at once.
PRACTICE QUESTIONS
MCQ
1. Which Python module is used to work with CSV files?
A) csv
B) pandas
C) json
D) os
2. What is the purpose of the csv.writer() object in Python?
A) To read data from a CSV file
B) To write data into a CSV file
C) To perform mathematical operations
D) To create directories
3. To open a CSV file for writing, which mode should you use in the open() function?
A) 'r'
B) 'w'
C) 'a'
D) 'rb'
4. Which method is used to write a single row into a CSV file using the csv.writer() object?
A) write()
B) writerows()
C) writerow()
D) row()
5. How do you close a CSV file after you finish working with it in Python?
A) close_file()
B) close()
C) end()
D) stop()
6. Which method is used to write multiple rows into a CSV file using the csv.writer() object?
A) write()
B) writerows()
C) writerow()
D) row()
7. What parameter should be used in the open() function to ensure correct newline handling
when working with CSV files?
A) newline='ignore'
B) newline=''
C) newline='skip'
D) newline=None
8. To read data from a CSV file in Python, which method of the csv.reader() object is used to
iterate through each row?
A) readline()
B) next()
C) readrows()
D) for loop
9. What does the newline='' parameter in the open() function ensure when working with CSV files?
A) It skips writing empty lines.
B) It converts newlines to spaces.
C) It ensures universal newline support.
D) It prevents reading blank rows.
10. Which of the following is NOT a valid mode for opening a CSV file in Python?
A) 'r' (read mode)
B) 'w' (write mode)
C) 'a' (append mode)
D) 'x' (exclusive creation mode)
11. What type of data format is a CSV file?
A) Binary
B) Text-based
C) Image
D) Executable
12. Which method is used to read the entire contents of a CSV file into a list of lists using
the csv.reader() object?
A) read()
B) readline()
C) next()
D) list()
13. When using the csv.writer() object, which method is used to write a list of data into a CSV
file as a single row?
A) write()
B) writerow()
C) writeall()
D) row()
14,In Python's CSV module, which of the following is true about delimiter characters?
A) The delimiter character cannot be customized.
B) The delimiter character must always be a comma.
C) The delimiter character separates values within a CSV file.
D) The delimiter character is used for comments.
15. How does the csv.writerows() method differ from the csv.writerow() method?
A) writerows() writes a single row, while writerow() writes multiple rows.
B) writerows() writes multiple rows at once, while writerow() writes one row at a time.
C) writerows() converts data to CSV format, while writerow() writes data as-is.
D) writerows() automatically adds headers, while writerow() does not.
16. Which of the following is a benefit of using the csv module in Python for CSV file operations?
A) It requires less memory compared to other modules.
B) It automatically converts CSV files to Excel format.
C) It provides advanced data visualization features.
D) It supports various data formats other than CSV.
17. What does the newline='' parameter in the open() function prevent when writing to CSV files?
A) It prevents empty lines from being written.
B) It prevents writing data as binary.
C) It prevents newlines from being converted to spaces.
D) It prevents duplicate rows from being written.
18. When using the csv.reader() object to read from a CSV file, what type of data structure is each
row of data represented as?
A) String
B) Dictionary
C) List
D) Tuple
19. How does the csv.DictReader() class differ from the csv.reader() class in Python?
A) DictReader() reads data as lists, while reader() reads data as dictionaries.
B) DictReader() reads data with column headers, while reader() does not.
C) DictReader() reads data as tuples, while reader() reads data as dictionaries.
D) DictReader() reads data as dictionaries, while reader() reads data as lists.
20. What is the purpose of using the newline='' parameter when opening a CSV file in Python?
A) To convert newlines to spaces.
B) To ensure cross-platform compatibility for newline characters.
C) To skip writing empty lines to the CSV file.
D) To automatically add headers to the CSV file.
2 marks questions
1. What is the purpose of using the csv module in Python?
2. Discuss the importance of newline handling when working with CSV files.
3. Differentiate between writerow() and writerows() methods in the csv.writer() object.
4. Describe the data format of a CSV file.
5. Explain the concept of a delimiter character in CSV files.
6. Write a Python code snippet to open a CSV file named "data.csv" in write mode and write a
single row of data into it using the csv.writer() object.Include the necessary import statement and
ensure proper closing of the file after writing.
7. Create a Python script that reads data from a CSV file named "input.csv" using the csv.reader()
object and prints each row of data to the console.Handle any exceptions that may occur during
file handling.
8. Write a Python program that generates a CSV file named "output.csv" and writes multiple rows
of data into it using the csv.writer() object.The data can be generated randomly or from
predefined lists.
9. Modify the previous code to append additional rows of data to the "output.csv" file using
the csv.writer() object.
10.Implement a Python function that takes a CSV file path as input and returns the total number of
rows in the CSV file using the csv.reader() object.
3 marks questions

1. write a Python program that performs the following tasks:


 Opens a CSV file named "inventory.csv" in read mode using the csv.reader() object.
 Iterates through each row in the CSV file.
 Checks if the quantity (second column) of each item is less than 10. If so, appends the
item's name (first column) to a list named low_stock_items.
 Finally, prints the list low_stock_items containing the names of items with low stock.
2. Fill in the blanks in the following code snippet to open a CSV file named "sales.csv" in read
mode using the csv.reader() object and calculate the total revenue by summing up the values in
the third column (Price) of each row.
import csv
total_revenue = 0 with open('sales.csv', 'r') as file:
reader = csv.reader(file) next(reader) # Skip header
row for row in reader:
total_revenue +=
print('Total revenue:', total_revenue)
3. Given the CSV file "employees.csv":
Name,Department,Salary Alice,HR,50000 Bob,Engineering,60000 Charlie,Sales,45000
Identify and correct any errors in the following Python code snippet, then determine the output of the
corrected code:
import csv
total_salary = 0
with open('employees.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
total_salary += row[2] print('Total
salary:', total_salary)
4. Write a Python program that opens a CSV file named "students.csv" in write mode using the
csv.writer() object. The program should prompt the user to enter student names and their
respective grades, and then write this data into the CSV file. Ensure appropriate error handling for
incorrect input.
5. Explain the concept of delimiter characters in CSV files and discuss their significance when
working with the csv module in Python. Provide examples of different delimiter characters
and explain how they affect the organization and interpretation of data within a CSV file.
6. Write a Python program that reads data from a CSV file named "data.csv" using the csv.reader()
object. For each row, if the value in the second column (index 1) is greater than 50, write that
row into a new CSV file named "high_scores.csv" using the csv.writer() object.
7. Fill in the blanks in the following code snippet to open a CSV file named "output.csv" in
append mode and add a new row containing the student's name, age, and grade using the
csv.writer() object.
import csv
student_data = ['Alice', 25, 'A']
with open('output.csv', 'a', newline='') as
file: writer = csv.writer( )
writer. (student_data)
Output and Error Handling:
8. Given the following CSV file named "inventory.csv":
What will be the output of the following Python program? If there is any error, identify and correct it.
total_cost = 0
with open('inventory.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
quantity = int(row[1])
price = float(row[2])
total_cost += quantity * price
print('Total inventory cost:', total_cost)
9. Write a Python program that reads data from a CSV file named "students.csv" using the
csv.reader() object. Create a dictionary where the keys are the student names and the values are
lists containing their age and grade. Print the dictionary.
10. Fill in the blanks in the following code snippet to read data from a CSV file named
"sales.csv" using the csv.reader() object and calculate the total sales amount. Print the total
sales amount.
import csv
total_sales = 0
with open('sales.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
sales_amount = float( [2])
total_sales += sales_amount
print('Total sales amount:', total_sales)
5 mark questions

1. Write a Python program that reads data from a CSV file named "inventory.csv" using the
csv.DictReader() class. The CSV file contains columns for "Product", "Quantity", and "Price".
Your program should calculate the total value of each product in inventory (quantity * price)
and print a summary report showing each product's name and total value.
2. Identify and correct the error in the following Python code that attempts to open a CSV file
named "data.csv" for writing using the csv.writer() object.
import csv
data = [['Name', 'Age', 'City'], ['Alice', 25, 'New York'], ['Bob', 30, 'San Francisco']]
with open('data.csv', 'r') as file:
writer = csv.writer(file) writer.writerows(data)
3. Fill in the blanks in the following code snippet to open a CSV file named "output.csv" in write
mode and write multiple rows of data into it using the csv.writer() object. The data to be
written includes product information (name, quantity, price) stored in a list of dictionaries.
import csv
product_data = [ {'Name': 'Laptop', 'Quantity': 10, 'Price': 1200}, {'Name': 'Mouse', 'Quantity': 50, 'Price':
20}, {'Name': 'Keyboard', 'Quantity': 20, 'Price': 50} ]
with open('output.csv', 'w', newline='') as file:
fieldnames = ['Name', 'Quantity', 'Price']
writer = csv.DictWriter(file, fieldnames=

) writer.writeheader()
writer.writerows( )
4. Write a Python program that reads data from a CSV file named "sales.csv" using the csv.reader()
object. The CSV file contains columns for "Date", "Product", and "Revenue". Your program
should calculate and print the total revenue earned for each product across all dates.
5. Write a Python program that reads data from two CSV files, "sales.csv" and "inventory.csv",
using appropriate methods like csv.reader() or csv.DictReader().
The "sales.csv" file contains columns for "Date", "Product", and "Revenue", while the
"inventory.csv" file contains columns for "Product" and "Quantity". Your program should combine
these datasets to create a new CSV file named "combined_data.csv" that includes the columns
"Date", "Product", "Revenue", and "Available Quantity". Ensure to handle missing or mismatched
data appropriately.
Case study based questions-4 marks each
1. Imagine you work for a retail company that stores its daily sales data in a CSV file named
"sales_data.csv". Develop a Python script using the csv module to read this file and generate a
daily sales report. The report should include total sales revenue, the number of items sold, and a
breakdown of sales by product category.
2. You are managing a student gradebook for a school, and the grade data is stored in a CSV file
named "gradebook.csv". Design a Python program using the csv module to read and update
student grades. Implement functionalities such as adding new grades, calculating average grades
for each subject, and generating individual progress reports.
3. In a warehouse setting, you have an inventory CSV file named "inventory.csv" containing product
details like name, quantity, and reorder level. Create a Python application using the csv module to
track inventory levels, identify low-stock items (below reorder level), and generate a restocking
list with recommended quantities.
4. A company receives customer feedback through an online survey, and the feedback data is stored
in a CSV file named "feedback_data.csv". Develop a Python script using the csv module to read
and analyze the feedback. Implement sentiment analysis to categorize feedback as positive, neutral,
or negative and generate a summary report highlighting key customer sentiments.

5. You are responsible for managing personal finances and have a CSV file named "expenses.csv"
containing daily expense records. Build a Python application using the csv module to read and
analyze the expense data. Implement functionalities such as calculating total expenses,
categorizing expenses (e.g., food, transportation), and generating a budget overview with spending
trends.

ANSWERS
1.A) csv
2.B) To write data into a CSV file
3.B) 'w'
4. C) writerow()
5. B) close()
6. B) writerows()
7. D) newline=None
8. D) for loop
9. C) It ensures universal newline support.
10. D) 'x' (exclusive creation mode)
11. B) Text-based
12. D) list()
13. B) writerow()
14. C) The delimiter character separates values within a CSV file.
15. B) writerows() writes multiple rows at once, while writerow() writes one row at a time.
16. A) It requires less memory compared to other modules.
17. A) It prevents empty lines from being written.
18. C) List
19. D) DictReader() reads data as dictionaries, while reader() reads data as lists.
20. B) To ensure cross-platform compatibility for newline
characters. 2 marks questions
1. The csv module in Python is used to work with CSV (Comma Separated Values) files. It provides
functions to read, write, and manipulate data in CSV format, making it easier to handle tabular
data. 2.
Newline handling is crucial when working with CSV files because different operating systems use
different newline characters (such as '\n' for Unix/Linux and '\r\n' for Windows). If newline
handling is not done correctly, it can lead to issues like extra blank lines or improper row parsing.
Using newline='' in the open() function ensures universal newline support, preventing such
issues. 3.
 writerow(): Writes a single row of data into the CSV file.
 writerows(): Writes multiple rows of data into the CSV file. It takes an iterable of rows (e.g., a
list of lists) and writes each row as a separate line in the CSV file.
4.
A CSV file is a text-based file format used to store tabular data. Each line in a CSV file represents a
row, and values within each row are separated by a delimiter character, commonly a comma (','),
although other characters like tabs or semicolons can also be used.
5.
The delimiter character is used to separate values within a CSV file. It signifies where one value
ends and the next one begins within a row. Common delimiter characters include commas (','), tabs
('\t'), semicolons (';'), and pipes ('|'). The choice of delimiter depends on the data and the
requirements of the CSV file.
6.
import csv
data = ['Name', 'Age', 'City']
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(data)
7.
import csv
try:
with open('input.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Error:", e)
8.
import csv
import random
data = [['Name', 'Age', 'City'],
['Alice', 25, 'New York'],
['Bob', 30, 'San Francisco'],
['Charlie', 28, 'Los Angeles']]
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
9
import csv
new_data = [['David', 35, 'Chicago'],
['Emma', 29, 'Houston']]
with open('output.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerows(new_data)
10.
import csv
def count_rows(csv_file):
try:
with open(csv_file, 'r') as file:
reader = csv.reader(file)
row_count = sum(1 for row in reader)
return row_count
except FileNotFoundError:
return 0
except Exception as e:
print("Error:", e)
return 0
file_path = 'data.csv'
total_rows = count_rows(file_path)
print("Total rows in", file_path, ":",
total_rows) import csv

low_stock_items = []
with open('inventory.csv', 'r') as
file: reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
if int(row[1]) < 10: # Assuming quantity is in the second column
low_stock_items.append(row[0]) # Assuming item name is in the first column
print("Low stock items:", low_stock_items)
3 MARKS QUESTIONS ANSWERS
1.
import csv
low_stock_items = []
with open('inventory.csv', 'r') as
file: reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
if int(row[1]) < 10: # Assuming quantity is in the second column
low_stock_items.append(row[0]) # Assuming item name is in the first column
print("Low stock items:", low_stock_items)
2.
import csv
total_revenue = 0
with open('sales.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
total_revenue += float(row[2]) # Assuming Price is in the third column
print('Total revenue:', total_revenue)
3.
import csv
total_salary = 0
with open('employees.csv', 'r') as
file: reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
total_salary += int(row[2]) # Assuming Salary is in the third
column print('Total salary:', total_salary)
4.
import csv
def write_student_data(file_name):
try:
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Grade']) # Write header row
while True:
name = input("Enter student name (or type 'exit' to quit): ")
if name.lower() == 'exit':
break
grade = input("Enter student grade: ")
writer.writerow([name, grade])
except Exception as e:
print("Error:", e)
write_student_data('students.csv')
5.
Delimiter characters in CSV files are used to separate individual fields (data values) within a row.
The most common delimiter character is a comma (,), but other characters like tabs (\t), semicolons
(;), and pipes (|) can also be used.
The significance of delimiter characters when working with the csv module in Python is that they
determine how data is organized and interpreted within a CSV file. When reading a CSV file,
Python uses the specified delimiter character to split each row into individual fields, making it
possible to access and process the data accordingly. Similarly, when writing data to a CSV file, the
delimiter character is used to separate different values within each row. Using the correct delimiter
ensures that the data is correctly formatted and can be read or written without errors.
6.
import csv
# Define the input and output file names
input_file = 'data.csv'
output_file = 'high_scores.csv'
# Open the input and output CSV files
with open(input_file, 'r') as file:
reader = csv.reader(file)
with open(output_file, 'w', newline='') as output_file:
writer = csv.writer(output_file # Write header row to the output
file header = next(reader)
writer.writerow(header)
# Iterate through each row in the input file
for row in reader:
# Check if the value in the second column is greater than 50
if int(row[1]) > 50: # Assuming the second column contains integers
writer.writerow(row)
7. import csv
student_data = ['Alice', 25, 'A']
with open('output.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(student_data)

8. Correct code:
import csv
student_data = ['Alice', 25, 'A']
with open('output.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(student_data)

output:
Total inventory cost: 500.0

9.
import csv
student_dict = {}
with open('students.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
name, age, grade = row
student_dict[name] = [int(age), grade]
print(student_dict)
10.

import csv
total_sales = 0
with open('sales.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
sales_amount = float(row[2]) # Assuming sales amount is in the third column
total_sales += sales_amount
print('Total sales amount:', total_sales)
5 MARKS QUESTIONS ANSWERS

1. import csv
product_values =
{}
with open('inventory.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
product = row['Product']
quantity = int(row['Quantity'])
price = float(row['Price'])
total_value = quantity * price
if product in product_values:
product_values[product] +=
total_value else:
product_values[product] = total_value
print("Summary Report - Total Value of Each Product:")
for product, total_value in product_values.items():
print(f"{product}: ${total_value:.2f}")
2.
import csv
data = [['Name', 'Age', 'City'], ['Alice', 25, 'New York'], ['Bob', 30, 'San Francisco']]
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
3
import csv
product_data = [
{'Name': 'Laptop', 'Quantity': 10, 'Price': 1200},
{'Name': 'Mouse', 'Quantity': 50, 'Price': 20},
{'Name': 'Keyboard', 'Quantity': 20, 'Price': 50}
]
fieldnames = ['Name', 'Quantity', 'Price']
with open('output.csv', 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(product_data)
4.
import csv
product_revenue = {}
with open('sales.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
product = row[1] # Assuming Product is in the second column
revenue = float(row[2]) # Assuming Revenue is in the third column
if product in product_revenue:
product_revenue[product] += revenue
else:
product_revenue[product] = revenue
print("Total Revenue Earned for Each Product:")
for product, total_revenue in product_revenue.items():
print(f"{product}: ${total_revenue:.2f}")
5.
import csv
# Read data from sales.csv
sales_data = {}
with open('sales.csv', 'r') as
sales_file: reader =
csv.DictReader(sales_file) for row
in reader:
date = row['Date']
product = row['Product']
revenue = float(row['Revenue'])
if product not in sales_data:
sales_data[product] = {'Date': date, 'Revenue': revenue}
else:
sales_data[product]['Revenue'] += revenue
# Read data from inventory.csv
inventory_data = {}
with open('inventory.csv', 'r') as inventory_file:
reader = csv.DictReader(inventory_file)
for row in reader:
product = row['Product']
quantity = int(row['Quantity'])
inventory_data[product] = quantity

# Combine datasets and write to combined_data.csv


fieldnames = ['Date', 'Product', 'Revenue', 'Available
Quantity']
with open('combined_data.csv', 'w', newline='') as combined_file:
writer = csv.DictWriter(combined_file, fieldnames=fieldnames)
writer.writeheader()
for product, data in
sales_data.items(): if product in
inventory_data:
data['Available Quantity'] = inventory_data[product]
writer.writerow(data)
4 marks questions
1,
import csv
def generate_sales_report(csv_file):
total_revenue = 0
total_items_sold = 0
sales_by_category = {}
with open(csv_file, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
revenue = float(row['Revenue'])
total_revenue += revenue
items_sold = int(row['Items Sold'])
total_items_sold += items_sold
category = row['Product Category']
if category in sales_by_category:
sales_by_category[category] += revenue
else:
sales_by_category[category] = revenue
print("Daily Sales Report:")
print(f"Total Revenue: ${total_revenue:.2f}")
print(f"Total Items Sold:
{total_items_sold}") print("Sales by
Category:")
for category, revenue in
sales_by_category.items(): print(f"{category}:
${revenue:.2f}")
generate_sales_report('sales_data.csv')
2.
import csv
def update_student_grades(csv_file, student_name, subject, grade):
# Read existing grades
grades = {}
with open(csv_file, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
name = row['Name']
if name not in
grades:
grades[name] = {} grades[name]
[row['Subject']] = float(row['Grade'])
# Update or add new grade
if student_name in grades:
grades[student_name][subject] = grade
else:
grades[student_name] = {subject: grade}
# Write updated grades to file
fieldnames = ['Name', 'Subject', 'Grade']
with open(csv_file, 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
for name, subjects in grades.items():
for subject, grade in
subjects.items():
writer.writerow({'Name': name, 'Subject': subject, 'Grade': grade})
def calculate_average_grade(csv_file, subject):
total_grade = 0
total_students = 0
with open(csv_file, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
if row['Subject'] == subject:
total_grade += float(row['Grade'])
total_students += 1
if total_students > 0:
average_grade = total_grade / total_students
print(f"Average Grade in {subject}: {average_grade:.2f}")
else:
print("No data for this subject.")
def generate_progress_report(csv_file, student_name):
with open(csv_file, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
if row['Name'] == student_name:
print(f"Progress Report for
{student_name}:") for subject, grade in
row.items():
if subject != 'Name':
print(f"{subject}: {grade}")
# Example usage:
update_student_grades('gradebook.csv', 'Alice', 'Math', 85)
calculate_average_grade('gradebook.csv', 'Math')
generate_progress_report('gradebook.csv', 'Alice')
3.
import csv
def track_inventory(csv_file, reorder_level):
low_stock_items = []
restocking_list = {}
with open(csv_file, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
name = row['Name']
quantity =
int(row['Quantity']) if
quantity < reorder_level:
low_stock_items.append(name)
restocking_list[name] = reorder_level - quantity

print("Low Stock Items:")


for item in
low_stock_items:
print(item)
print("Restocking List:")
for item, quantity in restocking_list.items():
print(f"{item}: {quantity}")
# Example usage:
track_inventory('inventory.csv',
10)
4.
import csv
from textblob import TextBlob
def
categorize_feedback(csv_file):
positive_feedback = []
neutral_feedback = []
negative_feedback = []
with open(csv_file, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
feedback = row['Feedback']
analysis =
TextBlob(feedback)
if analysis.sentiment.polarity > 0:
positive_feedback.append(feedback)
elif analysis.sentiment.polarity == 0:
neutral_feedback.append(feedback)
else:
negative_feedback.append(feedback)
print("Feedback Analysis Summary:")
print(f"Positive Feedback
({len(positive_feedback)}):") for feedback in
positive_feedback:
print(feedback)
print(f"Neutral Feedback ({len(neutral_feedback)}):")
for feedback in neutral_feedback:
print(feedback)

print(f"Negative Feedback ({len(negative_feedback)}):")


for feedback in negative_feedback:
print(feedback)
# Example usage:
categorize_feedback('feedback_data.csv')
5.
import csv
def analyze_expenses(csv_file):
total_expenses = 0
expense_categories = {}
with open(csv_file, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
amount = float(row['Amount'])
total_expenses += amount
category = row['Category']
if category in expense_categories:
expense_categories[category] += amount
else:
expense_categories[category] = amount
print("Expense Analysis:")
print(f"Total Expenses: “,${total_exp})

DATA STRUCTURE – STACK


Data Structure: A data structure is a group of data which can be processed as a single unit. This group of
data may be of similar or dissimilar data types. Data Structures are very useful while programming
because they allow processing of the entire group of data as a single Unit.
Types of data structures:
Linear data structures: The elements are stored in a sequential order.
Example: Array, Stack, Queue.
Non-Linear data structures: The elements are not stored in sequential order.
Example: Graph, Tree, linked lists.
Stack: It is a data structure that allows adding and removing elements in a particular order. Every time
an element is added, it goes on the top of the stack; the only element that can be removed is the element
that was at the top of the stack.
Two Characteristics of Stacks: It is a LIFO (Last-In First-Out) data structure, The insertion and
deletion happens at one end i.e. from the top of the stack.
Operations possible in the data structure: Major operations are Traversal, Insertion, Deletion
and Searching.
Major operations on Stack:

1. PUSH: The addition of elements is known as PUSH operation. It is done using the TOP position.
2. POP: Removal of elements is known as POP operation. Removal of object is always done from
TOP position.
3. PEEK: To show/ display the element placed at TOP position in the stack. Few applications of stack:
1. Expression evaluation
2. Backtracking (game playing, finding paths, exhaustive searching).
3. Memory management, run-time environment for nested language features.Stack implementation
using List:
1. PUSH: The addition of elements is known as PUSH operation. It is done on the TOP
position. S= [ ‘element1’, ‘element2’, ‘element3’, ‘element4’]
S.append(‘newElement’) # pushing element in stack at the TOP
S= [ ‘element1’, ‘element2’, ‘element3’, ‘element4’, ‘newElement’] #List after insertion
2. POP: Removal of elements is known as POP operation. It is also done using the TOP
position. S= [ ‘element1’, ‘element2’, ‘element3’, ‘element4’, ‘newElement’]
S.pop() # removes element at top
S= [ ‘element1’, ‘element2’, ‘element3’, ‘element4’] #List after deletion
3. PEEK: To show/ display the element placed at TOP position in the
stack. return S[-1] # shows element at top but do not remove it from the
stack.

Questions
Consider
1. a list named Nums which contains random integers.

Write the following user defined functions in Python and perform the specified
operations on a stack named BigNums.
(i) PushBig(): It checks every number from the list Nums and pushes all
such numbers which have 5 or more digits into the stack, BigNums.
(ii) PopBig(): It pops the numbers from the stack, BigNums and displays
them. The function should also display “Stack Empty” when there are
no more numbers left in the stack.
For example: If the list Nums contains the following data:
Nums=[213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]
Then on execution of PushBig(),the stack BigNums should store:
[10025, 254923, 1297653, 31498, 92765]
And on execution of PopBig(), the following output should be displayed:
92765
31498
1297653
254923
10025
Stack Empty
def PushBig(Nums,BigNums):
ANS for N in Nums:
if len(str(N))>=5:
BigNums.append(N)
def PopBig(BigNums):
while BigNums:
print(BigNums.pop())
else:
print(“Stack Empty”)
2. 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.
(i) 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.
(ii) 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.
For example: If the nested list contains the following data:
NList=[["New York", "U.S.A.", 11734],
["Naypyidaw", "Myanmar", 3219],
["Dubai", "UAE", 2194],
["London", "England", 6693],
["Gangtok", "India", 1580],
["Columbo", "Sri Lanka", 3405]]
The stack should contain:
['Naypyidaw', 'Myanmar'],
['Dubai', 'UAE'],
['Columbo', 'Sri
Lanka'] The output
should be: ['Columbo',
'Sri Lanka']
['Dubai', 'UAE']
['Naypyidaw', 'Myanmar']
Stack Empty
ANS

3. (a) A list contains the following record of customer:


[Customer_name, Room Type]
Write the following user-defined functions to perform given operations on the stack
named ' Hotel':
i) Push_Cust () - To Push customers names of those customers who are staying in
Delux' Room Type.
ii) Pop_Cust ()- To Pop the names of customers from the stack and display them.
Also, display "Underflow" when there are no customers in the stack.
For example: If the lists with customer details are as follows:
["siddarth", "Delux"] ["Rahul", "Standard"] ["Jerry", "Delux"]
The stack should contain
Jerry
Siddharth
The output should be:
Jerry
Siddharth
Underflow

b) Write a function in Python, Push (Vehicle) where, Vehicle is a dictionary


containing details of vehicles - {Car_Name: Maker}.
The function should push the name of car manufactured by "TATA' (including
all the possible cases like Tata, TaTa, etc.) to the stack.
For example:
If the dictionary contains the following data:
Vehicle={"Santro" : "Hyundai", "Nexon": "TATA", "Safari" : "Tata"}
The stack should contain
Safari
Nexon
a) customer=[["Siddarth", "Delux"], ["Rahul", "Standard"], ["Jerry", "Delux"]]
ANS hotel=[]
def push_cust():
for i in customer:
if i[1]=='Delux':
hotel.append(i[0])
return hotel

def pop_cust():
if hotel==[]:
return "Underflow"
else:
return hotel.pop()

push_cust()
while True:
if hotel==[]:
print(pop_cust())
break
else:
print(pop_cust())

b) Vehicle={"Santro" : "Hyundai", "Nexon": "TATA", "Safari" :


"Tata"} stk=[]
def push(vehicle):
for i in vehicle:
if vehicle[i].lower()=='tata':
stk.append(i)
return stk

push(Vehicle)
for i in range(-1,-len(stk)-1,-1):
print(stk[i])

4. A list contains following record of a customer:


[Customer_name, Phone_number, City]

Write the following user defined functions to perform given operations


on the stack named ‘status’:
(i) Push_element() - To Push an object containing name and
Phone number of customers who live in Goa to the stack
(ii) Pop_element() - To Pop the objects from the stack and
display them. Also, display “Stack Empty” when there are
no elements in the stack.

For example:
If the lists of customer details are:

[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777”,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”]
The stack should contain
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]

The output should be:


[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]
Stack Empty
ANS status=[]
def Push_element(cust):
if cust[2]=="Goa":
L1=[cust[0],cust[1]]
status.append(L1)

def Pop_element ():


num=len(status)
while len(status)!=0:
dele=status.pop()
print(dele)
num=num-1
else:
print("Stack Empty")
5. Write a function in Python, Push(SItem) where , SItem is a dictionary
containing the details of stationary items– {Sname:price}.
The function should push the names of those items in the stack who
have price greater than 75. Also display the count of elements pushed
into the stack.
For example:
If the dictionary contains the following data:
Ditem={"Pen":106,"Pencil":59,"Notebook":80,"Eraser":25}

The stack should contain


Notebook
Pen

The output should be:


The count of elements in the stack is 2
ANS stackItem=[]
def Push(SItem):
count=0
for k in SItem:
if (SItem[k]>=75):
stackItem.append(k)
count=count+1
print("The count of elements in the stack is : ", count)
6. 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
ANS R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[]
for k in R:
if R[k]>=75:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
7. Alam 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
ANS N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[]
for k in N:
if k%2==0:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
Unit : 2 introduction to Computer Networks
Network:-
The collection of interconnected computing devices is called a network. Two computing
devices are said to be interconnected if they are capable of sharing and exchanging
information.

Benefits of Network: -
(1) Resource Sharing: Resource Sharing means to make the
applications/programs, data(files) and peripherals available to anyone on the
network irrespective of the physical location of the resources and the user.
(2) Reliability: Reliability means to keep the copy of a file on two or more different
machines, so if one of them is unavailable (due to some hardware crash or any
other) them its other copy can be used.
(3) Cost Factor: Cost factor means it greatly reduces the cost since the resources can
be shared. For example a Printer or a Scanner can be shared among many
computers in an office/Lab.
(4) Communication Medium: Communication Medium means one can send
and receive messages. Whatever the changes at one end are done, can be
immediately noticed at another.
EVOLUTION OF NETWORKING
ARPANET (1969) – US Government formed an agency named ARPANET( Advanced
Research Project Agency Network) to connect computers at various universities and defence
agencies to share data/information efficiently among all of them.
NSFNET (1985) - National Science Foundation Network was a program of coordinated,
evolving projects sponsored by the National Science Foundation (NSF) from 1985 to 1995 to
promote advanced research and education networking in the United States. The program
created several nationwide backbone computer networks in support of these initiatives.
Initially created to link researchers to the NSF-funded supercomputing centers, through
further public funding and private industry partnerships it developed into a major part of
the Internet backbone.
INTERNET (1990)- INTER-connection NETwork , The worldwide network of networks.
Data communication terminologies:
Concept of communication: Communication is the act of sending and receiving data from
one device to another device or vice-versa. Data can be of any form i.e. text, image, audio,
video and multimedia files.
Components of Data communication:
Sender: A device that can send data over a network i.e. computer, laptop, smart phone
etc. Receiver: A device can receive data over a network i.e. computer, laptop, smart
phone etc. The sender and receivers are basically called nodes.
Message: It is the data/information that needs to be shared between the sender and
receiver.
Communication media: It is the medium through which the data/information is travelled
between the
sender and receiver. These may be wired or wireless.
Protocols: A network protocol is an established set of rules that determine how data is
transmitted between different devices in the same network. Essentially, it allows connected
devices to communicate with each other, regardless of any differencesin their internal
processes, structure or design.
Measuring Capacity of Communication Media: In data communication, the transmission
medium is also known as channel. The capacity of a channel is the maximum amount of
signals or traffic that a channel can carry. It is measured in terms of bandwidth and data
transfer rate as described below:
Bandwidth
Bandwidth of a channel is the range of frequencies available for transmission of data
through that channel.
Higher the bandwidth, higher the data transfer rate.
Normally, bandwidth is the difference of maximum and minimum frequency contained in the
composite signals.
Bandwidth is measured in Hertz (Hz). 1
KHz = 1000 Hz, 1 MHz =1000
Data Transfer Rate
Data travels in the form of signals over a channel. One signal carries one or more bits over
the channel. Data transfer rate is the number of bits transmitted between source and
destination in one second. It is also known as bit rate. It is measured in terms of bits per
second (bps). The higher units for data transfer rates are:
1 Kbps=1024 bps
1 Mbps=1024 Kbps
1 Gbps=1024 Mbps
IP Address:
An IP address is a unique address that identifies a device on the internet or a local network.
IP stands for "Internet Protocol," which is the set of rules governing the format of data sent
via the internet or local network.
Switching techniques:
In large networks, there may be more than one path for transmitting data from sender to
receiver. Selecting a path that data must take out of the available options is called switching.
There are two popular switching techniques – circuit switching and packet switching.
Circuit switching: Circuit switching is a type of network configuration in which a physical
path is obtained and dedicated to a single connection between two endpoints in the network
for the duration of a dedicated connection. Ordinary landline telephone service uses
circuit switching.
Packet switching: Packet switching is the method by which the internet works; it features
delivery of packets of data between devices over a shared network. For example the school
web server is sending you a webpage over the internet or you sending an email to a friend.
Transmission Media: Transmission media is a communication channel that carries the
information from the sender to the receiver. All the computers or communicating devices in
the network must be connected to each other by a Transmission Media or channel.
 A Transmission medium is a medium of data transfer over a network.
 The selection of Media depends on the cost, data transfer speed, bandwidth and
distance. Transmission media may be classified as

Transmission Media: Guided (Wired)


Twisted Pair Cable: Twisted pair or Ethernet cable is most common type of media which
consists four insulated pairs of wires twisted around each other. It is low-cost, low-weight
and easy to install flexible cables. It can transfer data up to 1Gbps speed covering 100 meters
distance. It uses RJ-45 Connector for connecting computers and network devices. Co-axial
Cable: This type of cable consists a solid insulated wire surrounded by wire mesh, each
separated by some kind of foil or insulator. The inner core carries the signal and mesh
provides the ground. Co-axial Cable or Coax, is most common in Cable TV transmission. It
can carry data up to 500 meters.
Fiber Optic Cable: Optical fiber consists of thin glass or glass like material and carries light
signals instead of electric current. Signal are modulated and transmitted in the form of light
pulses from source using Light Emitting Diode (LED) or LASER beam. Optical fibers offer
secure and high-speed transmission up to a long distance.
Transmission Media: Unguided (Wireless)
Infrared Wave: It used for short-range (approx. 5 meters) communication using
wireless signals. It is mostly used in Remote operated devices like TV, Toys, Cordless
phones etc. Radio waves: Radio wave uses Radio frequencies (3KHz-3 GHz) to
make broadcast network like AM/FM network within city. Radio wave propagates
in Omni direction (surrounding) and penetrate solid walls/buildings.
Microwaves: Microwave are high energy radio waves, used for line of sight communication
using Parabolic antenna aligned with each other. It is high speed wave and can cover
distance up to 100 km).
Network Devices: Hardware device that are used to connect computers, printers, fax
machines and other electronic devices to a network are called network device. There are
many types of network devices used in networking and some of them are described below:
MODEM (Modulator Demodulator): It is a device that converts digital signal to analog
signal (modulator) at the sender’s site and converts back analog signal to digital signal
(demodulator) at the receiver’s end, in order to make communication possible via telephone
lines. It enables a computer to transmit data over telephone or cable lines.
There are two types of MODEM, which are as follows
(i) Internal Modem Fixed within a computer.
(ii) External Modem Connected externally to a computer.
Ethernet card: An Ethernet card in your computer serves one basic function: to transmit
data from the network to your computer. Ethernet cards are physical expansion cards that
insert into a PCI expansion slot on a computer.
RJ45: RJ45 connectors are commonly seen with Ethernet network cables. Ethernet cables
with RJ45 connectors are also called RJ45 cables. These RJ45 cables feature a small plastic
plug on each end, and the plugs are inserted into RJ45 jacks of Ethernet devices.
Hub: A Hub is a connecting device which connects multiple computers together to form a
Local Area Network (LAN). Hubs make broadcast type Network and do not manage traffic
over the network channel. Signal entering any port is broadcast out on all other ports. It
broadcast the signals to all computers connected in the network. It provides various RJ-45
ports to connect Twisted Pair cable in STAR topology, making them act as a single network
segment. Now days, Switch is used in place of Hubs.
Types of Hub:
 Active Hub: Amplifies the signal when required and works as a Repeater.
 Passive Hub: It simply passes the signal without any change.
Switch: A switch is a hardware device, which is used to connect several nodes to form a
Network. It redirects the received signals only to the intended Node i.e. controls Network
traffic.It is also used to segment a big network into different Sub networks (Subnet) to
control the network traffic and security. It can also use to combine various small network
segments to form a big Network (as in Tree topology).
Hub V/s Switch: There is a vast difference between switch and hub. A hub forwards each
incoming packet (data) to all the hub ports, while a switch forwards each incoming packet to
the specified recipient.
Repeater: Repeater is a hardware device, which is used to amplify the signals when they are
transported over a long distance. The basic function of a repeater is to amplify the incoming
signal and retransmit it, to the other device.
Router: A router is used to connect different networks together. i.e. for two or more LANs to
be interconnected, you need a router
 The basic role of Routers in a network is to determine the best possible route
(shortest path) for the data packets to be transmitted. In a large network (WAN),
multiple routers works to facilitate speedy delivery of data packets.
 Router maintains a table of addresses (called routing table) that keeps a track of
paths connected to it.
Gateway:
 A gateway is a device, which is used to connect dissimilar networks. The gateway
establishes an intelligent connection between a local network and external
networks, which are completely different in structure.
 Gateway is also called protocol converter that convert data packets from one protocol to
other and connects two dissimilar networks.
 A gateway can be implemented in hardware, software or both, but they are usually
implemented by software installed within a router.
 A LAN gets connected to Internet (WAN) using a gateway.
Network Topologies:
Topology: Topology refers to the way in which the
device/computer/workstations attached to the network
are interconnected.
The layout of interconnection of devices in a network is
called Topology.
Different Topologies are: Star, Bus, Tree, Mesh.
BUS Topology: - The bus topology uses a common
single cable (backbone cable) to connect all the workstations. Each computer performs its
task of sending messages without the help of the central server. However, only one
workstation can transmit a message at a particular time in the bus topology.
Advantages:
(i) Easy to connect and install.
(ii) Involves a low cost of installation time.
(iii) Can be easily extended.
Disadvantages:-
(i) The entire network shuts down if there is a failure in the central cable.
(ii) Only a single message can travel at a particular time.
(iii) Difficult to troubleshoot an error.

STAR Topology: -In Star topology, each node is directly connected to a central device like Hub or
Switch. It is most popular topology to form Local Area Networks (LAN).
Advantages:
(i) Easy to troubleshoot
(ii) A single node failure does not affects the entire network.
(iii) Fault detection and removal of faulty parts is easier.
(iv) In case a workstation fails, the network is not affected.
Disadvantages: -
(i) Difficult to expand.
(ii) Longer cable is required.
(iii) The cost of the hub and the longer cables makes it
expensive over others.
(iv) All nodes are dependent on central node. if the central device (Switch) goes
down then entire network breaks down.

TREE Topology: - The tree topology combines the characteristics of the linear bus and the star
topologies. It consists of groups of star – configured workstations connected to a bus
backbone cable.
Advantages:
(i) Eliminates network congestion.
(ii) The network can be easily extended.
(iii) Faulty nodes can easily be isolated from the rest of the
network.
Disadvantages:
 Uses large cable length.
 Requires a large amount of hardware components and
hence is expensive.
 Installation and reconfiguration are very difficult.
Types of Computer Network:
A computer network may be small or big as per number of computers and other network devices
linked together. A computer network may contain devices ranging from handheld devices
(like mobile phones, tablets, laptops) connected through Wi-Fi or Bluetooth within a single
room to the millions of computers spread across the globe. Based on the size, coverage area,
data transfer speed and complexity, a computer network may be classified as:
LAN (Local Area Network): A Local Area Network (LAN) is a network that is limited to a small
area. It is generally limited to a geographic area such as within lab, school or building. It is
generally privately-owned networks over a distance up to a few kilometers. Now-a-days, we
also have WLAN (Wireless LAN) which is based on wireless network.
MAN (Metropolitan Area Network): MAN is the networks cover a group of nearby corporate
offices or a city and might be either private or public. Cable TV network or cable based
broadband internet services are examples of MAN.

WAN (Wide Area Network):These are the networks spread over large distances, say across
countries or even continents through cabling or satellite uplinks are called WAN. Typically, a
WAN combines multiple LANs that are geographically separated. It is a network of network.
The world’s most popular WAN is the Internet.
PAN (Personal Area Network): A Personal Area Network is computer network organized
around an individual person. It generally covers a range of less than 10 meters. Personal
Area Networks can be constructed with cables or wirelessly.

Comparison between PAN, LAN, MAN and WAN: -

Parameter PAN LAN MAN WAN


Area covered Small Area (upto A building or A city (upto 100 Entire country,
10m radius) campus (upto Km radius) Continent or
1 km) Globe
Networking Negligible inexpensive expensive Very expensive
Cost
Transmission Speed High High speed Moderate speed Low speed
speed
Error Rate Lowest Lowest Moderate Highest
Network WLAN, USB LAN/WLAN, Router, Gateway Router, Gateway
Devices used Dongle, Blutooth HUB/Switch,
Repeater,
Modem
Technology/ infrared, Ethernet, Wi- Optical fiber, Microwave,
Media used Bluetooth Fi Radio wave, Satellite
Microwave

Network Protocols:

HTTP (Hyper Text Transfer Protocol) :


 The Hyper Text Transfer Protocol is a set of rules which is used to
access/retrieve linked web pages across the web using web browser program.
 The more secure and advanced version is HTTP is HTTPS (HTTP Secure), which
controls the transfer of information in encrypted form to provide more security
and privacy.
 Other protocols like File Transfer Protocol (FTP) and Telnet can also be used
with URL. FTP is used to transfer files from web server to web client or vice-
versa.
 Telnet is protocol which used for login on remote computer to access/transfer
files or trouble shooting.
FTP (File Transfer Protocol) is a network protocol for transmitting files between computers
over Transmission Control Protocol/Internet Protocol (TCP/IP) connections. Point-to-Point
Protocol (PPP) is a TCP/IP protocol that is used to connect one computer system to
another. Computers use PPP to communicate over the telephone network or the Internet. A
PPP connection exists when two systems physically connect through a telephone line.

TCP/IP stands for Transmission Control Protocol/Internet Protocol and is a suite of


communication protocols used to interconnect network devices on the internet. TCP/IP is
also used as a communications protocol in a private computer network.
TELNET is commonly used by terminal emulation programs that allow you to log into a
remote host. However, TELNET can also be used for terminal-to-terminal communication
and interprocess communication. TELNET is also used by other protocols (for example, FTP)
for establishing a protocol control channel.
E-Mail (Electronic Mail):
Email is the short form of electronic mail. It is one of the ways of sending and receiving
message(s) using the Internet. An email can be sent anytime to any number of recipients at
anywhere. The message can be either text entered directly onto the email application or an
attached file (text, image, audio, video, etc.) stored on a secondary storage. An existing file
can be sent as an attachment with the email.
E-Mail Protocols:
Email are handled and exchanged through various mail servers in order to deliver email to mail
client. The mail client and mail servers exchange information with each other using some
protocols. The followings are commonly used protocols for email handling-
SMTP (Simple Mail Transfer Protocol): This protocol is used to send emails from sender
to recipient’s mail server.
IMAP (Internet Message Access Protocol): This is a standard client/server protocol for accessing e-
mails from local e-mail server.
POP3 (Post Office Protocol 3): This protocol facilitates users to access mailboxes and download
messages to their computer.
Voice over Internet Protocol (VoIP):
 Voice over Internet Protocol or VoIP, allows voice call (telephone service) over
the Internet. VoIP offers voice transmission over a computer network (IP) rather
than through the regular telephone network. It is also known as Internet
Telephony or Broadband Telephony. Examples of VoIP:- WhatsApp, Skype,
Google Chat etc.
 VoIP works on the principle of converting the analogue voice signals into digital
and then transmitting them over the broadband line.
 These services are either free or very economical. That is why these days
international calls are being made using VoIP.

Overview of Internet:
 Internet is a network of networks that consists of millions of private, public,
academic, business, and government networks, that are linked by various wired,
wireless, and optical networking technologies.
 The Internet is a global system of interconnected computer networks that use
the standard Internet protocol suite (TCP/IP) to serve several billion users
worldwide.
 The modern Internet is an extension of ARPANET (Advance Research Project
Agency Network), created in1969 by the American Department of Defense.
 In 1990 the British Programmer Tim Berners-Lee developed Hypertext and
HTML to create World Wide Web (WWW).
 The Internet carries an extensive range of information resources and services,
such as the inter-linked hypertext documents of the World Wide Web (WWW),
the communicational infrastructure to support mail, chat and transfer of Text,
Images, Audio, Video etc.

Introduction to web services:

World Wide Web (WWW):


World Wide Web, which is also known as a Web, is a collection of websites or web pages stored
in web servers and connected to local computers through the internet. These websites
contain text pages, digital images, audios, videos, etc. Users can access the content of these
sites from any part of the world over the internet using their devices such as computers,
laptops, cell phones, etc. The WWW, along with internet, enables the retrieval and display of
text and media to your device.
There sources of the Web (HTML pages) are transferred via the Hypertext Transfer Protocol
(HTTP), may be accessed by users by a software application called a web browser, and are
published by a software application called a web server.
Tim Berners-Lee—a British computer scientist invented the revolutionary World Wide Web in
1990 by defining three fundamental technologies that lead to creation of www: HTML
,URL, HTTP.

HTML(Hyper Text Markup Language):


Hyper Text Markup Language (HTML) is a language which is used to design standardized Web
Pages, so that the Web contents can be read and under stood from any computer using web
browser.
Basic structure of every web page is designed using HTML. HTML uses tags to define the way
page content should be displayed by the web browser. Web pages are stored as .html or .htm
files.
Extensible Markup Language (XML): Extensible Markup Language is a markup language and
file format for storing, transmitting, and reconstructing arbitrary data. It defines a set of
rules for encoding documents in a format that is both human-readable and machine-
readable.

Domain Name: A domain name is a unique, easy-to-remember address used to access websites,
such as 'google.com', and 'facebook.com'.

URL(Uniform Resource Locator):


URL—Uniform Resource Locator is a unique address of web resources located on the web. It
provides the location and mechanism (protocol) to access the resource. URL is sometimes
also called a web address.
A URL contains protocol, domain, sub domain and name of web page along with directory.

In the above URL, http is the protocol name, it can be https, http, FTP, Telnet, etc. www is a sub
domain. ncert.nic.in is the domain name. Textbook is directory and textbook.htm is webpage.
The complete unique address of the page on a website is called URL (Uniform Resource
Locator) e.g. http://www.cbse.nic.in/welcome.html
Since computers on the network are identified by its IP addresses, so it is required to
convert a Domain name or URL typed in the Browser, in to its corresponding IP address.
This process is called Domain Name Resolution. This resolution is done by the designated
servers called DNS servers, provided by the Internet Service Providers (ISP) like BSNL,
Airtel, Jio etc. Website:
 Website is a collection of related web pages that may contain text, images, audio
and video. The first page of a website is called home page. Each website has
specific internet address (URL) that you need to enter in your browser to access
a website.
 A website is a collection of web pages related through hyperlinks, and saved on a
web server. A visitor can navigate pages by clicking on hyperlinks.
 The main purpose of website is to make the information available to people at
large. For example, a company may advertise or sell its products, a government
organization may publish circulars, float tenders, invite applications for
recruitments etc.
 A website can be accessed by providing the address of the website (URL) in the
browser. The main page of website (Home page) will be open when it is opened
on the browser.
Web Page:
 A web page is a document on the WWW that is viewed in a web browser. Basic
structure of a web page is created using HTML (Hyper Text Markup Language).
 To make web pages more attractive, various styling CSS (Cascading Style Sheets)
and formatting are applied on a web page.
 Further, program codes called scripts also used to make webpage interactive and
define different actions and behavior. JavaScript, PHP and Python are commonly
used script language.
 The first page of the website is called a home page which contains Menus and
Hyperlinks for other web pages.
 A web page is usually a part of a website and may contain information in
different forms, such as: text, images, audio & video, Hyperlinks, interactive
contents (chat etc.)
A web page can be of two types: Static Web Page and Dynamic Web Page

Web Browsers:
 A web browser or simply ‘browser’ is a software application used to access
information on the World Wide Web. When a user requests some information,
the web browser fetches the data from a web server and then displays the
webpage on the user’s screen.
 The popular web browsers are Google Chrome, Mozilla Firefox, Internet
Explorer, Opera, Safari, Lynx and Netscape Navigator, Microsoft Edge etc.
 A web browser essentially displays the HTML documents which may include
text, images, audio, video and hyperlinks that help to navigate from one web
page to another. The modern browsers allow a wide range of visual effects, use
encryption for advanced security and also have cookies that can store the
browser settings and data.
Web Server:
 A web server is used to store and deliver the contents of a website to web clients
such as a browser.
 A Computer stores web server software and a website's contents (HTML pages,
images, CSS style sheets, and JavaScript files). The server needs to be connected to
the Internet so that its contents can be made accessible to others.
 Web server as a software, is a specialized program that understands URLs or
web addresses coming as requests from browsers, and responds to those requests.
 The server is assigned a unique domain name so that it can be accessed from
anywhere using Internet. The web browser from the client computer sends a HTTP
request for a page containing the desired data or service. The web server then
accepts request, interprets, searches and responds (HTTP response) against request
of the web browser. The requested web page is then displayed in the browser of the
client. If the requested web page is not found, web server generates “Error: 404 Not
found” as a response.
Web Hosting:
 A web hosting service is a type of Internet hosting service that allows individuals
and organisations to make their website accessible via the World Wide Web. In Simple,
uploading of website on Web Server is known as hoisting. To upload the website, we
need some web space on server to upload website. This space is available on some
nominal charges.
 All web servers are assigned a unique numeric address called IP address when
connected to the Internet. This IP address needs to be mapped/changed to domain
name (Textual name) of the website using DNS (Domain Name Service). Thus, user can
access website by providing domain name through a browser (URL). The domain name
has to be registered (purchased) with an authorized agency i.e. Registrar Domain
Names.
QUESTIONS ON COMPUTER NETWORKING
MULTIPLE CHOICE QUESTIONS(1 MARK EACH)
1. is a communication methodology designed to deliver both voice and multimedia
communications over Internet protocol.
(A) SMTP (B) VoIP (C) PPP (D) HTTP

2. Which of the following is used to receive emails over Internet?


a) SMTP b) POP c) PPP d) VoIP

3. What is the size of IPv4 address?


(a)32 bits (b) 64 bits (c) 64 bytes (d) 32 bytes

4. protocol provides access to command line interface on a remote computer.

a) FTP b)Telnet c)VoIP d)SMTP


5. is a communication methodology designed to deliver electronic mail (E-mail) over
the internet.

. (a) VoIP (b) HTTP (c) PPP (d) SMTP


6. Which protocol is used for transferring files over a TCP/IP network?
a) FTP b) SMTP c) PPP d) HTTP

7. Network in which every computer is capable of playing the role of a client, or a server
or both at same time
is called
a) local area network b) peer-to-peer network c) dedicated server network d) wide
area network

8 is a communication methodology designed to establish a direct and


dedicated communication between an internet user and his/her ISP.
a) VoIP (b) SMTP (c) PPP (d)HTTP

9. Identify the device on the network which is responsible for forwarding data from
one device to another
(a) NIC (b) Router (c) RJ45 (d) Repeater

10. Which of the following device send data to every connected node?
a) Switch b)Repeater c)Router d) Hub

11. In which type of switching first the connection is established between


sender and receiver and then the data is transferred?
a) Circuit b)Message c)Packet d)None

12. Identify the cable which consists of an inner copper core and a second
conducting outersheath:
(i)Twisted Pair (ii) Co-axial (iii) Fiber Optical (iv) Shielded Twisted Pair
13. In fiber optic transmission, data is travelled in the form of:
(i) Light (ii) Radio link (iii) Microwave Link (iv) Very low frequency
14. Which of the following devices modulates digital signals into analog signals
that can be sentover traditional telephone lines?
(i) Router (ii) Gateway (iii) Bridge (iv) Modem

15. Out of the following guided media, which is not susceptible to


external interference?
(i) Twisted Pair (ii) Co-axial Cable (iii) Fiber Optical (iv) Electric Wire

16. Which of the following device is used for sorting and distribution of data packet
to theirdestination based on their IP Address?
(i) Gateway (ii) Router (iii) Bridges (iv) Switch

17. Which of the following device is used to connect network of


different protocols so that theycan communicate properly?
(i) Gateway (ii) Router (iii) Bridges (iv) Switch

18. Which type of Network is generally privately owned and links the devices in a
single office,building or Campus?
a. LAN b. MAN c. WAN d. PAN

19. Raj, is working as a Tech Support Engineer and sometimes he wants to


work on Client’scomputer from his office. Identify the traditional protocol
used for this purpose?
a. FTP b.Telnet c,HTTP d.POP3

20. Raj is looking for some information about How Router works, for this he
opens the browser and typed the URL of requested site. In few moments he
received the requested page on his browser screen. Identify the type of
protocol, used between Browser (Client) and Web Server for the
communication?
a. TCP/IP b.HTTP c,SMTP d.POP3

2 MARKS QUESTIONS
1. Write two points of difference between Bus topology and star topology.
2. Write two points of difference between XML and HTML.
3. Write the full forms of the following:
(i) HTTP (ii) FTP
4. Discuss the use of TELNET
5. Write two advantages and two disadvantages of circuit switching.
6. Differentiate between Web server and web browser. Write any two popular web browsers.

7. Classify each of the following Web Scripting as Client Side Scripting and
Server SideScripting :
(i) Java Scripting
(ii) ASP
(iii) VB Scripting
(iv) JSP

8. What is Bandwidth? What is the measuring unit of Bandwidth in term of range


of frequencies a channel can pass?
9. (a) Write the full forms ithe following:
(i) FTP (ii) HTTPS
b) Name the protocols which are used for sending and receiving emails?

10. Write two differences between Coaxial and Fiber transmission media.

5 MARKS QUESTIONS
1. A professional consultancy company is planning to set up their new offices in India with its
hub at
Hyderabad. As a network adviser, you have to understand their requirement and suggest them the
best
available solutions. Their queries are mentioned as (i) to (v) below.

a) Which will be the most appropriate block, where TTC should plan to install their server?

b) Draw a block to block cable layout to connect all the buildings in the most
appropriate manner for efficient communication.

c) What will be the best possible connectivity out of the following, you will suggest to
connect the new setup of offices in Bengalore with its London based office.
● Satellite Link
● Infrared
● Ethernet

d) Which of the following device will be suggested by you to connect each computer in
each of the buildings?
● Switch
● Modem
● Gateway

e) Company is planning to connect its offices in Hyderabad which is less than1 km. Which
type of network will be formed?

Sol: (i) The company should install its server in finance block as it is having maximum number
of computers.
(ii) The layout is based on minimum cable length required, which is 120 metres in
the above case.
(iii) Satellite Link.
(iv) Switch.
(v) LAN

2. FutureTech Corporation, a Bihar based IT training and development company, is planning to


set up training centers in various cities in the coming year. Their first centeris coming up in
Surajpur district. At Surajpur center, they are planning to have 3different blocks - one for
Admin, one for Training and one for Development. Each block has number of computers,
which are required to be connected in a network for communication, data and resource
sharing. As a network consultant of this company,you have to suggest the best network related
solutions for them for issues/problems raised in question nos. (i) to (v), keeping in mind the
distances between variousblocks/locations and other given parameters.

(i) Suggest the most appropriate block/location to house the SERVER in the Surajpur
center (out of the 3 blocks) to get the best and effective connectivity. Justify your
answer.

(ii) Suggest why should a firewall be installed at the Surajpur Center?

(iii) Suggest the best wired medium and draw the cable layout (Block to Block)
to most efficiently connect various blocks within the Surajpur Center.

(iv) Suggest the placement of the following devices with appropriate reasons:
a) Switch/Hub b) Router

(v) Suggest the best possible way to provide wireless connectivity between Surajpur Center
and Raipur Center.

Sol: i) Development because it contains more number of computers


ii) Surajpur centre has multiple blocks and firewall ensures security. So it is required. It
allows or block unwanted attacks.
iii)

iv) a) Switch/Hub – In every block to interconnect the devices within every block
b) Router -In development block because server is going to be placed here
v) Satellite

3. Total-IT Corporation, a Karnataka based IT training company, is planning to set up


training
centers in various cities in next 2 years. Their first campus is coming up in Kodagu district.
At Kodagu campus, they are planning to have 3 different blocks, one for AI, IoT and
DS (Data Sciences) each. Each block has number of computers, which are required to
be connected in a network for communication, data and resource sharing. As a network
consultant of this company, you have to suggest the best network related solutions for them
for issues/problems raised in question nos. (i) to (v), keeping in mind the distances
between various blocks/locations and other given parameters.

(i) Suggest the most appropriate block/location to house the SERVER in the Kodagu
campus (out of the 3 blocks) to get the best and effective connectivity. Justify your
answer. Ans: IoT block, as it has the maximum number of computers.

(ii) Suggest a device/software to be installed in the Kodagu Campus to take care of


data security.
Ans:Firewall

(iii) Suggest the best wired medium and draw the cable layout (Block toBlock) to
most efficiently connect various blocks within the Kodagu Campus.
Ans:Optical fiber
(iv) Suggest the placement of the following devices with appropriate reasons:
a) Switch/Hub b) Router
Sol:a) Switch/Hub: In each block to interconnect the computers in that block.
b) Router: In IoT block (with the server) to interconnect all the three blocks.

(v) Suggest a protocol that shall be needed to provide Video Conferencing solution
between Kodagu Campus and Coimbatore Campus.
Sol:VoIP

4. Aryan Infotech Solutions has set up its new center at Kamla Nagar for its office and web
based activities. The company compound has 4 buildings as shown in the diagram
below:

i) Suggest a cable layout of connections between the buildings.


ii) Suggest the most suitable place (i.e. building) to house the server of this
organisation with a
suitable reason

iii) Suggest the placement of the following devices with justification:


a. Internet Connecting Device/Modem
b. Switch

iv) The organisation is planning to link its sale counter situated in various parts of
the same city,
which type of network out of LAN, MAN or WAN will be formed? Justify your answer.

v) What do your mean by PAN? Explain giving example.

Sol: i)

ii) Orbit Building


iii) a. Internet Connecting Device/Modem- Orbit Building
b. Switch- Each Building
iv) MAN, it is formed to connect various locations of the city via
various communication media.
v) PAN is “Personal Area Network”, basically configured at home area.

5. Magnolia Infotech wants to set up their computer network in the Bangalorebased campus
having four
buildings. Each block has a number of computers that are required to be connected for ease of
communication, resource sharing and data security. You are required to suggest the best
answers to
the questions i) to v) keeping in mind the building layout on the campus.
i) Suggest the most appropriate block to host the Server. Also justify your choice.

ii) Suggest the device that should should be placed in the Server building so that they can
connect to Internet Service Provider to avail Internet Services.

iii) Suggest the wired medium and draw the cable block to block layout to economically
connect the various blocks.

iv) Suggest the placement of Switches and Repeaters in the network with justification.

v) Suggest the high-speed wired communication medium between Bangalore Campus and
Mysore campus to
establish a data network.

Sol: i) Admin Block since it has maximum number of computers.


ii) Modem should be placed in the Server building
iii) The wired medium is UTP/STP cables.

iv) Switches in all the blocks since the computers need to be connected to the
network. Repeaters between Admin and HR block& Admin and Logistics block. The
reason being the distance is more than 100m.
v) Optical Fiber cable connection.
Unit : 3 Database Management and Mysql

Relational
Database
Model
Introductory
Database
Concepts of
Constraints
Database

Database
Management

Common Database
Database Languages
Operations & SQL

Database
Keys

Structured Query Language (SQL)

SQL

DDL DML TCL Query

Operations in SQL

SELECT ALIAS ORDER BY


MATHS RELATIONAL LOGIC
OPERATION OPS OPS
IN / IS / LIKE /
NOT IS NOT LIKE
IN NOT
DISTINCT GROUP BY HAVING
EQUI NATURAL CARTESIAN
JOIN JOIN PRODUCT
Database Management System (DBMS)

Common Terminologies related to database:


 Data -> Raw facts or figures
 Database -> A collection of interrelated data.
 DBMS -> A collection of files and a set of programs allowing users to
access/modify these files are known as Database Management System.
 Data Redundancy - > Duplication of data.
 Data Security -> Protection of data against accidental/intentional disclosure to
unauthorized person or unauthorized modification/destruction.
 Data Privacy -> Right of individual/organization to determine when/how/what information
to be transmitted to others.

Need of using Database:


 Helps to store data in a structured manner
 Query in the Database (i.e. ask questions about the data)
 Sort and Manipulate Data in the Database
 Validate the Data Entered and check for inconsistencies
 Produce Flexible Reports
Advantage of using Database:
 Reduce data redundancy
 Control inconsistency
 Facilitates sharing of data
 Enforce standards
 Ensure data security
 Maintain integrity
Limitations of implementing Database:
 Compromise of Security and Integrity without good control
 Performance overhead
 Extra hardware required sometimes
 Complex system
Types of DBMS:
 Hierarchical DBMS
 Network Based DBMS
 Object Based DBMS
 Relational DBMS

RELATIONAL DATA MODEL


Relational Data Model is defined as a model of defining a database as a collection of
tables/relations i.e. arrangement of values in rows/tuples and columns/fields/attributes.
Common Terminologies related to Relational Data Model:
 Relation: Collection of data organized in rows and columns where each cell has
atomic value. (same as Table)
 Tuple: Row of a table (same as Record)
 Attribute: Column of a table (same as Field)
 Domain: Range of values (data types) allowed for an attribute
 Degree: No. of attributes/columns/fields in a table
 Cardinality: No. of tuples/rows/records in a table
 View: Virtual table (no physical existence) derived from one or more base table for ease
of query only.
 Referential Integrity: Property of database that requires every value of one attribute of
a Relation must be present in another attribute (same datatype) in a different (or the
same) relation.
Example:

In the above table STUDENT, degree = 7 and cardinality = 5.

Database Key
Key in a database is defined as a set of attributes to identify each record uniquely in a table. A Key
must be unique and not null.
Classification of Keys:

Key

Candidate Primary Key Alternate Key Foreign Key



 Candidate Key: Candidate key is defined as a set of minimum no. of attributes to uniquely
identify a record in a table. A table may have multiple candidate keys.
 Primary Key: The one candidate key chosen by Database Administrator for a table to
uniquely identify a record in a table is said to be Primary Key of that table. A table can
have exactly one Primary Key.
 Alternate Key: Candidate key(s) not chosen by Database Administrator in a table is/are
defined as alternate key(s). A table can have 0 or more alternate keys.
 Foreign Key: Foreign Key is a non-key attribute derived from primary key of some other
table. A table can have 0 or more foreign keys.

Data types in SQL


 Numeric data types: Used for representing number in a column
e.g. –
int(m) – Integer of maximum length m i.e. maximum number of digits allowed in m.
float(m,d), decimal (m,d), numeric(m,d) – Real number of maximum length m where
maximum number of digits permissible after decimal point is d and before decimal point is
m-d.

 Date & Time data types: Used to represent date, time, or both in a column. Data is enclosed
with quotes ‘ ’ or “ “.
e.g. - date, datetime, time

 String / Text data types: Used to represent text in a column. Data is enclosed with quotes ‘ ’
or “ “.
e.g. –
char(m) – Fixed length character of length m where 1 character takes 1 Byte in memory.
Memory space is wasted if text size is less than m.
varchar(m) – Variable length character allowing maximum number of characters m. It
saves memory allocation for text having lesser size than m.

blob – Binary Large object for huge size text.

 NULL – NULL is said to be the absence of any value in a column. No arithmetic or


comparison operation can be performed on NULL value.

Classification of Database Language

Data Definition Language (DDL):


Data Definition Language (DDL) defines the different structures in a database like table, view,
index etc.
DDL statements are used to create structure of a table, modify the existing structure of the table
and remove the existing table.
e.g. - CREATE, ALTER, DROP
Syntax of DDL statements:
 CREATE TABLE table_name
(column_name datatype constraint)
 ALTER TABLE table_name
ADD column datatype constraint (if any)
MODIFY column new_datatype new_constraint (if any)
DROP column
 DROP TABLE table_name

Data Manipulation Language (DML):


Data Manipulation Language (DML) statements are used to access and manipulate
data in existing tables.
The manipulation includes inserting data into tables, deleting data from the tables and modifying
the existing data.
e.g. – INSERT, UPDATE, DELETE

Types of DML statements:


 INSERT record
INSERT INTO table_name(columns) VALUES (1 or more comma separated values)
 UPDATE one or more columns in already existing record(s)
UPDATE table_name SET column = value or expression
(comma separated if multiple columns updated) WHERE condition
 DELETE record
DELETE FROM table_name WHERE condition

Transaction Control Language (TCL):


Database ensures that a database transaction i.e. complete set of records involved in a transaction
either fully completed or not taken place at all to maintain data consistency. Transaction Control
Language (TCL) statements allows to save or revert database transactions.
e.g. –
COMMIT – Save the changes permanently in the database
ROLL BACK – Revert back the changes made in database

Query:
Query is a type of SQL commands which accepts tables (relations), columns (fields or attributes)
and conditions or specifications if any and display the output by means of a temporary table which
consists of data represented through fields and records.
Structure of Query:
SELECT < 1, multiple ( comma i.e. , separated) or all columns >
FROM < 1 table or multiple tables ( comma i.e. , separated) in case of join >
WHERE <condition on column(s)>
GROUP BY <1 column>
HAVING < condition on aggregate function on a column only if group by exists >
ORDER BY <0, 1 or more ( comma i.e. , separated) columns >
Note:
I. Among above SELECT and FROM are mandatory statements in a query and all other
statements are optional.
II. SELECT statement contains one or more columns. * should be used to display all columns.
Functions or expressions on columns can also be done.
III. FROM statement contains multiple tables only if columns from more than one tables are
displayed through SELECT statement in case of product or join operations. Here records
can be fetched from multiple tables.
IV. WHERE clause may contain multiple conditions related with logical OR / AND operators.
Logical NOT operator can be used on a condition also.
V. GROUP BY clause is used if statistical records are to be displayed based on a field/column.
In this case SELECT statements should contain GROUP BY field and aggregate function
on another column at least. Once a group is formed individual records cannot be accessed
in the same query.
VI. ORDER BY clause can be used to arrange the output records in ascending (by default) or
descending order of values in one or more columns.
Order of execution of a
query Step 1: Identify table(s) with FROM clause
Step 2: Filter records using WHERE clause
Step 3: Form group if any using GROUP BY clause
Step 4: Filter groups using HAVING clause only if GROUP BY is used
Step 5: Arrange the output records in ascending or descending order using ORDER BY
Step 6: Display the fields mentioned in SELECT clause.

Database Constraints
Rules imposed on the values of one or more columns in the tables are called database constraints. The
database constraints are:
UNIQUE Ensures that all values in a column are different. No two records have
same values in that column.
NOT NULL Ensures that a column can never have NULL values.
PRIMARY KEY Uniquely identify a record. It is a combination of UNIQUE and NOT
NULL.
CHECK Specify the domain of values with certain criteria for a column.
DEFAULT Provides default value for a column when no value is specified.
REFERENCES /
FOREIGN KEY

SQL STATEMENTS WITH EXAMPLES


Create two tables EMPL and DEPT as follows:
In DEPT table:
1. DEPT_ID is primary key
2. DNAME is not null
3. MAX_STRENGTH should be minimum 1
In EMPL table:
1. EID is primary key
2. ENAME is not null
3. HOMETOWN is ‘BANGALORE’ by default
4. SALARY is between 5000.00 and 300000.00
5. MGR_ID refers to EID of manager
6. DEPT_ID refers to DEPT_ID of table DEPT
A. Write DDL statement to create a database OFFICE and define two tables mentioned as above
under OFFICE database.
Create new database OFFICE in MySQL as following:
CREATE DATABASE OFFICE;
Work inside the database OFFICE as following:
USE OFFICE;
Note: By default, TEST database is used which is in-built database in MySQL. So no need to
create test. Only ‘use test;’ statement can be written to enter test.
DDL statement to create DEPT table is as following:
SOLUTION 1 SOLUTION 2
CREATE TABLE DEPT CREATE TABLE DEPT
( (
DEPT_ID VARCHAR(4) PRIMARY KEY, DEPT_ID VARCHAR(4),
DNAME VARCHAR(15) NOT NULL, DNAME VARCHAR(15) NOT NULL,
DLOC VARCHAR(20), DLOC VARCHAR(20),
MAX_STRENGTH INT(2) CHECK MAX_STRENGTH INT(2),
(MAX_STRENGTH >= 1) PRIMARY KEY(DEPT_ID),
); CHECK (MAX_STRENGTH >= 1)
);
Schema or structure of table DEPT is as follows:

DESC DEPT;

DDL statement to create EMPL table is as following:

CREATE TABLE EMPL


(
EID VARCHAR(6) PRIMARY KEY,
ENAME VARCHAR(30) NOT
NULL,
GEN CHAR(1) CHECK (GEN IN ('M', 'F', 'T')),
DOJ DATE,
HOMETOWN VARCHAR(20) DEFAULT 'BANGALORE',
SALARY DECIMAL(8, 2) CHECK (SALARY BETWEEN 5000 AND 300000),
MGR_ID VARCHAR(6) REFERENCES EMPL(EID),
DEPT_ID VARCHAR(4) REFERENCES DEPT(DEPT_ID)
);

or,
CREATE TABLE EMPL
(
EID VARCHAR(6),
ENAME VARCHAR(30) NOT
NULL, GEN CHAR,
DOJ DATE,
HOMETOWN VARCHAR(20) DEFAULT 'BANGALORE',
SALARY DECIMAL(8, 2) ,
MGR_ID VARCHAR(6) ,
DEPT_ID VARCHAR(4)
, PRIMARY KEY(EID),
CHECK (GEN IN ('M', 'F', 'T')),
CHECK (SALARY BETWEEN 5000.00 AND 300000.00),
FOREIGN KEY(MGR_ID) REFERENCES EMPL(EID),
FOREIGN KEY(DEPT_ID) REFERENCES DEPT(DEPT_ID)
);

Schema or structure of table EMPL is as follows:

DESC EMPL;
Name of tables defined in current database so far.

SHOW TABLES;

B. Write DML statements to insert records in two tables.

DML statements to insert records in DEPT are as follows:

INSERT INTO DEPT VALUES ('D01', 'FINANCE', 'MUMBAI', 20);

INSERT INTO DEPT VALUES ('D02', 'ADMIN', 'KOLKATA', 15);

INSERT INTO DEPT VALUES ('D03', 'IT', 'CHENNAI', 5);

DML statements to insert records in EMPL are as follows:

INSERT INTO EMPL VALUES ('E0001', 'RITU SEN', 'F', '2002-06-20', 'KOLKATA',
40000.00, NULL, 'D03');

INSERT INTO EMPL VALUES ('E0002', 'MALCOM RAY', 'M', '1998-11-12',


'BANGALORE', 50000.00, NULL, 'D02');

INSERT INTO EMPL(EID, ENAME, GEN, DOJ, HOMETOWN, SALARY, DEPT_ID)


VALUES ('E0003', 'SUNDAR P', 'M', '2008-12-09', 'BANGALORE', 40000.00, 'D01');

INSERT INTO EMPL VALUES ('E0004', 'ANISHA RAWAT', 'F', '2019-09-04', 'DELHI',
20000.00, 'E0001', 'D03' );

INSERT INTO EMPL VALUES ('E0005', 'SANA KHAN', 'F', '2017-08-31', 'DELHI',
30000.00, 'E0003', 'D01');

C. Write SQL statements for the following queries and display their outputs.

1. Display all the records from table DEPT.


SELECT * FROM DEPT;

2. Display name and salary of all the employeEs from table EMPL.
SELECT ENAME, SALARY
FROM EMPL;
4. Display DNAME in ascending order of MAX_STRENGTH.

SOLUTION 1 SOLUTION 2 OUTPUT


SELECT DNAME SELECT DNAME
FROM DEPT FROM DEPT
ORDER BY ORDER BY
MAX_STRENGTH; MAX_STRENGTH ASC;

Note:
 Sorting in SQL is by default in ascending order of values be it numeric or
alphabetical order. Hence ASC is default keyword and need not be used in ORDER
BY statement.
 In case of arranging the output of query in descending order of values DESC keyword
must be used in ORDER BY statement.

Comparison operators
= > < >= <= <> !=

4. Display name and gender of employees whose hometown is BANGALORE.


SOLUTION OUTPUT
SELECT ENAME, GEN
FROM EMPL
WHERE HOMETOWN =
'BANGALORE';

5. Display the name of departments which are not located in KOLKATA.

SOLUTION 1 SOLUTION 2 OUTPUT


SELECT DNAME SELECT DNAME
FROM DEPT FROM DEPT
WHERE DLOC <> WHERE DLOC !=
KOLKATA'; 'KOLKATA';

6. Display name of employees and salary in descending order of names where DEPT_ID is
not 'D03'.
SOLUTION OUTPUT
SELECT ENAME,
SALARY
FROM EMPL
WHERE DEPT_ID !=
'D03'
ORDER BY ENAME
DESC;

7. Display EID, ENAME of employees whose DOJ is after January, 2015.

SOLUTION OUTPUT
SELECT EID, ENAME FROM
EMPL
WHERE DOJ > '2015-01-31' ;

[Note: DATE should be preferably mentioned in 'yyyy-mm-dd' format.]

Logical Operators
OR AND NOT
Logical operators are used in where clause. AND, OR are binary operations which require 2
conditions. NOT is unary operator which requires one condition only.
 AND : c1 and c2 → If both c1 and c2 are true the overall condition is true.
 OR : c1 or c2 → If at least one between c1 or c2 are true the overall condition is true.
 NOT : not c1 → If c1 is true the overall condition is false and vice versa.

BETWEEN: BETWEEN operator can be used as a substitute of and operation where the minimum
and maximum value is to be checked for a single column.

8. Display the records of those employees whose salary is between 35000 and 45000.
SOLUTION1 SOLUTION2
SELECT * FROM EMPL SELECT * FROM EMPL
WHERE SALARY WHERE SALARY BETWEEN
>=35000 35000 AND 45000;
AND SALARY <=45000;
Checking a list of values

IN: IN operator is a substitute of OR operation(s) among equality checking of a single column with
multiple values.
NOT IN: NOT IN operator is used for non-equality checking of a column with multiple values.

9. Display name and hometown of employees who belong to departments 'D01' or 'D02'.
SOLUTION 1 SOLUTION 2 OUTPUT
SELECT ENAME, SELECT ENAME,
HOMETOWN HOMETOWN
FROM EMPL FROM EMPL WHERE
WHERE DEPT_ID = 'D01' DEPT_ID IN ('D01', 'D02');
OR DEPT_ID = 'D02';

10. Display EID and SALARY of employees whose half of salary is neither 10000 nor 20000.
SOLUTION 1 SOLUTION 2 OUTPUT
SELECT EID, SALARY SELECT EID, SALARY
FROM EMPL FROM EMPL
WHERE NOT (SALARY/2 = WHERE SALARY/2 NOT
10000 OR SALARY/2 = IN (10000, 20000);
20000);

Wildcard Characters

A string constant to be checked with a value stored in a column may have one or more characters
missing in case of sub string checking. Such placeholder can be of two types:
_ → Replacement or placeholder of exactly one character in the string constant value.
(underscore)
% → Replacement or placeholder of 0 or more characters in the string constant value.

LIKE: A string constant containing one or more wildcard characters can be checked for equality
with LIKE operator only, not =.
NOT LIKE: Likewise NOT LIKE operator checks inequality checking with a string constant
containing one or more wildcard characters. It cannot be done using <> or !=.

11. List the name of employees whose name starts with 'S' and have length at least 5.
SOLUTION OUTPUT
SELECT ENAME
FROM EMPL
WHERE ENAME LIKE 'S %';

[Hints: 4 underscores i.e. _ after S]


12. List the name of employees whose name ends with 'N' or does not contain 'M' in it.

SOLUTION OUTPUT
SELECT ENAME
FROM EMPL
WHERE ENAME LIKE '%N'
AND ENAME NOT LIKE '%M
%';

NULL checking
IS: IS is a special operator which is used to check absence of value i.e. NULL in a column as no
other comparison operator can be used on NULL values.
IS NOT: Likewise, IS NOT is used to check the presence of values i.e. NOT NULL in a column.
13. Print ENAME and DEPT_ID of employees who do not have manager i.e. MGR_ID is blank.
SOLUTION OUTPUT
SELECT ENAME, DEPT_ID
FROM EMPL
WHERE MGR_ID IS NULL;

14. Print ENAME and DEPT_ID of employees who have manager i.e. MGR_ID is not empty.
SOLUTION OUTPUT
SELECT ENAME, DEPT_ID
FROM EMPL
WHERE MGR_ID IS NOT NULL;

Display redundant or unique values


ALL: ALL keyword allows all the values occurring including duplicate values to be displayed in
output. SQL allows duplicate values in output. ALL is by default used in SQL, so need not be used
explicitly.
DISTINCT: By default, SQL does not remove any duplicate values in the output on its own.
Hence DISTINCT keyword is used along with a column where redundant values need to be
removed before displayed.
15. List the hometowns of all the employee (Including duplicate values).
SOLUTION 1 SOLUTION 2 OUTPUT
SELECT SELECT ALL
HOMETOWN HOMETOWN
FROM EMPL; FROM EMPL;

16. List the name of places which are hometown of any employee. (No duplicate values)
SOLUTION OUTPUT
SELECT DISTINCT
HOMETOWN
FROM EMPL;

Aggregate functions

SUM( ) AVG( ) MAX( ) MIN( ) COUNT( )

Aggregate or statistical functions can be used on a group of records.


Using GROUP BY clause: Display outputs regarding each group formed by the GROUP BY field.
Without using GROUP BY clause: Display output corresponding to the overall table may or may
not be filtered by where clause.
For example, consider the following ITEM table:

GROUP BY: GROUP BY clause is used if statistical records of a table are to be displayed based
on a field. Once the group is formed individual records cannot be accessed in that query. Several
clusters or groups are formed based on the number of different values in the GROUP BY column
present in the table.
For example, if GROUP BY is applied on TYPE field of ITEM table 3 groups are formed – Crops
have 2 records, Leaves and Pulses have one record each.
Renaming field and table
AS is an optional keyword to rename a column a table in FROM clause or an expression on
column(s) in SELECT clause. If there is blank space in alias then it must be surrounded by ' ' or '' ''.
Column renaming is done for customized display of query output.
Table renaming is done for giving convenient names to the tables in join operations for
ease of access by programmers.
17. Display the number of distinct DLOC mentioned in table DEPT.
SOLUTION OUTPUT
SELECT COUNT(DISTINCT DLOC) as 'NO. OF
LOCATIONS'
FROM DEPT;

18. Display the earliest and latest DOJ of employees as per EMPL.
SOLUTION OUTPUT
SELECT MIN(DOJ) 'EARLIEST', MAX(DOJ)
'LATEST'
FROM EMPL;

19. Display the number of employees of each gender GEN.


SOLUTION OUTPUT
SELECT GEN, COUNT(*) COUNT
FROM EMPL
GROUP BY GEN;

20. Display the total SALARY paid by each department.


SOLUTION OUTPUT
SELECT DEPT_ID, SUM(SALARY) 'TOTAL
SALARY'
FROM EMPL
GROUP BY DEPT_ID;

HAVING: It is a conditional statement used along with group by clause only. It compares the
values with the outcome of aggregate functions belonging to each group already formed by
GROUP BY clause.
Difference between WHERE and HAVING:

21. Display the hometowns and no. of employees belonging to them if the headcount per
hometown is at least 2.
SOLUTION OUTPUT
SELECT HOMETOWN, COUNT(EID) 'NO
OF EMPLOYEE'
FROM EMPL
GROUP BY HOMETOWN
HAVING COUNT(EID) >=
2;

22. Display the number of employees working in each DEPT_ID excepting 'D01' where no. of
employees in the DEPT_ID is more than 1.
SOLUTION OUTPUT
SELECT DEPT_ID, COUNT(*) AS 'NO OF
EMPLOYEE'
FROM EMPL
WHERE DEPT_ID != 'D01'
GROUP BY DEPT_ID
HAVING COUNT(*) > 1;

Cartesian Product
Cartesian product is performed on two tables and it produces all the combination of records in both
tables. It does not require any common column.
If tables A, B have m, n columns and p, q records respectively then resultant table A x B has m+n
columns and p x q records.
23. Perform Cartesian Product between EMPL and DEPT.
SOLUTION 1 SOLUTION 2 SOLUTION 3
SELECT * SELECT * SELECT *
FROM EMPL, DEPT; FROM EMPL INNER JOIN FROM EMPL
DEPT; JOIN DEPT;
[RECOMMENDED
STATEMENT]
JOIN
NATURAL JOIN: Natural join is a binary operator which works on two tables. They should have
one column which have same name and domain. It a combination of Cartesian product and a where
clause with equality checking on the common columns.
 Other conditions in that query are ANDed with the join condition.
 Natural join is mostly done on Foreign key field of one table and Primary key field of
another table.
 If tables A, B have m, n columns and p, q records respectively then resultant table has m+n
columns and minimum(p,q) records.

EQUI JOIN: Equi join is a join operation which works on the equality condition of values in two
columns from two tables having similar data type. NATURAL JOIN, EQUI JOIN are said to be
INNER JOIN.
24. Perform Natural Join between these two tables.
SOLUTION 1 SOLUTION 2
SELECT * SELECT *
FROM EMPL NATURAL JOIN FROM EMPL, DEPT
DEPT; WHERE EMPL.DEPT_ID =
DEPT.DEPT_ID;
[RECOMMENDED STATEMENT]

25. Display every ENAME and their corresponding DNAME.


SOLUTION OUTPUT
SELECT ENAME, DNAME
FROM EMPL, DEPT
WHERE EMPL.DEPT_ID = DEPT.DEPT_ID;

26. List the name of employees who work in ADMIN department.


SOLUTION OUTPUT
SELECT ENAME
FROM EMPL AS E, DEPT AS D
WHERE E.DEPT_ID = D.DEPT_ID
AND DNAME = 'ADMIN';

27. Display no. of employees working in those departments whose DLOC is CHENNAI.
SOLUTION OUTPUT
SELECT COUNT(*) 'NO. OF EMPLOYEES'
FROM EMPL AS E, DEPT AS D
WHERE E.DEPT_ID = D.DEPT_ID
AND DLOC = 'CHENNAI';

28. Display ENAME of employees who have manager along with that display ENAME of their
corresponding manager as well.
SOLUTION OUTPUT
SELECT E.ENAME 'EMPLOYEE', M.ENAME
'MANAGER'
FROM EMPL E, EMPL M
WHERE E.MGR_ID = M.EID;

29. Display ENAME and the amount of bonus to be paid to that employee where bonus = 5000 +
5% of SALARY.
SOLUTION OUTPUT
SELECT ENAME, SALARY,
5000 + 0.05 * SALARY 'BONUS'
FROM EMPL;

D. Write DML statements for the following purpose:


1. Assign DEPT_ID 'D03' to those employees who are presently working at 'D02'.
SOLUTION OUTPUT
UPDATE EMPL
SET DEPT_ID = 'D03'
WHERE DEPT_ID = 'D02';

SELECT * FROM EMPL;

2. Increase SALARY of all the employees by 10%.


SOLUTION OUTPUT
UPDATE EMPL
SET SALARY = 1.1
* SALARY;

SELECT * FROM EMPL;

3. Delete the department 'D02' from DEPT table.


SOLUTION OUTPUT
DELETE FROM DEPT
WHERE DEPT_ID = 'D02';

SELECT * FROM DEPT;


E. Write DDL statements for the following purpose:
1. Add DPHONE field to table DEPT which should be a number of 10 digits and unique for each
department.
SOLUTION OUTPUT
ALTER TABLE DEPT
ADD DPHONE INT(10) UNIQUE;

DESC DEPT;

2. Drop the column MAX_STRENGTH from DEPT.


SOLUTION OUTPUT
ALTER TABLE DEPT
DROP MAX_STRENGTH;

SELECT * FROM DEPT;

3. Modify the datatype of SALARY in table EMPL to an integer of length 6 and drop the existing
check constraint.
SOLUTION OUTPUT
ALTER TABLE EMPL
MODIFY SALARY INT(6);

DESC EMPL;

Questions ;
Q. No. 1 to 20 are MCQs of 1 mark each

1. An attribute in a table is foreign key if it is the key in any other table.


a) Candidate b) Primary c) Unique d) Alternate
2. 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
3. Which of the following is not a database constraint?
a. CHECK b. DEFAULT c. UNIQUE d. NULL
4. The data types CHAR (n) and VARCHAR (n) are used to create and
types of string/text fields respectively in a database.
a) Fixed, equal b) Equal, variable c) Fixed, variable d) Variable, equal
5. Which of the following is a DDL command?
A. UPDATE B. INSERT C. DELETE D. ALTER
6. Which command is used to open the database “SCHOOL”?
a. USE SCHOOL b. OPEN SCHOOL
c. USE DATABASE SCHOOL d. SHOW SCHOOL
7. In the given query which keyword has to be inserted?
INSERT INTO employee (1002, “Kausar”, 2000);
a) Value b) Values c) Values into d) Into Values
8. Which SQL statement is used to display all the data from PRODUCT table in the
decreasing order of PRICE?
a. SELECT * FROM PRODUCT ORDER PRICE BY DESC ;
b. SELECT * FROM PRODUCT PRICE ORDER BY DESC;
c. SELECT * FROM PRODUCT ORDER BY DESC PRICE;
d. SELECT * FROM PRODUCT ORDER BY PRICE DESC;
9. Which of the following function is used to FIND the largest value from the given
data in MYSQL?
a) MAX () b) MAXIMUM () c) LARGEST () d) BIG ()
10. Which keyword is used for aliasing a table?
a) ASC b) AS c) IS d) None of these
11. aggregate function does not ignore NULL values in a column.
a) Min() b) Sum() c) Avg () d) Count ()
12. SELECT name FROM class WHERE subject NULL;
Which comparison operator may be used to fill the blank space in above query?
a) = b) LIKE c) IS d) <>
13. Which SQL statement is used to display all the data from ITEMS table where
INAME is ending with ‘L’?
a. SELECT * FROM ITEMS WHERE INAME LIKE ‘L%’;
b. SELECT * FROM ITEMS WHERE INAME LIKE ‘%L’;
c. SELECT * FROM ITEMS WHERE INAME LIKE ‘%L%’;
d. SELECT * FROM ITEMS WHERE INAME LIKE ‘_L_’;
14. Which join combines each row from the first table with every row from the
second table to make the result set?
a. CROSS JOIN b. OUTER JOIN c. INNER JOIN d. EQUI JOIN

State True / False for Q. No. 15 and 16


15. MySQL statement to delete a table STUDENT from the database SCHOOL is
DELETE TABLE STUDENT;
16. Where and Having clauses can be used interchangeably in SQL queries.

Q. No. 17 to 20 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 correct explanation for A.
c. A is true but R is false.
d. A is false but R is true.
17. 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.

18. Assertion(A): DBMS is an application package which arranges the data in orderly
manner in a tabular form.
Reason(R): It is an interface between database and the user. It allows the users to
access and perform various operations on stored data using some tools.

19. Assertion(A): Aggregate function AVG() calculates the average of a set of values
and produces a single value as result.
Reason(R): The aggregate functions are used to perform some basic calculations
like sum, max, min, etc on a set of numbers.

20. Assertion(A): While inserting records in EMP table, value of DateOfBirth field
must be enclosed withing quotes ‘ ‘.
Reasoning(R): Date is represented as char / varchar always.

Q. No. 21 to 30 are questions of 2 marks each


21. a) What do you mean by degree and cardinality of a table?
b) Consider the following table and find its degree and cardinality.

22. What do you mean by referential integrity? Explain with suitable example.

23. Write MySQL statement to create a table named REMEDIAL based on the
following specification:
Table: REMEDIAL

24. Write MySQL statements to do the following:


a. Enter into the database OFFICE and display the name of all the tables.
b. Display the structure of the table ‘EMPL’.

25. Consider the following table PLAYER:

a. Suggest the most suitable Primary Key. Justify your answer.


b. Identify the alternate Keys.
26. Consider the table MOTOR having the following attributes:
VNO, MODEL, BRAND, PRICE

Write SQL statement for the following:


a. Modify the existing column MODEL as varchar(30) and NOT NULL.
b. Increase PRICE by 20% for the BRAND ‘TATA’

27. Categorize the following commands as DDL or DML:


INSERT, UPDATE, ALTER, DROP

28. A MySQL table, sales have 10 rows. The following queries were executed on
the sales table.
SELECT COUNT(*) FROM sales;
COUNT(*)
10

SELECT COUNT(discount) FROM sales;


COUNT(discount)
6
Write a statement to explain as to why there is a difference in both the counts.

29. Explain Group by clause with a suitable example.

30. Distinguish between Natural Join and Equi Join.

Attribute Q. No. 31Data


to 40type
– 3 marks question Constraints
SNAME VARCHAR(20) NOT NULL
31. Write output of the SQL queries based on the following table Employee:
ROLL INT UNIQUE
FEES FLOAT
ADMN INT PRIMARY KEY

(i) select name, project from employee order by project;


(ii) select name, salary from employee where doj like '2015%';
(iii) select min(doj), max(dob) from employee;
PNO PNAME SPORTS COUNTRY SALARY
C001 VIRAT CRICKET INDIA 112
F003 RONALDO FOOTBALL PORTUGAL 1134
T007 ROGER TENNIS SWITZERLA 795
ND
B002 SINDHU BADMINTON INDIA 59
32. Write output of the SQL queries based on the following tables Projects and
Employee:

(i) select project, count(*) from employee group by project;


(ii) select pid, pname, eid, name from projects p, employee e where
p.pid=e.project;
(iii) select avg(salary) from employee where doj between '2018-08-01' and
'2018-08-31';

33. Write SQL statements to do the following:

i. Define CID in CUSTOMER table as Foreign Key that refers to CID i.e.
Primary Key of COMPANY table.

ii. Display the ‘CUSTOMER NAME’, ‘PRODUCT NAME’ who have purchased
any product from the ‘COMPANY NAME’ ‘SONY’.

iii. Increase the QTY by 15 for the products with PRICE below 40,000.

34. Consider the GAMES table and answer the following questions:

i. Identify the possible Candidate Keys in the above table.


ii. Suggest the most suitable column for Primary key of the above table. Give
reason behind your answer.
iii. Write down the Alternate Keys for the above table.
35. Consider a table STORE having attributes as following:
ItemNo –numeric
ItemName – character of size 20
Scode – numeric
Quantity – numeric

Abhay wants to do the following operations on the STORE table. Please help him
to do by writing appropriate SQL statements.
i. Insert the following record in the STORE table:
(2010, Notebook, 23, NULL)
ii. Add a new column price with data type as decimal.

iii. Remove STORE table from the database.

36. What do you mean b y CHECK constraint and DEFAULT constraint? Explain
with suitable example.
37. Consider the following tables and answer the questions below:
i. What will be the degree and cardinality of the resultant table after performing
Cartesian Product between PRODUCT and CLIENT?
ii. What will be the degree and cardinality of the resultant table after performing
NATURAL JOIN between PRODUCT and CLIENT?
iii. Are these values same? What can be the reason for this?
38. i. Write down the purpose of using aggregate functions in MySql.
ii. Give example of any two aggregate functions and their purposes.
iii. Can we use aggregate functions without GROUP BY clause? Justify.

39. i. What is the significance of NULL value in database?


ii. Name the operator that can check for NULL value in a column.
iii. Name the SQL command to permanently save the changes caused by DML
statements in the database.

40. i. Name the aggregate functions valid on a column of DATE data type.
ii. Suggest a keyword for renaming an attribute or a table in MySql.
iii. Write down the syntax of representing the common column CODE while
performing Equi Join between two tables GAME and USER.

Q. No. 41 to 45 – 5 marks question


41. i. Differentiate between ‘WHERE’ clause and ‘HAVING’ clause in MySQL with
appropriate example.

ii. Consider the following table and find the output of the following queries:

a. select SEX, avg(SALARY) from TEACHER group by SEX;

b. select SUBJECT, count(*) from TEACHER group by


SUBJECT having count(*)>1;

c. select SUBJECT, min(SALARY) from TEACHER


where TNAME not like ‘%Kumar’ group by SUBJECT;
42. i. Differentiate between DELETE and DROP in MySQL. Cite suitable examples.

ii. Consider the following tables – Bank_Account and Branch:

What will be the output of the following statement?


SELECT * FROM Bank_Account, Branch;
iii. Choose the correct option:
The above SQL query represents operation.
a. Outer join b. Natural join c. Equi join d. Cross join
43. Fill in the blanks with appropriate keywords in order to complete the following
SQL queries:
CAR

i. Display all the databases present in MySQL of a system.


show ;

ii. Display the values in TYPE column of the table CAR after removing the
duplicate values from the output.
select TYPE from CAR;

iii. Display MODEL, PRICE, COLOUR from CAR whose COLOUR is neither
RED nor BLUE.
select MODEL, PRICE, COLOUR from CAR
where COLOUR (‘RED’, ‘BLUE’);

iv. Display the total number of records present in CAR table.


select (CID) from CAR;

v. Display Discount on each CAR where Discount is 5% of the PRICE.


select MODEL, PRICE*0.05 ‘DISCOUNT’ from
CAR;
44. i. Write two advantages of using database.
ii. Distinguish between CHAR and VARCHAR data type. Which one is preferable
in general and why?
iii. Write down the significance of the data type NUMERIC(7,3).
45. i. What do you mean by Self Join. Give an example.
ii. Fill in the blanks with appropriate keywords for creating the table DRESS with
the following specifications:
 Default COLOR is ‘BLACK’.
 PRICE between 0 and 8000.

CREATE (a) DRESS


(
DCODE INT PRIMARY KEY,
DNAME VARCHAR(15),
COLOR VARCHAR(10) (b) ‘BLACK’,
PRICE DECIMAL(6, 2) (c) PRICE BETWEEN 0 and 8000
);

Q. No. 46 to 50 – Case Study based questions of 4 marks each


46. Consider the following tables ITEM and CUSTOMER and find the outputs of the
following queries:

CID BRAND MODEL TYPE COLOUR PRICE


CO1 MARUTI SWIFT HATCHBACK WHITE 5,00,000
D32 HYUNDAI VERNA SEDAN BLACK 16,00,000
F32 TATA NEXON SUV RED 9,00,000
C29 KIA SELTOS SUV BLUE 17,00,000

i) SELECT ITEM_NAME, MAX(PRICE), COUNT(*) FROM


ITEM GROUP BY ITEM_NAME;

ii) SELECT CNAME, MANUFACTURER FROM ITEM,


CUSTOMER WHERE ITEM.ID=CUSTOMER.ID;

iii) SELECT ITEM_NAME, PRICE*100 FROM ITEM


WHERE MANUFACTURER="ABC";

iv) SELECT DISTINCT CITY FROM CUSTOMER;


47. Consider the tables ITEM and CUSTOMER and write the queries:

(i) Display the total PERIODS for each SUBJECT from SCHOOL table.

(ii) Display TEACHERNAME, GENDER from the tables SCHOOL and ADMIN
whose DESIGNATION is ‘COORDINATOR’.

(iii) Display TEACHERNAME and DOJ in the descending order of CODE.

(iv) Display TEACHERNAME whose DOJ is in the year 2000.


48. Modern Public School is maintaining fees records of students. The
database administrator Aman decided that-
• Name of the database -School
• Name of the table – Fees
• The attributes of Fees are as follows:
Rollno – numeric
Name – character of size 20
Class - character of size 20
Fee – Numeric
PayDate – Date
Primary Key – (Rollno, Class)
Answer the following questions:

(i) Write the DDL statement to create database School.


(ii) Write the SQL statement to create Fees table in School database with the
above-mentioned specifications.
(iii) Write SQL statement to display all the table names in School database.
49. Consider the table Fees mentioned in Q. No. 48 and answer the following
questions:

i. Insert the following record into the table


Rollno-1201, Name-Akshay, Class-12th, Fee-350, PayDate-24 JUNE 2019

ii. Increase the second quarter fee of class 12th students by 50.
iii. Delete the record of student with Rollno-1212
iv. Aman wants to display the schema (structure) of Fees table. Which command
will he use from the following:
a) CREATE b) ALTER c) SHOW d) DESCRIBE

50. Sagar, a cloth merchant creates a table CLIENT with a set of records to maintain
the client’s order volume in Qtr1, Qtr2, Qtr3 and their total. After creation of the
table, he has entered data of 7 clients in the table.

Based on table CLIENT, write SQL statements for the following:

i. Write the statements to Update a record present in the table with data for
Qtr2 = 200, Qtr3 = 600 , total = sum of all Qtrs where the Client_ID is C660.
ii. Delete all records where total is between 500 to 900.

iii. Make changes in ClientName with data type varchar(20) and not null
constraint.
iv. Remove the column Total from the CLIENT table.

SOLUTIONS
1. B 2. a 3. d 4. c 5. d
6. a 7. b 8. d 9. a 10. b
11. d 12. c 13. b 14. a 15. False
16. False 17. a 18. a 19. b 20. c
21. Name Project
a) Degree - no. of attributes in a table, Cardinality – no. of records in a table.
b)Ranjan P01 – 6
Degree – 4, cardinality
22. Muneera
Foreign key of one P01
table refers to the Primary key of another table.
23. Alex
CREATE TABLE P02
Akhtar
REMEDIAL ( P04
Satyansh P04
SNAME VARCHAR(20) NOT NULL,
ROLL INT(5) UNIQUE,
Name FEES FLOAT(7,2),
Salary
RanjanADMN INT(5) 150000
PRIMARY KEY
);Akhtar 125000
24. a. USE OFFICE;
b.min(DOJ)
DESC EMPL; max(DOB) or DESCRIBE EMPL;
25. a.2015-01-21
PNO as unique throughout
1996-11-15table and not null.
b. PNAME, SPORTS, SALARY.
26. a. ALTER TABLE MOTOR MODIFY MODEL VARCHAR(30) NOT NULL;
b. UPDATE MOTOR SET PRICE = PRICE * 1.20 WHERE BRAND = ‘TATA’;
27. DML - INSERT, UPDATE
DDL - ALTER, DROP
28. Count(*) will return the number of records in the table sales. Count(discount) will
return the number of records having not null values in the discount field of sales
table.
29. GROUP BY clause is used if statistical records of a table are to be displayed based
on a field. Groups are formed based on the number of different values in the
GROUP BY column present in the table.
30. In Natural Join the common attribute between two tables appears only once. Where
as in Equi Join the common attribute appears as it is i.e. twice. Hence these
common attributes are accessed as table_name.attribute in the query to resolve the
conflict.
31. i.

ii.

iii.

32. i.
Project count(*)
P01 2
P04 2
P02 1
ii.

iii.
avg(Salary)
135000
33. i. ALTER TABLE CUSTOMER
ADD FOREIGN KEY(CID) REFERENCES COMPANY(CID);

ii. SELECT CU.NAME, CO.PRODUCTNAME


FROM COMPANY CO, CUSTOMER CU
WHERE CU.CID = CO.CID AND CO.NAME = ‘SONY’;

iii. UPDATE CUSTOMER SET QTY = QTY*1.15 where PRICE<40000;


PID PName EID
34. i.P01
Candidate keys Road
- GCode,
102 GameName,
Carpenting PrizeMoney,
E01 ScheduleDate
ii.P04
Primary key - GCode as not null and unique
Footover Bridge K-13 E02 for each game.
iii.
P01Alternate key -Road
GameName, PrizeMoney,
102 Carpenting ScheduleDate
E03
P02 Civil Lines Parking E04
35. i.P04
INSERT INTO Footover
STORE VALUES (2010,E05
Bridge K-13 ‘Notebook’, 23, NULL);
ii. ALTER TABLE STORE ADD PRICE DECIMAL(10,2);
iii. DROP TABLE STORE;

36. CHECK – Ensure that the attribute contains only permissible set of values.
DEFAULT – Ensure the default value is inserted if no value is mentioned.
e.g. -
CREATE TABLE STOCK
(
SNO INT PRIMARY
KEY, SNAME
VARCHAR(20),
LOCATION VARCHAR(15) DEFAULT ‘BANGALORE’,
PRICE FLOAT(7,2) CHECK (PRICE BETWEEN 0.00 AND 10000.00)
)
37. i. After Cartesian product, Degree = 8, Cardinality = 25
ii. After natural join, Degree = 7, Cardinality = 5
iii. No, because cartesian product is the all-possible combination of tuples between
two tables. Where as Natural join selects only those tuples for whom the values of
the common attributes are same.

38. i. Aggregate functions perform calculation on a set of values, and returns a single
value. If used with GROUP BY clause, it returns one value for each group.
SUM() - returns the total sum of a numerical column
MAX() - returns the largest value within the selected column

ii. Yes. Then it returns a single value for the selected attribute by considering all the
records in that table.
39. i. NULL is said to be absence of any value in an attribute. NULL cannot participate
in any operation.
ii. IS
iii. COMMIT
40. i. MAX(), MIN(), COUNT()
ii. AS
iii. SELECT * FROM GAME G, USER U WHERE G.CODE=U,CODE;
41. i. WHERE clause allows to filter data from individual rows of a table based on
certain conditions. In contrast, the HAVING clause allows to filter data from a
group of rows in a query based on conditions involving aggregate functions.
ii.
a)

b)

c)

SEX AVG(SALARY)
42. i.MDELETE is used68666
for deleting records from a table. DROP is used to delete the
F 65000
entire schema of any database object like table.
e.g. –
DELETE FROM STUDENT WHERE ROLL = 5;
SUBJECT
DROP TABLE STUDENT;COUNT(*)
ii.Computer Science 2

SUBJECT MIN(SALARY)
Computer
iii. d. Cross Science
join 75000
43. English
i. databases 55000
ii.Economics
distinct 71000
iii. not in
iv. count
v. as
44. i. Data integrity, data security
ii. Char data type stores data of fixed length, whereas the Varchar data type stores
variable length data. Varchar is preferable as it is more flexible for data of any size.
iii. It can represent 7 digit real number with 3 digits in the right of decimal point.
45. i. A self-join is a regular join, but the table is joined with itself.
E_CODE* FROMNAME
SELECT EMP A, EMP B where E_CODE A.ID = B.ID;LOCATION
ii.E01 ASHISH E05 MUMBAI
E02(a) TABLE SURESH E05 MUMBAI
(b) DEFAULT
(c) CHECK
46. i.

ii.
ITEM_NAME MAX(PRICE) COUNT(*)
Personal Computer 37000 3
Laptop 57000 2

CNAME MANUFACTURER
N Roy PQR
R Singh
iii. XYZ
R Pandey COMP
C Sharma PQR
K Agarwal ABC

iv.
ITEM_NAME PRICE*100
Personal Computer 3500000
Laptop 5500000

City
47. (i)Delhi
SELECT SUM (PERIODS), SUBJECT FROM
Mumbai GROUP BY SUBJECT;
SCHOOL
Bangalore
(ii) SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN WHERE
DESIGNATION = ‘COORDINATOR’ AND SCHOOL.CODE=ADMIN.CODE;

(iii) SELECT TEACHERNAME, DOJ FROM SCHOOL ORDER BY CODE


DESC;

(iv) SELECT TEACHERNAME FROM SCHOOL WHERE DOJ LIKE ‘%2000’;


48. i. CREATE DATABASE SCHOOL;
ii. USE SCHOOL
create table Fees
(
Rollno numeric(5),
Name varchar(20),
Class varchar(20),
Fee Numeric(7,2),
PayDate Date,
Primary Key(Rollno, Class)
);
iii. SHOW TABLES
49. i. INSERT INTO FEES VALUES(1201, ‘Akshay’, ‘12th', 350, ‘2019-06-24’);
ii. UPDATE TABLE FEES SET FEE = FEE+50 WHERE CLASS=’12th’;
iii. DELETE FROM FEES WHERE ROLLNO =1212;
iv. d) DESCRIBE
50. i. UPDATE CLIENT SET Qtr2 = 200, Qtr3 = 600, Total =
Qtr1+Qtr2+Qtr3 WHERE Client_ID = ‘C660’;
ii. DELETE FROM CLIENT WHERE Total between 500 AND 900;
iii. ALTER TABLE CLIENT MODIFY ClientName VARCHAR(20) NOT NULL;
iv. ALTER TABLE CLIENT MODIFY DROP Total;

Interface of Python with an SQL database

Connecting SQL with Python


A Python library - mysql connector is required which provides connectivity from Python to
Mysql. There are mainly six steps that must be followed in Python environment to create a
database connectivity application. Steps for Creating Database Connectivity Applications:-

1. Import the package required for database access.


2. Open a connection to database.
3. Create a cursor instance.
4. Execute a query.
5. Extract data from result set or make the changes permanent.
6. Clean up the environment.

To establish the connection, write codes in script mode:


1. Import the Library
import mysql.connector
2. connect() statement to create a connection to the Mysql server and returns a Mysql
connection object mydb and pass three parameters, if required then also pass database
parameter.
mydb=mysql.connector.connect(host='localhost',user='root',passwd='password')
3. Creating cursor object of a class cursor which allows python code to execute sql commands.
mycursor=mydb.cursor()
4. execute() statement with sql query to execute SQL query from
python. mycursor.execute(“sql query”)
5. To read the data from the table of database using fetchone()/ fetchmany()/ fetchall()
methods as per requirement and store in a resulset.
myresult = mycursor.fetchall()

To save the current transactions of inserting, updating and deleting data we use:
mydb.commit()
6. close() to close the connection and clean up the environment
mydb.close()

Code For Creating A Mysql Database Through Python


import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="john", password="john")
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")

Code For Creating A Table In Mysql Through Python


import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="john",password="john",
database="mydatabase")
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address
VARCHAR(255))")

Code For Inserting Data In A Mysql Table Through Python


import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="john",password="john",
database="mydatabase")
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("Mary", "ABC")
mycursor.execute(sql, val)
mydb.commit()

Code For Displaying Data From A Mysql Table Through Python


import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="john", password="john",
database="mydatabase”)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)

Code For Deleting A Record From Mysql Table Using Python


import mysql.connector
mydb =
mydb = mysql.connector.connect(host="localhost", user="john",password="john",
database="mydatabase")
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE name = 'XYZ'"
mycursor.execute(sql)
mydb.commit()

Code For Updating A Record From Mysql Table Using Python


import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="john",password="john",
database="mydatabase")
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 123'"
mycursor.execute(sql)
mydb.commit()

mycursor.rowcount: To count total number of records affected by the execute method.


print(mycursor.rowcount)
Mind Map – Python MySql Connectivity

1 Mark Questions (MCQ)

1. To establish a connection with MySQL from Python which of the following functions is used?
(a) connection()
(b) connect()
(c) open()
(d) cursor()

2. execute() method can execute .


(a) DDL statements
(b) DML statements
(c) DDL and DML statements.
(d) Select statement only

3. To establish a connection between Python and sql database, connect() is used. Which of
the following arguments may not necessarily be given while calling connect()?
(a) host
(b) database
(c) user
(d) password

4. What is the purpose of the `rowcount` attribute in Python-Mysql database connectivity?


(a) Number of rows affected by the last executed command
(b) Total number of rows in the database
(c) Total number of columns in the database
(d) Number of tables in the database
5. Which method is used to retrieve N number of records
(a) fetchone()
(b) fetchall()
(c) fetchmany()
(d) fetchN()

6. To make the changes made by any SQL Queries permanently in database, which function is
used after execution of the query?
(a) save()
(b) commit()
(c) execute()
(d) dump()

7. How is dynamic insertion of values achieved in SQL queries?


(a) Using execute()
(b) Using dynamicValues()
(c) Using ‘%s’ format specifier or format()
(d) Using insertValues()
8. it is a pointer or iterator which points towards the resultset of the SQL query.
(a) cursor
(b) rset
(c) temp
(d) None of these

9. To get all the records from result set, you may use .
(a) cursor.fetchmany()
(b) cursor.fetchall()
(c) cursor.fetchone()
(d) cursor.execute()

10. Which of the following is not a valid method to fetch records from database in python.
(a) fetchmany()
(b) fetchone()
(c) fetchmulti()
(d) fetchall()

11. Which attribute of cursor is used to get number of records stored in cursor (Assumeg cursor
name is mycursor)?
(a) mycursor.count
(b) mycursor.row_count
(c) mycursor.records
(d) mycursor.rowcount

12. Which of the following package must be imported in Python to create a database connectivity
application?
(a) mysql.connector
(b) mysql.connect
(c) sql.connector
(d) sql.execute

13. Which of the following method reflects the changes made in database permanently?
(a) <connection>.done()
(b) <connection>.final()
(c) <connection>.reflect()
(d) <connection>.commit()

14. Which method of cursor class is used to fetch limited rows from the table?
(a) cursor.fetchsize(SIZE)
(b) cursor.fetchmany(SIZE)
(c) cursor.fetchall(SIZE)
(d) cursor.fetchonly(SIZE)

15. Which method of cursor class is used to get the number of rows affected after any of
the Insert/update/delete database operation executed from Python?
(a) cursor.rowcount
(b) cursor.getaffectedcount
(c) cursor.rowscount
(d) cursor.rcount

16. Which of the following component acts as a container to hold the data returned from the query:
(a) table
(b) cursor
(c) resultset
(d) container

17. To get the next record from the result set, we may use .
(a) cursor.fetch(next)
(b) cursor.fetchmany()
(c) cursor.fetchall()
(d) cursor.fetchone()

18. SQL command is passed to which function to run after establishment of the
connection between python and database
(a) cursor()
(b) execute()
(c) connection()
(d) fetchall()

19. Which of the following function is used to close the connection between python and database?
(a) cursor.close()
(b) is.close()
(c) connection.close()
(d) execute.close()

20. Which is the correct statement about fetchone()


(a) Fetch the next row of a query result set, returning a single tuple, or None when no more data is
available
(b) Fetch the First row of a query result set, returning a single tuple, or None when no more data is
available
(c) Fetch the current row of a query result set, returning a single tuple, or None when no more data
is available
(d) None of the above
Ans:
1 (b)
2 (c)
3 (b)
4 (a)
5 (c)
6 (b)
7 (c)
8 (a)
9 (b)
10 (c)
11 (d)
12 (a)
13 (d)
14 (b)
15 (a)
16 (c)
17 (d)
18 (b)
19 (c)
20 (a)

2 Marks Questions
1. Which method we use to establish the connection and clear the connection?
Ans: connect() and close() methods with connection object.

2. Which statement we use to access the MySQL module?


Ans: import mysql.connector

3. What are the difference between fetchone() and


fetchmany()? Ans: fetchone(): It will return one record from the
result set.
fetchmany(n): It will return number of records as per value of n and by-default only one record.

4. How can you use Python with MySQL?


Ans: Python can be used with MySQL in a number of ways. One way is to use the mysql.connector
python library, which is a MySQL driver written in Python. This library can be used to connect to
a MySQL database and perform various operations, such as creating and executing SQL queries.

5. What is a cursor in the context of MySQL?


Ans: A cursor is a pointer that points to a specific location in a database table. In MySQL,
cursors are used to iterate through the rows of a table and retrieve data from them.

6. What’s the difference between autocommit and commit?


Ans: Autocommit is a database feature that automatically commits changes to the database as soon
as they are made. This means that changes are immediately visible to other users and there is no
need to explicitly call the commit() method. Commit, on the other hand, is a database feature that
allows changes to be made to the database and then explicitly committed by the user. This allows
the user to control when changes are made visible to other users.

7. How can you check if a table exists in MySQL?


Ans: You can check if a table exists in MySQL by using the SHOW TABLES command. This will
show you a list of all the tables in the database. If the table you are looking for is not in the list,
then it does not exist.

8. How do you disconnect from the database?


Ans: Use the close() method. db.close() closes the connection from the database, where db is connection
object.

9. What is database connectivity?


Ans: Database connectivity refers to connection and communication between an application and a
database system.

10. What is connection? What is its role?


Ans:A Connection (represented through a connection object) is the session between the application
program and the database. To do anything with database, one must have a connection object.

3 Marks Questions
1. What is a result set? Give example with coding.
Ans: A result set refers to a logical set of records that are fetched from the database by executing a
query and made available to the application-program.
Eg: myresult = mycursor.fetchall()

2. Which package must be imported in Python to create a database connectivity application? Give
example with coding.
Ans:There are multiple packages available through which database connectivity applications can be
created in Python. One such package is mysql.connector.PyMySQL, mysqlclient, etc. can also
be used for connectivity.
Eg: import mysql.connector

3. Explain the following result retrieval methods:-


(a) fetchone()
(b) rowcount
(c) fetchall ()
Ans: (a) fetchone() :- The fetchone() method will return only one row from the result set in the
form of tuple containing a record.
(b) rowcount() :- cursor.rowcount that always return how many records have been
retrieved so for using any of the fetch..() methods.
(c) fetchall() :- The fetchall() method return all the rows from the result set in the form of
a tuple congaing the records.

4. Write the python script to read the whole data from the table emp and display all the records.
Ans: import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="school")
print (mydb)
mycursor=mydb.cursor()
numrow=mycursor.execute("select * from student")
print(mycursor.fetchall())
mydb.close()

5. Write the main difference among fetchone(),fetchmany() and


fetchall(). Ans: fetchone() fetches a single record or row from the
resultset.
fetchmany () method returns blocks of results according to a set limit. It will fetch n records at a time
from the table.
fetchall() fetches all the records or rows at a time from the table.

4 Marks : Case Based Questions

1. The code given below inserts following record in to a table EMPLOYEE


EMPNO – Integer
ENAME – string
SALARY -
Integer BONUS -
Integer DEPTID –
string

Help your friend Sonia in writing the following missing statements to complete the code:-

import________________# Statement1
mydb=mysql.connector.connect(host="localhost",user="root",passwd='root',database="class12")
mycursor=_______________# Statement 2
mycursor.execute("INSERT INTO EMPLOYEE VALUES(114,'BP Singh',56400,800,'D01')")
# Statement 3
print(mycursor.rowcount, "Record
inserted")
# Statement 4

Ans:
Statement 1: mysql.connector
Statement 2: mydb.cursor()
Statement 3: mydb.commit()
Statement 4: mydb.close()

2. Avni is trying to connect Python with MySQL for her project. Help her to write the
python statement on the following:
i. Name the library, which should be imported to connect MySQL with Python.
ii. Name the function, used to run SQL query in Python.
iii. Name the function required to make the changes permanent.
iv. Name the fuction to clear the environment.

Ans:
i. mysql.connector
ii. execute()
iii. commit()
iv. close()

3. Your friend Jagdish is writing a code to fetch data from a database Shop and table name
Products using Python. He has written incomplete code. You have to help him to write complete
code: import as m # Statement-1
object1 = m.connect(host="localhost", user="root", password="root", database="Shop")
object2 = object1. # Statement-2
query = '''SELECT * FROM Products WHERE NAME LIKE "A%";'''
object2__________(query) # Statement-3
.close() # Statement-4

Ans:
Statement 1: mysql.connector
Statement 2: cursor()
Statement 3: execute()
Statement 4: object1

4. The code given below reads the following record from Table named Employee and display
those record salary >= 30000 and <= 90000:
Empno – integer
EName – string
Desig – integer
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is Password
The table exists in a MYSQL database named Bank.

Write the following missing statements to complete the code on behalf of your friend Sandeep:
Statement 1 – to form the cursor object
Statement 2 – to query string.
Statement 3 - to execute the query that extracts records of those Employees whose salary >=30000
and <=90000.
Statement 4 - to close the connection.
import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='Password',database='bank')
mycursor=__________________# statement1
mycursor_________________#statement 2
data=____________________# statement 3
for x in data:
print(x)
# statement 4

Ans:
Statement 1: mydb.cursor()
Statement 2: execute('''SELECT * FROM Employee WHERE salary >= 30000 and salary <=
90000;''')
Statement 3: mycursor.fetchall()
Statement 4: mydb.close()

5. The code given below inserts the following record in the table Emp:

Empno – integer
EName – string
Designation – integer
Salary – integer
Bonus - Integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is tiger
The table exists in a MYSQL database named Employee.
The details (Empno, EName, Designation, Salary and Bonus) are to be accepted
from the user.
Help your friend in writing the following missing statements to complete the code:
Statement 1 – to create a connection
Statement 2 – to form the cursor object
Statement 3 – to execute the command that inserts the record in the table Emp.
Statement 4 - to add the record permanently in the database
import mysql.connector as mysql
def sql_data():
mycursor=__________________#Statement 1
eno=int(input("Enter Employee Number: "))
Ename=input("Enter Employee Name: ")
Designation=input("Enter Designation: "))
Salary=int(input("Enter Salary: "))
Bonus=int(input("Enter Bonus: "))
querry="insert into emp values({},'{}',{},{})".format(eno,ename,designation,bonus)
#Statement 2
# Statement 3
print("Employee Data Added
successfully")

Ans:
Statement 1: con1= mysql.connect(host="localhost",user="root", password="tiger",
database="Employee")
Statement 2: con1.cursor()
Statement 3: mycursor.execute(querry)
Statement 4: con1.commit()

5 Marks Questions

1. Write the steps to perform an Insert query in database connectivity application. Table Student
values are rollno, name, age (10,’Ashok’,26).

Ans: import mysql.connector as mydb


conn= mydb.connect(host=”localhost”, user=”root”, passwd=”1234”, database="school")
cur=conn.cursor()
cur.execute(“INSERT INTO student
values(10,’Ashok’,26);”) cur.commit()

2. Observe the following python code and answer the


questions: import mysql.connector as___#Statement 1
con = c.connect(host="localhost", user="root", passwd="",
database="test") mycursor= #Statement 2
mycursor.execute(" CREATE TABLE studentinfo (name VARCHAR (30), age INT(3)")
sql = """INSERT INTO studentinfo( name, age) VALUES ('Ashok',17) """
#Statement 3
#Statement 4
#Statement 5

i) Write the python statement to give appropriate alias name in statement1.


ii) Write the python statement to establish the database cursor as statement2.
iii) Write the python statement to insert the row into the table as statement 3 by using the
string ‘sql’ given above.
iv) Write the python statement to make the changes permanent.
v) Write the python statement to clear the environment.

Ans:
Statement 1: c
Statement 2: con.cursor()
Statement 3: mycursor.execute(sql)
Statement 3: mycursor.commit()
Statement 3: con.close()
3. Write the python function to accept the name as parameter and find out whether record
present in the table or not. Table Student columns are rollno, name, age.

Ans: import mysql.connector


def check_name(name):
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",
database="school")
cur=mydb.cursor()
cur.execute("select * from student")
s=cur.fetchall()
for k in s:
if((k[1]==name)):
print("Record Found",k)
break

4. Observe the codes given below and fill in the blanks:-


# statement 1
mydb = mycon.connect( host="localhost", user="yourusername", password="yourpassword",
database="mydatabase" )
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway No. 21")
mycursor.execute(sql, val)
# statement 2
mycursor____________("SELECT * FROM customers") # statement 3
myresult =__________________________________# statement 4
for x in myresult:
print(x)
.close() #statement 5

Ans:
Statement 1: import mysql.connector as mycon
Statement 2: mycursor.commit()
Statement 3: execute
Statement 4: mycursor.fetchall()
Statement 5: mydb

5. The Code given below is deleting a record from table EMPLOYEE.


Fill in the blanks to complete the code
import mysql.connector
mydb=__________(host="localhost",user="root",passwd='root',database="class12") #statement 1
mycursor=______________#statement 2
("DELETE FROM EMPLOYEE WHERE EMPNO=114") # statement 3
# statement 4
# statement 5
Ans:
Statement 1: mysql.connector.connect
Statement 2 mydb.cursor()
Statement 3: mycursor.execute
Statement 4: mydb.commit()
Statement 5: mydb.close()

You might also like