Identifying Python Code Errors
Identifying Python Code Errors
1. KEYWORDS
Predefined words with special meaning to the language processor; are reserved for special
purposes and must not be used as normal identifier names.
Example - True, for, if, else, elif, from, is, and, or, break, continue, def, import, in, while, False,
try, finally, except, global, etc.
2. IDENTIFIERS
Python Identifier is a name used to identify a variable, function, class, module or other object.
The rules for creating Identifiers :
Start with the alphabet or underscore. Followed by digits or more letters
Python keyword cannot be used as an Identifier.
Identifier should not contain special characters except underscore.
Identifiers are unlimited in length.
Some valid identifiers are: Myfile, MYFILE, Salary2021, _Chk ,First_Number
Invalid Identifies are: [Link], break, 2021salary, if#, First Number
3. LITERALS
Data items that have a fixed value.
String Literals: are sequence of characters surrounded by quotes (single, double or triple)
S1=”Hello” S2=”Hello” S3=”””Hello”””
Python allows nongraphic characters in string values. E.g. \r,\n,,\a,\b,\u,\v
Numerical Literals: are numeric values in decimal/octal/hexadecimal form. D1=10
D2=0o56 (Octal) D3=0x12 (Hex)
Floating point literals: real numbers and may be written in fractional form (0.45) or exponent
form (0.17E2).
Complex number literal: are of the form a+bJ, where a, b are int/floats and J(or i) represents
−1 i.e. imaginary number. Ex: C1=2+3j
Boolean Literals: It can have value True or False. Ex: b=False
Special Literal None: The None literal is used to indicate absence of value.
Ex: c=None
4. OPERATORS
Tokens that trigger some computation/action when applied to variables and other objects in an
expression. These are
Arithmetic : +, -, *, /, %, **, //
Bitwise : &, ^, |
1
Identity : is, is not
Relational : >, >=, <, <=,!=, ==
Logical : and, or
Assignment :=
Membership : in, not in
Arithmetic assignment: /=, +=, -=, *=, %=, **=, //=
5. PUNCTUATORS
Punctuators are symbols that are used to organize sentence structure. Common punctuators used
in
Python are: ‘ “ # \ ( ) [ ] { } @ , : .
DATA TYPES
Means to identify type of data and set of valid operations for it. These are
1. NUMBERS
To store and process different types of numeric data: Integer, Boolean, Floating-point, Complex no.
2. STRING
Can hold any type of known characters i.e. letters, numbers, and special characters, of any known
scripted language. It is immutable datatype means the value can’t be changed at place. Example:
“abcd”, “12345”,”This is India”, “SCHOOL”.
-6 -5 -4 -3 -2 -1
S C H O O L
0 1 2 3 4 5
3. LISTS
Represents a group of comma-separated values of any datatype between square brackets.
Examples:
L1=list()
L2=[1, 2, 3, 4, 5]
L3=[5, ‘Neha’, 25, 36, 45]
L4=[45, 67, [34, 78, 87], 98]
In list, the indexes are numbered from 0 to n-1, (n= total number of elements). List also supports
forward and backward traversal. List is mutable datatype (its value can be changed at place).
4. TUPLE
Group of comma-separated values of any data type within parenthesis. Tuple are immutable i.e.
non-changeable; one cannot make change to a tuple.
t1=tuple()
t2=(1, 2, 3, 4, 5)
t3=(34, 56, (52, 87, 34), 67, ‘a’)
5. DICTIONARY
The dictionary is an unordered set of comma separated key:value pairs, within { }, with the
requirement that within a dictionary, no two keys can be the same. Following are some examples of
dictionary:
2
d1=dict()
d2={1:’one’, 2:’two’, 3:’three’}
d3={‘mon’:1, ‘tue’:2, ‘wed’:3}
d4={‘rno’:1, ‘name’:’lakshay’, ‘class’:11}
In dictionary, key is immutable whereas value is mutable.
STRING
In Python, a string literal is a sequence of characters surrounded by quotes.
Python supports single, double and triple quotes for a string
A Character literal is a single character surrounded by single or double quotes.
The value with triple-quote ’’’ ‘’’ is used to give multiline string literal.
Example:
strings = “This is Python”
char = “C”
multiline_str = ‘’’This is multiline string with
more than one line code.’’’
print(strings)
print(char)
print(multiline_str)
STRING REPLICATION
When a string is multiplied by a number, string is replicated that number of times.
Note: Other datatype – list and tuple also show the same behavior when multiplied by an integer
number.
>>> STR=’Hi’
>>> print(STR*5)
>>>HiHiHiHiHi
>>> L=[1, 2]
>>> print(L*5)
>>> [1,2,1,2,1,2,1,2,1,2]
>>> t=(1, 2)
>>> print(t*5)
>>> (1,2,1,2,1,2,1,2,1,2)
STRING SLICE
String Slice refers to part of a string containing some contiguous characters from the string. The
syntax is str_variable[start:end:step].
start: from which index number to start
end: upto (end-1) index number characters will be extracted
step: is step value. (optional) By default it is 1
Example : Suppose S='KENDRIYA'
Backward Index no -8 -7 -6 -5 -4 -3 -2 -1
Character K E N D R I Y A
Forward Index no 0 1 2 3 4 5 6 7
LISTS
A List is a standard data type of python that can store a sequence of values belonging to any data
type. List elements are enclosed with square brackets. Lists are mutable i.e., you can change
elements of a list in place.
CREATING LIST
1) Empty List
>>>L=[] OR >>> L=list()
2) From existing sequence
>>>st=’HELLO’
>>> L1=list(st) # from a string
>>> t=(1, 2, 3)
>>> L2=list(t) # from a tuple
3) from Keyboard entering element one by one
>>> L=[]
>>> for i in range(5):
n=int(input(‘Enter a number :’))
[Link](n)
TRAVERSING A LIST
>>> L=[1, 2, 3, 4, 5]
>>> for n in L:
print(n)
JOINING LISTS
>>> L1=[1, 2, 3]
>>> L2=[33, 44, 55]
>>> L1 + L2 # output: [1, 2, 3, 33, 44, 55]
APPENDING ELEMENT
>>> L=[10, 11, 12]
>>>[Link](20) # Will append 20 at last
>>> L # output : [10, 11, 12, 20]
>>>[Link]([4,5])
# Appended data will be treated as a single element
>>> L # output: [10, 11, 12, 20, [4, 5]]
5
EXPANDING LIST
>>> L=[10, 11, 12]
>>>[Link]([44,55])
# Will extend given item as separate elements
>>> L # output: [10, 11, 12, 44, 55]
UPDATING LIST
>>> L=[10, 11, 12]
# Suppose we want to change 11 to 50
>>> L[1]=50
>>> L # output: [10, 50, 12]
DELETING ELEMENTS
del List[index]# Will delete the item at given index del List[start : end]# Will delete from index no
start to (end-1)
>>> L=[x for x in range(1,11)]
>>> L # list is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> del L[2:5]
>>> L # now list is [1, 2, 6, 7, 8, 9, 10]
TUPLES
The Tuples are depicted through parenthesis or Tuples are sequence of elements enclosed within
parenthesis. Tuples are immutable sequences i.e., you cannot change elements of a tuple in a place
T=()
T=(value,…)
6
Where <sequence> can be strings, lists and tuples.
>>>T1= tuple(‘hello’)
>>>T1
(‘h’,’e’,’l’,’l’,o’)
>>> L=[23,25,30,40]
>>> t2=tuple(L)
>>> t2
(23,25,30,40)
Traversing a Tuple
T=(‘s’,’c’,’h’,’o’,’o’,’l’)
for a in T:
print(T)
The above loop will produce output as
s
c
h
o
o
l
Joining Tuples
The + operator, the concatenation operator, when used with two tuples, joins two tuples.
>>>T1=(10,20,30)
>>>T2 =(50,60,70)
>>>T1+T2
(10,20,30,50,60,70)
DICTIONARY
Dictionaries are a collection of some unordered key:value pairs; are indexed by keys (keys must be
of any non-mutable type). Dictionaries are mutable, unordered collections with elements.
<dictionary-name> = {<key>:<value>,<key>:<value>…}
TRAVERSING A DICTIONARY
>>> d={1:’one’, 2:’two’, 3:’three’}
>>> for key in d:
print(key, “:”, d[key], sep=’\t’)
1 : one 2 : two 3 : three
OTHER FUNCTIONS
Function with Syntax Description
<dict>.get() To get the value of the given key
<dict>.items() To get all the items(key : value pairs) of the dictionary
<dict>.keys() To get all the keys of the dictionary
<dict>.values() To get all the values of the dictionary
<dict>.fromkeys(<keysequence>, To create a new dictionary from a sequence containing all the
[<value>]) keys and a common value, which will be assigned to all keys
<dict>.setdefault() To insert a new key : value pair
<dict>.update() To update or add key : value pair from dictionary
<dict>.copy() Returns a shallow copy of the dictionary
del <dict> To delete the whole dictionary <dict>
<dict>.pop(key,<value>) Removes and returns the dictionary element associated to
passed key
<dict>.popitem() Returns the deleted key:value pair
<dict>.clear() Removes all items from the dictionary and empty dictionary
objects remains.
MCQ
[Link] developed Python?
(A)Ritche (B) Guido Van Rossum (C)Bill Gates (D) Sunder Pitchai
[Link] symbol is used to print more than one item on a single line.
(A)Semicolon(;) (B) Dollor($) (C)comma(,) (D) Colon(:)
18. Python uses the symbols and symbol combinations as _____ in expressions
a) literals b) keywords c) delimiters d) identifiers
9
27. What is the output of the following snippet?
T=1
while T:
print(True)
break
(A)False (B) True (C)0 (D)no output
29. A loop place within another loop is called as ____________ loop structure
a) entry check b) exit check c) conditional d) nested
30. Which statement is used to skip the remaining part of a loop and start with next iteration?
a) condition b) continue c) break d) pass
33. Which of the following function is used to count the number of elements in a list?
(a)count() (b)find () (c)len() (d)index()
36. Which of the following Python function can be used to add more than one element within an
existing list?
(a)append() (b)append_more (c)extend() (d)more()
10
42. Which of the following is used to delete known elements where the index value is known?
(a)del (b)delete (c)remove() (d)del()
43. Which function is used to convert the result of range() function into list?
(a)convert() (b)range() (c)list() (d)listrange()
46. While creating a tuple from a list, the element should been closed within
(a)[] (b)() (c){} (d)[()]
48. Which of the following is the output of the following python code?
str1="Puducherry"
print(str1[::-1])
(a) Puducherry (b) Pdcry (c) yrhudp (d) yrrehcuduP
49. What will be the output of the following code?
str1 = "Chennai Schools"
str1[7] = "-"
(a) Chennai-Schools (b) Chenna-School (c) Type error (d) Chennai
55. Which of the following formatting character is used to print exponential notation in upper case?
(a) %e (b) %E (c) %g (d) %n
56. Which of the following is used as placeholders or replacement fields which get replaced along
with format( ) function?
(a) { } (b) <> (c) ++ (d) ^^
62. Which function returns the number of sub strings occurs within the given range?
a) count() b) range() c) return() d) format()
[Link] will be the output of following Python code?
d1={“a”:10,”b”:2,”c”:3}
str1=””
for i in d1:
str1 =str1+str(d1[i] +” “
str2=str1[:-1]
print(str2[::-1]
a) 3,2 b) 3,2,10 c) 3,2,01 d) Error
64. Which of the following will raise an error if the given dictionary is empty?
a) del b) pop() c) popitem() d) all of these
[Link] value is assigned to keys, if no value is specified with the fromkeys() method?
a) 0 b) 1 c) None d) any of these
ASSERTIONS AND REASONS
In the following questions, a statement of assertion (A) is followed by a statement of reason (R).
Mark the correct choice as:
(a) Both A and R are true and R is the correct explanation of A.
(b) Both A and R are true but R is not the correct explanation of A.
(c) A is true but R is false (or partly true).
(d) A is false (or partly true) but R is true.
(e) Both A and R are false or not fully true.
1. Assertion: Assigning a new value to an int variable creates a new variable internally.
Reason: The int type is immutable data type of Python.
5. Assertion: The break statement can be used with all selection and iteration statements.
Reason: Using break with an if statement is of no use unless the if statement is part of a looping
construct.
6. Assertion: The break statement can be used with all selection and iteration statements.
Reason: Using break with an if statement will give no error.
7. Assertion: Lists and Tuples are similar sequence types of Python, yet they are two different
datatypes.
Reason: List sequences are mutable and Tuple sequences are immutable.
12
8. Assertion: Modifying a string creates another string internally but modifying a list does not create
a new list.
Reason: Strings store characters while lists can store any type of data.
9. Assertion: Modifying a string creates another string internally but modifying a list does not create
a new list.
Reason: Strings are immutable types while lists are mutable types of Python.
10. Assertion: Dictionaries are mutable, hence its keys can be easily changed.
Reason: Mutability means a value can be changed in place without having to create new
storage for the changed value.
11. Assertion Dictionaries are mutable but their keys are immutable.
Reason: The values of a dictionary can change but keys of dictionary cannot be changed
because through them data is hashed.
13. Assertion: The documentation for a Python module should be written in triple-quoted strings.
Reason: The docstrings are triple-quoted strings in Python that are documentation when help
<module> command is issued.
14. Assertion: After importing a module through import statement, all its function definitions,
variables, constants etc. are made available in the program.
Reason: Imported module's definitions do not become part of the program's namespace if
imported through an import <module> statement.
15. Assertion: If an item is imported through from <module> import <item> statement then you do
not use the module name along with the imported item.
Reason: The from <module> import command modifies the namespace of the program and
adds the imported item to it.
16. Assertion: Python's built-in functions, which are part of the standard Python library, can directly
be used without specifying their module name.
Reason: Python's standard library's built-in functions are made available by default in the
namespace of a program.
18. Assertion: Python offers two statements to import items into the current program : import and
from<module>import, which work identically.
Reason. Both import and from <module> import bring the imported items into the current
program.
Answers
1. a 2. c 3. d 4. a 5. a 6. b 7. a 8. c 9. a 10. d 11. a 12. a 13. A
14. b 15. a 16.a 17.b 18.e
13
Question and Answers
2. Given the lists L=[1, 3, 6, 82, 5, 7, 11, 92], write the output of print(L[2:5]).
Ans: [6,82,5], as it will start from index no 2 to (5-1) i.e. 4.
5. Declare a dictionary Colour, whose keys are 1, 2, 3 and values are Red, Green and Blue
respectively.
Ans : Colour={1:'Red', 2:'Green', 3:'Blue'}
7. Name the built-in mathematical function / method that is used to return an absolute value of a
number.
Ans : Abs()
14
12. STR=”VIBGYOR”
colors=list(STR) >>>del colors[4]
>>>[Link]("B")
>>>[Link](3)
>>>print(colors)
Ans : It will create a list as colors=['V', 'I', 'B', 'G', 'Y', 'O', 'R']. del colors[4] will delete the element
at index no 4 i.e. so list will be ['V', 'I', 'B', 'G', 'O', 'R']. [Link]("B") will remove ‘B’. so list
will be ['V', 'I', 'G', 'O', 'R']. [Link](3) will extract ‘O’. So finally colors will be ['V', 'I', 'G', 'R'].
15
20. Write a program to check if a number is Positive, Negative or zero.
num = int(input("Enter the number "))
if num > 0:
print(" The given number is Positive")
elif num ==0:
print("The given number is Zero")
else:
print("The given number is Negative")
21. Write a program to display
A
A B
A BC
ABC D
A B C DE
Program:
for i in range (65, 70):
for j in range (65, i+1):
print(chr(j), end=' ')
print("")
22. Write a program to display all 3 digit even numbers.
for i in range(100,1000,2):
print(i,end=’\t’)
23. Write a python program to display following pattern
*****
****
***
**
*
for i in range(5,0,-1):
for j in range(1,i+1,1):
print("*",end=" ")
print("\n")
Example
Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F',95.3)
('Saisri', 'XII-G', 93.8)
32. Write a program to create a third dictionary from two dictionaries having some common
key, in way so that the values of common keys are added in the third dictionary.
dct1 = { ‘1’:100,’2’:200,’3’:300}
dct2 = { ‘1’:300,’2’:200,’5’:400}
dct3=dict(dct1) # create a new dictionary dct3
[Link](dct2)
for i, j in [Link]():
fox x,y in [Link]():
if i == x:
dct3[i] = (j+y)
L= ['im', 'ur']
for i in L:
print([Link]())
print (L)
Output
IM
UR
['im', 'ur']
34. What is the output of the following code?
i=9
while True:
if (i+1)% 4 == 0:
break
print(i, end = '')
i += 1
Output : 9 10
18
35. What is the output of the following code?
i=4
while True:
if i% 0o7 == 0:
break
print(i, end = '')
i += 1
Output: 4 5 6 (Note. 007 is a valid integer, written in octal forming)
True = False
while True:
print (True)
True = True
The above code will give Error because keyword True has been used as variable (in first line of
code: True = False and in last line of the code: True=True). We cannot use keywords as variables
or any other identifiers.
[Link] the following code in Python after removing all syntax error(s). Underline each
correction done in the code.
Value = 30
for VAL in range(0, Value)
If val % 4 == 0:
print (VAL* 4)
Elseif val %5 == 0:
print (VAL + 3)
else
print (VAL + 10)
Corrected Code:
Value = 30
for VAL in range(0, Value): # Error 1 - colon missing
if val%4==0: # Error 2 - if should be in lower case
print (VAL*4)
elif val%5==0: # Error 3 - it should be elif
print (VAL+3)
else: # Error 4 - colon missing
print (VAL+10)
19
39. What is the output of the following codes?
x=’abcd’
for i in x:
print(i,end = ‘ ‘)
[Link]()
output: a b c d
x=’abcd’
for i in x:
print([Link](),end = ‘ ‘)
output: A B C D
20
FUNCTIONS
Block of statement(s) for doing a specific task.
Advantages of function:
Cope-up with complexity
Hiding details – Abstraction
Fewer lines of code - lessor scope for bugs
Increase program readability
BUILT-IN FUNCTION
Pre-defined functions available in Python.
Need not import any module (file).
Example of some built-in functions are:
str(), eval(), input(), min(), max(), abs(),
type(), len(), round(), range(), dir(), help()
MODULES
Module in Python is a file ([Link]) which contains the definition of variables and functions. A
module may be used in other programs. We can use any module in two ways
1. import <module-name>
2. from <module-name> import <func-name> Some well-known modules are: math, random,
matplotlib, numpy, pandas, datetime
USER-DEFINED FUNCTIONS
UDFs are the functions which are created by the user as per requirement.
After creating them, we can call them in any part of the program.
Use ‘def’ keyword for UDF.
ACTUAL AND FORMAL PARAMETER/ ARGUMENT
Formal Parameter appear in function definition
Actual Parameter appear in function call statement.
Example:
def findSum(a, b): # a, b formal parameter
print(‘The sum is ‘,(a+b))
#main-program
21
X, Y=10,30
findSum(X, Y) # X, Y are actual parameter
VARIABLE SCOPE
Arguments are local
Variable inside functions are local
If variable is not defined , look in parent scope
Use the global statement to assign to global variables
TYPES OF ARGUMENTS
Python supports four types of arguments:
1. Positional 2 Default 3. Keyword 4. Variable Length
1. POSITIONAL ARGUMENTS
Arguments passed to function in correct positional order. If we change the position of their order,
then the result will change.
>>> def subtract(a, b):
print(a - b)
>>> subtract(25, 10) # output: 15
>>> subtract(10, 25) # output: - 15
2. DEFAULT ARGUMENTS
To provide default values to positional arguments; If value is not passed,
then default values used.
def findSum(a=30, b=20, c=10):
print('Sum is ',(a+b+c))
def mySum(a=30, b=20, c):
print('Sum is ',(a+b+c))
#Error that non-default argument follows default arguments
#main-program
p, q, r =100, 200, 300
findSum(p,q,r) #output - Sum is 600
findSum(p,q) #output - Sum is 310
findSum(r) #output - Sum is 330
findSum(q,r) #output - Sum is 510
findSum() #output - Sum is 60
3. KEYWORD ARGUMENTS
we can pass arguments value by keyword, i.e. by passing parameter name to change the sequence
of arguments, instead of their position. Example:
def print_kv(kvnm, ronm):
,
print(kvname,'comes under',roname,'region')
#main-program
print_kv(kvnm='Rly Gandhidham', ronm='Ahmd')
print_kv(ronm='Jaipur', kvnm='Bharatpur')
23
The functions that return some result in terms of a value, it uses return statement as per syntax:
return<value>
The value returned may be any one of the following: a literal, a variable, an expression
For example
return 5
return 6+4
return a
return a**5
return a/6
def sum(a,b):
s=a+b
return s
result = sum(10,5)
def ret(x,y,z):
return x**x,y**y,z**z
T1=ret(5,6,7) #T1 is tuple receives multiple returned values
Print(T1)
String library
capitalize() Convert 1st letter to upper case
index(ch) Return index-no of 1st occurrence
isalnum() True, if entire string is (a-z, A-Z, 0-9)
isalpha() True, if entire string is (a-z, A-Z)
isdigit() True, if entire string is (0-9)
islower() True, if entire string is in lower
isupper() True, if entire string is in upper
len() Return length of the string
24
MCQ
1. A named blocks of code that are designed to do one specific job is called as
(a) Loop (b) Branching (c) Function (d) Block
13. What is the name given to that area of memory, where the system stores the parameters and
local variables of a function call?
a) heap b) storage area c) a stack d) an array
14. Pick one the following statements to correctly complete the function body in the given code
Snippet
def f(number):
#Missing function body
print(f(5))
a) return “number” b) print(number) c) print(“number”) d) return number
25
15. Which of the following function headers is correct?
a) def f(a=1,b): b) def f( a=1,b,c=2):
c) def f(a=1,b=1,c=2): d) def f(a=1,b=1,c=2,d):
19. What is a variable defined outside all the functions referred to as?
a) A static variable b) A global variable c) A local variable d) An automatic variable
21. What is the default return value for a function that does not return any value explicitly?
a) None b) int c) double d) null
22. Which of the following items are present in the function header?
a) function name only b) both function name and parameter list
c) parameter list only d) return value
3. Assertion: A parameter having a default in function header becomes optional in function call.
Reason: A function call may or may not have values for default arguments.
5. Assertion: A variable not declared inside a function can still be used inside the function if it is
declared at a higher scope level.
Reason: Python resolves a name using LEGB rule where it checks in Local, Enclosing, Global
and Built-in scopes, in the given order.
6. Assertion: A parameter having a default value in the function header is known as a default
parameter.
Reason: The default values for parameters are considered only if no value is provided for that
parameter in the function call statement.
26
7. Assertion: A function declaring a variable having the same name as a global variable, cannot
use that global variable.
Reason: A local variable having the same name as a global variable hides the global
variable in its function.
8 Assertion: If the arguments in a function call statement match the number and order of
arguments defined in the function definition, such arguments are called positional arguments.
Reason: During a function call, the argument list first contains default argument(s) followed by
positional argument(s).
9. Assertion: To use a function from a particular module, we need to import the module.
Reason: Import statement can be written anywhere in the program, before using a function
from that module.
Answers
1. a 2. b 3. b 4. a 5. a 6. b 7. a 8. c 9. b
27
Example:
c=1
def add():
print(c)
add()
Function blocks begin with the keyword “def” followed by function name and
parenthesis().
Any input parameters or arguments should be placed within these parentheses when define
a function.
The code block always comes after a colon (:) and is indented.
The statement “return [expression]” exits a function, optionally passing back an
expression to thecaller.
A “return” with no arguments is the same as returnNone.
9. What is the order of resolving the scope a name used in a function or a program?
The order of name resolution in Python is LEGB, i.e. Local namespace, Enclosing
namespace, Global namespace and Built-in namespace.
[Link] has the following code in Python. But he is confused in Built in function and
User defined function help him to find out built-in functions and user defined functions.
length = 5
width = 3
result = calculate_area(length, width)
print("Area of the rectangle:", result)
Built-in functions — These are pre-defined functions and are always available for use.
For example: In the above example, print(), len(), input() etc. are built-in functions.
User defined functions — These are defined by programmer. For example: In the above
example, calculate_area is a user defined function.
28
11. Consider the code below and answer the questions that follow:
def multiply(number1, number2):
answer = number1 * number2
return(answer)
print(number1,’times’,number2,’=’,answer)
output: multiply(5,5)
12. From the program code given below, identify the parts function header, function call,
arguments, parameters, function body, main program:
1. def processNumber(a,b):
2. c= a+b
3. return c
4.
5. x,y=54,65
6. res = processNumber(x,y)
Output:
150 # 50
150 # 100
100 # 70
29
14. Trace the following code and predict output produced by it.
1. def power(b,p):
2. y = b**p
3. return y
4.
5. def calcSquare(x):
6. a=power(x,2)
7. return a
8.
9. n=5
10. result = calcSquare(n) + power(3,3)
11. print(result)
Function headers i,ii and iv will cause error because non-default arguments cannot follow
default arguments.
16. Define three functions fun(), disp() and msg(), store them in a list and call them one by
one in a loop
def fun():
print(‘In fun’)
def disp():
print(‘In disp’)
def msg():
print(‘In msg’)
lst = [fun,disp,msg]
for fn in lst:
fn()
Output
In fun
In disp
In msg
30
17. Write a Python function to create and return a list containing tuples of the form (x,x 2,x3)
for all x between 1 and 20 (both included)
def generate_list():
lst=list()
for i in range(1,11):
[Link]((i, i**2,i**3))
return lst
newlst = generate_list()
print(newlst)
output:
[(1, 1, 1), (2, 4, 8), (3, 9, 27), (4, 16, 64), (5, 25, 125), (6, 36, 216), (7, 49, 343), (8, 64, 512), (9, 81,
729), (10, 100, 1000)]
def fun():
print('First function')
fun()
def fun():
print('Second function')
fun()
output:
First function
Second function
Do it by yourself
1 Write a function in python named SwapHalfList(Array), which accepts a list Array of numbers and
swaps the elements of 1st Half of the list with the 2nd Half of the list
Sample Input Data of the list:
Array= [ 100, 200, 300, 40, 50, 60]
Output Arr = [40, 50, 60, 100, 200, 300]
2. Write a function listchange(Arr) in Python, which def listchange(Arr): accepts a list Arr of numbers,
the function will replace the even number by value 10 and multiply odd number by 5.
Sample Input Data of the list is:
a=[10, 20, 23, 45]
listchange(a)
output : [10, 10, 115, 225] a=[10, 20, 23, 45]
[Link] a function HowMany(ID, VALUE) to count and display number of times the VALUE is present
in the list ID. For example, if the ID contains [115, 25, 65, 59, 74, 25, 110, 250] and the VALUE
contains 25, the function should print:
25 ound 2 times.
4. Write a program that defines a function remove_duplicate() to remove all duplicate entries from
the list that it receives.
31
5. Which of the following are valid return statements?
return(a,b,c)
return a + b + c
return a,b,c
7. How will you define a function containing three return statements, each returning a different type
of value?
[Link] a function LShift(Arr,n), which accepts a list Arr of numbers and n is a numeric value by
which all elements of the list are shifted to left.
Sample Input Data of the list
Arr= [ 10,20,30,40,12,11], n=2
Output:
Arr = [30,40,12,11,10,20]
32
EXCEPTION HANDLING
Errors that occur during Compilation or Interpretation are called Syntax Errors.
Compile-time errors are the errors resulting from a violation of a programming language’s
grammar rules. E.g., writing syntactically incorrect statements like
print (“hello” + 2)
will result in a compile-type error because of invalid syntax. All syntax errors are reported during
compilation.
Logical errors occur when the program runs completely but produces incorrect results or
behaves in unintended ways due to flaws in the logic or algorithm used.
Semantic Error occurs when a program runs without syntax errors but does not perform the
intended action or produce the expected results due to incorrect use or understanding of
language constructs, functions, or logic. Essentially, it's an error in the meaning or intention
behind the code, rather than a mistake in the code's syntax.
Run-time errors are the errors that occur during runtime because of unexpected situations.
Such errors are handled through exception routines of Python.
Errors that occur during execution are called Exceptions.
A well-defined mechanism of catching and preventing errors of any type that may occur during
the execution of the program is known as Exception Handling.
The concept of Exception handling is to write your source code (program) in such a way that
it raises some error flag every time goes wrong while executing the code in runtime. Exception
handling provides a way to detect, handle, and recover from errors, ensuring the program can
continue operating or terminate completely.
Key Components of Exception Handling in Python
try Block: This block contains the code that might throw an exception. It is where you place
the code that you want to monitor for errors.
except Block: This block contains code that executes if an exception is raised in the try
block. You can specify different except blocks to handle different types of exceptions.
else Block: This block, which is optional, executes if no exception was raised in the try
block. It is useful for code that should run only when no errors occur.
finally Block: This block, also optional, always executes regardless of whether an
exception was raised or not. It is commonly used for clean-up actions, such as closing files
or releasing resources.
raise: As a programmer, you can force an exception to occur through the raise keyword. It
allows you to explicitly generate exceptions, either built-in or custom-defined, and manage
error conditions more effectively.
assert statement is a debugging aid that tests a condition, If the condition is true, it does
nothing and your program just continues to execute. If false, it raises an AssertionError
exception with an optional error message.
33
MCQ:
11. What will be the output of the following Python code, if the time module has already been
imported?
4 = ‘3’
a) NameError b) IndexError c) ValueError d) TypeError
13. Compare the following two Python codes shown below and state the output if the input entered
in each case is -6?
CODE 1
import math
num = int(input(“Enter a number of whose factorial you want to find”))
print([Link](num))
CODE 2
num = int(input(“Enter a number of whose factorial you want to find”))
print([Link](num))
a) ValueError, NameError b) AttributeError, ValueError
c) NameError, TypeError d) TypeError, ValueError
18. Errors resulting out of violation of programming language’s grammar rules are known as
a) Compile error b) Logical error c) Runtime error d) Exception
1. Assertion: Exception handling is responsible for handling anomalous situations during the
execution of a program.
Reason: Exception handling handles all types of errors and exceptions
36
3. Assertion: Exception handling code is clear and block-based in Python.
Reason: The code where unexpected runtime exceptions may occur is separate from the code
where the action takes place when an exception occurs.
4. Assertion: No matter what exception occurs, you can always make sure that some common
action takes place for all types of exceptions.
Reason: The finally block contains the code that must be executed.
Answers
MCQs
1. d 2. c 3. d 4. d 5. b 6. d 7. c 8. a 9. c 10. b 11. d 12. b 13. a
14. c
15. b 16. d 17. b 18. a 19. b 20. a
True/False
1. False 2. True 3. False 4. True 5. True 6. False
Exceptions: Exceptions are raised when the program is syntactically correct, but the code results
in an error. This error does not stop the execution of the program; however, it changes the normal
flow of the program.
Example:
marks = 10000
a = marks / 0
print(a)
37
4. What are the advantages of Exception handling?
Exception handling separates error-handling code from normal code.
It clarifies the code and enhances readability.
It stimulates consequences as the error-handling takes place in one place and in one manner.
It makes for clear, robust, fault-tolerant programs.
5. “Every Syntax error is an exception but every exception cannot be a syntax error”. Justify
the statement.
An exception means the occurrence of some unexpected event. A syntax error occurs when
some language rules are violated, which is an unexpected event and hence can be termed
as an exception.
However, exception means the occurrence of unexpected events causing program disruption
during runtime, while syntax errors are caught during compile time only.
7. Identify the type of exceptions for the codes and input given below:
a) # input as “S”
x=int(input(“ Enter a number”))
b) for a in range(0,9):
print(20/a)
c) import myownmodule
d) x=8
print(X)
e) mylist=[2,3,4]
print(mylist[4])
f) import math
a = [Link](1000000,1000000)
g) filename=”[Link]”
open(“[Link]”,”r”)
9. Write a code where you use the wrong number of arguments for a method ( sqrt() and
pow()). Use the exception handling process to catch the ValueError exception.
import math
print ("This Program to test Invalid arguments for MATH functions ")
38
try:
num1 = int(input ("Enter the Positive Integer number "))
result1= [Link](num1)
print ("The square root of ",num1, " is ", result1)
except ValueError : # to enter only integers
print ("Please enter only Positive Integers ")
try:
num2= int(input("Enter Integer "))
result2 = [Link](num1, num2)
print (num1, " Power of ", num2, " is ", result2)
except ValueError : # to enter only integers
print ("Please enter only valid Integers ")
except :
print("You have entered invalid integer")
finally: # to be executed at the end
print("This Program Tested only Invalid arguments for Math functions 'sqrt' and 'pow' ")
OUTPUT
This Program to test Invalid arguments for MATH functions
Enter the Positive Integer number 25
The square root of 25 is 5.0
Enter Integer 3
25 Power of 3 is 15625.0
This Program Tested only Invalid arguments for Math functions 'sqrt' and 'pow'
Output:
10 100
20 400
30 900
40 1600
50 2500
Total Numbers processed 5
39
FILE HANDLING (Text, Binary and CSV)
File: A file is a named location on a secondary storage media like HDD where data are
permanently stored for reusability.
Need of File Handling: To store data in secondary storage for reusability. To access the data
[Link] perform different operations on file likes: open, read, write, search, update, close etc.
Types data files: (i) Text File (ii) Binary File (iii) csv file
Text File:A text file consists of human readable characters. Each line of a text file terminated By a
special character called the end of line (EOL). Default EOL used newline (\n).
Binary file: It made up of non-human readable characters and symbols. They represent the actual
content such as image, audio, video, exe file.
CSV File: A CSV (Comma Separated Value) format is one of the simplest and common way to store
tabular data. To represent a csv file, it must be saved with .csv extension. Comma is also a delimiter
which separates two files in a row 3
Modes of files:
Opening and closing a file:To open a file we use open() method and to close file, we use close()
method.
pickle module: we used in binary file for dump() and load() method respectively to write into a
file and read contents from the file.
Pickle module is used for serializing/pickling and de-serializing/unpickling any python object.
40
Pickling- It will convert python object into byte stream and unpickling convert byte stream into
python Object.
dump() method: It used to convert(pickling) python objects for writing data in a binary file.
Syntax: module [Link](dataobject,file object)
load(): It is used to load/read(unpickling) data from a file. Syntax:
storeobject=[Link](file object).
reader(): function is used to read the file, which returns an iterable reader object. The reader
object is then iterated using for loop to print the content of each row. [Link](file object)
function in default mode of csv file having comma delimiter.
writer (): The [Link](file object) function returns a writer object that converts the user’s data
into delimiter string.
Writerow():The string can later be used to write into CSV File using [Link]( )
function.
Writerows():If we need to write the content of 2‐Dimensional list into csv file, instead of using
writerow() function many times, we can write [Link]() func. Note: syntax for
accessing modules and methods respectively: import module name and Objectname=module
[Link] name()
Text file Methods: write (): writing a single string and returns number of characters being written.
writeline(): writing a sequence of(multiple)strings to a file and does not return the number of
characters written in the file.(Both functions use as [Link](single string/multiple string)
read (): It is used to read a specified number of bytes of data from a data file. [Link](n) where
n-no of bytes read, if we do not pass no argument or a negative number is specified in read () then
it read entire content of file.
readline([n]): It will read one complete line from a file where line terminate with (\n). if we pass as
an argument n then it read a specified number of bytes. If no argument pass or negative number
pass it read complete line. To read the entire file line by line using the readline() we use a for loop.
readlines(): It reads all the lines and returns the lines along with newline as a list of strings.
split (): If we want to display each word of a line separately as an element of a list. splitlines(): It is
used instead of split(), then each line is returned as element of a list.
SETTING OFFSETS IN A FILE: To access the data in random fashion then we use seek () and tell
() Method.
tell (): It returns an integer that specifies the current position of the file object in the file. [Link]()
and seek(): It is used to position the file object at a particular position in a file. [Link](offset
[, reference point]) where offset is the number of bytes by which the file object is to be moved and
reference point indicating the starting position of the file object. Values of reference point as 0-
beginning of the file, 1- current position of the file, 2- end of file.
A CSV (Comma Separated Value) format is one of the simplest and common way to store tabular
data. To represent a csv file, it must be saved with .csv extension.
csv file is used to store tabular data in a comma separated values. Each line of file is a data record.
Each record consists of one or more field separated by comma. (comma is separator). Comma is
also a delimiter which separates two files in a row
csv module is used to perform read/ write operation in csv file.
import csv module # import csv
[Link]( ) # Read from csv file
[Link]( ) # Write to csv file – single row
[Link]( ) # Write to csv file – multiple rows
open( ) # Functions to open csv file
close( ) # Functions to close csv file
ACCESS MODE
r ‐ read mode used to read the content of csv file.
w ‐ write mode used to write to csv file,previous data is first deleted and write
new data. Only newly added data will be shown to csv file.
a ‐ append mode data will be added at the last previous data
is not deleted, only inserted after previous data
42
If our csv file is a tab delimiter, to read such files, we need to pass optional parameter to [Link](
) fnction.
f = open("[Link]", "r", “\t”)
f = open(csvfile, mode,delimiter)
f = open("[Link]", "r", “,”)
SINGLE FILE TO FIRST CREATE FILE USING WRITE AND THEN READ RECORD
APPEND RECORD
44
MCQs
3. Which of the following option is the correct Python statement to read and display the first 10
characters of a text file “[Link]”?
a) F = open(“[Link]”); print([Link](10))
b) F = open(“[Link]”); print([Link](10))
c) F = open(“[Link]”); print([Link](10))
d) F = open(“[Link]”; print([Link](10))
6. Which of the following option is correct usage for the tell() of a file object?
a) It places the file pointer at a desired offset in a file
b) It returns the entire content of a file.
c) It returns the byte position of the file pointer as an integer.
d) It tells the details about the file.
9. Expansion of CRLF is
a)control return and line feed b) carriage return and form feed
c) control router and line feed d) carriage return and line feed
45
10. Which of the module is provided by python to do several operations on the CSV files?
a) Py b)xls c)csv d) os
13. Each record is to be located on separate line, delimited by a line break by pressing------- key
a) Esc b) enter c)end d) Alt
14. Which of the following mode is used when dealing with non-text files like image or exe files
a) text mode b)binary mode c)xls mode d)csv mode
15. In which mode, while reading from the file the data should be in the format of string
a) text mode b)binary mode c)xls mode d)csv mode
17. In open command, file name or the complete path name can be represented within -----
a) “” b)’ ‘ c) both a) and b) d) either a) or b)
19. Making some changes in the data of the existing file or adding more data is called
a)editing b)appending c)modification d) alteration
20. Which function is designed to take each line of the file make list of all columns?
a)read() b)reader() c)row() d)list()
21. Which of the following is a string used to terminate lines produced by writer method of csv module
a) Line terminator b)enter key c)form feed d)data terminator
22. To read the next line of the file from a file object infi, we can use
a) [Link](all) b) [Link]() c) [Link]() d) [Link]()
[Link] read the remaining lines of the file from a file object fh,we use
a) [Link](all) b) [Link]() c) [Link]() d) [Link]()
46
5. The _______file mode will open a file for write and read purpose.
6. To close an open file,________method is used.
7. To read all the file contents in the form of a list,______ method is used.
8. To write a list in a file,______method may be used.
9. To force Python to write the contents of file buffer on to storage file,______ method may be
used.
10. To read and write into binary files,__________ module of Python is used
11. The_______ method of pickle module writes data into a binary file
12. The________ method of pickle module reads data from a binary file.
13. The conversion of an object hierarchy in byte stream is called _________ or__________
14. We can suppress EOL translation in text file by giving ______ argument in open().
15. The file mode to open a binary file for reading, as well as writing, is___________
16. The file mode to open a binary file for writing, as well as reading, is___________
TRUE/FALSE
1. When you open a file for reading, if the file does not exist, an error occurs.
2. When you open a file for writing, if the file does not exist, an error occurs.
3. When you open a file for writing, if the file exists, the existing file is overwritten with the new file.
4. The absolute paths are from the topmost level of the directory structure.
5. The relative paths are relative to the current working directory.
6. The relative path for a file always remains the same even after changing the directory.
7. The types of operations that can be carried out on a file depend upon the file mode a file is
opened.
8. If no path is given with a file name in the file open(), then the file must exist in the current
directory.
9. Functions readline() and readlines() are essentially the same.
10. Python automatically flushes the file buffers before closing a file with close() function.
11. When you open a file for writing, if the file does not exist, a new file is created.
12. When you open a file for appending, if the file exists, the existing file is overwritten with the new
file.
13. Conversion of an object hierarchy in byte stream is called Serialisation.
2. Assertion: ‘Pickling’ is the process whereby a Python object hierarchy is converted into a byte
stream.
Reason: A binary file works with byte-streams
3. Assertion: ‘Pickling’ is the process whereby a Python object hierarchy is converted into a byte
stream.
Reason: The pickling process is used to work with binary files as a binary file works with byte-
streams.
4. Assertion: Every open file maintains a file-pointer and keeps track of its position after every
operation.
Reason: Every read and write operation takes place at the current position of the file pointer.
47
5. Assertion. Python is said to have broadly two types of files - binary and text files, even when
there are CSV and TSV files also.
Reason. The CSV and TSV are types of delimited text files only where the delimiters are
comma and tab respectively.
6. Assertion. The file modes "r", "w", "a" work with text files, CSV files and TSV files alike.
Reason. The CSV and TSV are types of delimited text files only.
7. Assertion. The file modes "r", "w", "a" also reveal the type of file these are being used with.
Reason. The binary file modes have 'b' suffix with regular file modes.
8. Assertion. 'Pickling' is the process whereby a Python object hierarchy is converted into a
byte-stream.
Reason. A binary file works with byte-streams.
9. Assertion. 'Pickling is the process whereby a Python object hierarchy is converted into a
byte-stream.
Reason. Pickling process is used to work with binary files as a binary file works with
byte-streams.
10. Assertion. Every open file maintains a file-pointer and keeps track of its position after every
operation.
Reason. Every read and write operation takes place at the current position of the file pointer.
11. Assertion. CSV (Comma Separated Values) is a file format for data storage which looks like a
text file.
Reason. The information is organized with one record on each line and each field is separated
by comma.
ANSWERS
MCQs
1. c 2. d 3. c 4. b 5. a 6. c 7. c 8.a 9.d 10.c 11.c 12.d 13. B
14.b 15.a 16.b 17.d 18.a 19.c 20.b 21.a 22.c 23.b 24.a 25.d
True/False
1. T 2. F 3. T 4. T 5. T 6. F 7. T 8. T 9. F 10. T 11. T 12. F 13. T
1. Write a single loop to display all the contents of a text file [Link] after removing leading and
trailing whitespaces.
for line in file(“[Link]”):
print([Link]())
2. Write a function LongLine() that accepts a filename and reports the file’s longest line.
def LongLine(filename):
longest = “”
48
for line in file(filename):
if len(line) > len(longest):
longest = line
print(“Longest line’s length =”, len(longest))
print(longest)
4. Write a function remove_lowercase() that accepts two filenames and copies all line that do not
start with a lowercase letter from the first file into the second.
def remove_lowercase(infile, outfile):
output=file(outfile,”w”)
for line in file(infile):
if not line[0] in “abcdefghijklmnopqrstuwxyz”:
[Link](line)
[Link]()
5. Write code to print just the last line of a text file “[Link]”
fin = open(“[Link]”,”r”)
LineList = [Link]()
print(“Last Line = “,LineList[-1])
7. What is unpickling ?
The “unpickling” is the inverse operation of pickling (deserialization), whereby a byte
stream(often read from a binary file) is converted back into an object hierarchy.
8. Your recipe uses some ingredients. Write a program to store the list of ingredients in a binary file.
import pickle
ingredients = [‘badam’, ’pista’, ’dry grapes’, ’walnut’, ’pumpkin seeds’]
with open(‘[Link]’,’wb’) as fout:
[Link](ingredients,fout)
17. How will you open a new binary file [Link] in write and read mode?
File1 = open(“[Link]”,”wb+”)
50
19. What is a delimited text file?
A delimited text file is a file that has individual data items separated by an embedded delimiter
such as quotation marks, commas, tabs etc.
20. Write a statement in Python to open a text file [Link] so that existing content can be
read from it
file = open(“[Link]”,”r”)
OR
file=open(“[Link]”,”r+”)
21. Write a function to count the number of lines starting with uppercase characters in a text file
“[Link]”.
def CountUpper():
count=0
with open("[Link]",'r') as f:
while True:
line=[Link]()
if not line:
break
if line[0].isupper():
count=count+1
if count=0:
print("no line starts with upper case character')
else:
print("count=",count)
22. Write a function to count the number of alphabets present in a text file “[Link]”.
def countalpha():
fname="[Link]"
count=0
with open(fname,'r') as f:
l=[Link]()
for line in l:
for word in line:
for char in word:
if [Link]():
count=count+1
print(count)
[Link]()
23. Read the following passage and answer the question that follows.
A text file can be understood as a sequence of characters consisting of alphabets, numbers
and other special symbols. When we open a text file using a text editor (e.g. Notepad) we
see served lines of text. However, the file contents are not stored in such a very internally.
Rather, they are stored in sequence of bytes consisting of 0s and 1s. In ASCII, UNICODE or
any other encoding scheme, the value of each ASCII value and shows us the equivalent
character that is readable by the human being. For example, the ASCII value 65 (binary
equivalent 10000001) will be displayed by a text editor as the letter ‘A’ since the number 65
in ASCII character set represents ‘A’. Each line of a text files is terminated by a special
character as EOL. However, other characters can be used to indicate EOL. When a text
editor or a program interpreter encounters the ASCII equivalent of EOL character, it displays
the remaining file contents starting from a new line. Contents in a text file are usually
separated by whitespace, but comma(,) and tab(\t) are commonly used to separate values in
a text file.
i. The file extension (s) used for text file is/are
a) .txt b) .py c) .csv d) All of these
51
ii. What is the default EOL character in Python?
a) \n b) \t c) \e d) \l
iii. Each line of a text file is terminated by a special character called
a) DNS b) IP c) CSV d) EOL
iv. How can you separate the content in a text file?
a) whitespace b) tab c) comma d) All of these
24. Read the following passage and answer the question that follows:
Arun, during Practical Examination of Computer Science, has been assigned an incomplete
search() function to search in a pickled file [Link]. the File [Link] is created by his
Teacher and the following information is known about the file.
File contains details of students in [roll_no, name, marks] format
File contains details of 10 students and separate list of each student is written in the
binary file using dump()
Arun has been assigned the task to complete the code and print details of roll number 1
def search():
f = open(“[Link]”,______) #Statement-1
______: #Statement-2
while True:
rec = pickle.________ #Statement-3
if(_______): #Statement-4
print(rec)
except: pass
______ #Statement-5
ii) identify the suitable code to be used at blank space in line marked as Statement-2
a) if(rec[0]==1) b) for i in range(10) c) try d) pass
iii) Identify the function, to be used at blank space in line marked as Statement-3
a) Load() b) load([Link]) c) load(f) d) load(fin)
iv) What will be the suitable code for blank space in line marked as Statement-4
a) Rec[0] ==2b) rec[1] == 2 c) rec[2] == 2 d) rec[0]== 1
v) Which statement Arun should use at blank space in line marked as Statement-5 to
close the file.
a) [Link]() b) close(file) c) [Link]() d) close()
25. Write a function in Python to count the number of lines in a text file ‘[Link]’ which starts with
an alphabet ‘H’
def CountLines():
file = open(‘[Link]’,’r’)
lines = [Link]()
count = 0
for w in lines:
if w[0] == ”H” or w[0] == “h” :
count = count + 1
print(“Total lines started with ‘H’ or ‘h’ is ”,count)
[Link]()
52
26. Write a method /function countlines_et () in python to read lines from a text file [Link], and
COUNT those lines which are starting either with ‘E’ and starting with ‘T’ respectively. And display
the Total count separately.
For example: if [Link] consists of “ENTRY LEVEL OF PROGRAMMING
CAN BE LEARNED FROM USEFUL FOR VARIETY OF USERS.” Then, Output
will be: No. of Lines with E: 1 No. of Lines with T: 1
Solution:
def countlines_et():
f=open("[Link]",'r')
lines=[Link]()
linee=0
linet=0
for i in lines:
if i[0]=='E':
linee+=1
elif i[0]=='T':
linet+=1
print("[Link] Lines with E:",linee)
print("[Link] Lines with T:",linet)
countlines_et()
27. Write a method/function show_todo():in python to read contents from a text file [Link] and
display those lines which have occurrence of the word “ TO” or “DO”
For example: If the content of the file is
“THIS IS IMPORTANT TO NOTE THAT SUCCESS IS THE RESULT OF HARD WORK WE
ALL ARE EXPECTED TO DO HARD WORK. AFTER ALL EXPERIENCE COMES FROM
HARDWORK.”
The method/function should display”
THIS IS IMPORTANT TO NOTE THAT SUCCESS IS THE RESULT OF HARD WORK.
WE ALL ARE EXPECTED TO DO HARD WORK.
Solutions:
def show_todo():
f=open("[Link]",'r')
lines=[Link]()
for i in lines:
if "TO" in i or "DO" in i:
print(i)
show_todo()
[Link] a function that counts the number of “Me” or “My” words present in a text file” [Link].
If the “[Link]” content are as follows: My first book was Me and My Family. It gave me chance to
be known to the world.
The output of the function should be: Count of Me/My in file: 4
Solution:
def displayMeMy():
num=0
f=open("[Link]","rt")
N=[Link]()
53
M=[Link]()
for x in M:
if x=="Me" or x== "My":
print(x)
num=num+1
[Link]()
print("Count of Me/My in file:",num)
displayMeMy()
29. Write a function count_A_M(), which should read each character of a text file [Link],
should count and display the occurrence of alphabets A and M (including small cases a and m too).
Example: If the file content is as follow: Updated information As simplified by official websites.
The count_A_M():function should display the output as:
A or a:4 M or m:2
Solution:
def count_A_M():
f=open("[Link]","r")
A,M=0,0
r=[Link]()
for x in r:
if x[0]=="A" or x[0]=="a" :
A=A+1
elif x[0]=="M" or x[0]=="m":
M=M+1
[Link]()
print("A or a: ",A,"\t M or m: ",M)
count_A_M()
30. Consider a binary file [Link] that has the following data: OrderId, MedicineName,Qty and
Price of all the medicines of wellness medicos, write the following functions:
a)AddOrder() that can input all the medicine orders.
b)DisplayPrice() to display the details of all the medicine that have Price.
Solution:
import pickle
def AddOrder():
f=open("[Link]",'ab')
OrderId=input("Enter Order Id")
MedicineName=input("Enter Medicine Name")
Qty=int(input("Enter Quantity:"))
Price=int(input("Enter Price:"))
data=[OrderId,MedicineName,Qty,Price]
[Link](data,f)
[Link]()
AddOrder()
def DisplayPrice():
f=open("[Link]",'rb')
try:
while True:
data=[Link](f)
if data[3]>500:
54
print(data[0],data[1],data[2],data[3],sep="\t")
except:
[Link]()
DisplayPrice()
31. Create a binary file [Link] that can store details of rides such as Ticketno, Ridename,
No_ofpersons, and price with the help of AddRides() function and write another python function
display Total to display total amount of each ticket. Also count total number of tickets sold.
Solution:
import pickle # to use binary file
def AddRides():
f=open("[Link]",'ab')
Ticketno=input("Enter Ticket Number")
RideName=input("Enter The Name of Ride")
No_ofperson=int(input("Enter no of Persons"))
Price=int(input("Enter Price:"))
data=[Ticketno,RideName,No_ofperson,Price]
[Link](data,f)
[Link]()
AddRides()
def Display Total():
f=open("[Link]",'rb')
total=0
count=0
32. A binary file “[Link]” has structure [BookNo, Book_Name, Author, Price].
[Link] a user defined function CreateFile() to input data for a record and add
to [Link].
b. Write a function CountRec(Author) in Python which accepts the Author name as parameter
and count and retum number of books by the given Author are stored in the binary file “[Link]”.
import pickle
def CreateFile():
fobj=open("[Link]","ab")
BookNo=int(input("Book Number : "))
Book_name=input("Name :")
Author = input("Author: ")
Price = int(input("Price : "))
rec=[BookNo,Book_Name,Author,Price]
[Link](rec,fobj)
[Link]()
def CountRec(Author):
fobj=open("[Link]","rb")
num = 0
try:
while True:
rec=[Link](fobj)
if Author==rec[2]:
num = num + 1
except:
[Link]()
return num
55
33. A binary file named “[Link]” 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 [Link]. The function will calculate & display the Average of the
ScoredMarks of the passed Subject on screen.
Solution:
def DisplayAvgMarks(sub):
f=open("[Link]","rb")
count=0
sum=0
try:
while True:
data=[Link](f)
total=data[2]*data[3]
print(data[0],data[1],data[2],data[3],total,sep="\t")
count=count+1
except:
[Link]()
print("Total number of Tickets sold are:",count) DisplayTotal()
while True:
pos=[Link]()
rec=[Link](f)
if rec[1]==sub:
sum+=rec[3]
count+=1
except:
[Link]()
print("AVG Marks:",sum/count)
DisplayAvgMarks(sub)
34. Abhisar is making a software on “Countries & their Capitals” in which various records are to be
stored/retrieved in [Link] data file. It consists of some records. He has written the following
code. As a programmer, you have to help him to successfully execute the program.
import # Statement-1
def AddNewRec(Country,Capital): # Fn. to add a new record in CSV file
f=open(“[Link]”,_______) # Statement-2 fwriter=[Link](f)
[Link]([Country,Capital])
f. # Statement-3
def ShowRec(): # Fn. to display all records from CSV file with
open(“[Link]”,”r”) as NF:
NewReader=csv. (NF) # Statement-4 for rec in NewReader: print(rec[0],rec[1])
AddNewRec(“INDIA”,”NEW DELHI”)
AddNewRec(“CHINA”,”BEIJING”)
ShowRec() # Statement-5
1) Name the module to be imported in Statement-1.
Ans: csv module
2) Write the file mode to be passed to add new record in Statement-2.
Ans : ‘a’ -append mode.
3) Fill in the blank in Statement-3 to close the file.
Ans : [Link]()
4) Fill in the blank in Statement-4 to read the data from a csv file.
Ans : reader()
56
5) Write the output which will come after executing Statement-5.
Ans: INDIA NEW DELHI
CHINA BEIJING
[Link] a program to copy a data from [Link] to [Link]
import csv
f=open (“[Link]”,”r”)
f1=open (“[Link]”,”w”)
d=[Link] (f)
di= [Link](f1)
for i in d:
[Link](i)
[Link]()
[Link]()
36. Write python program to read the following names [Link] file and sort the data in
alphabetically order the names in the list and display the output
SLNO NAME
1 DEVI
2 ALIYA
3 BAAVANA
import csv,operator
d=[Link](open(‘[Link]’))
next(d)
s=sorted(d,key=[Link](1)
for x in s:
print(x)
OUTPUT:
[’2’, ’aliya’]
[’3’, ’baavana’]
[‘1’,’devi’]
37. Write a program to display all the records in a file along with line/record number
fh =open(“[Link]”,”r”)
count=0
rec=” ”
while True:
rec = [Link]()
if rec !=” “:
count = count + 1
print(count,rec)
[Link]()
38. A text file contains alphanumeric text ([Link]). write a program that reads this text file
and prints only the numbers or digits from the file.
F=open(“[Link]”,”r”)
for line in F:
words = [Link]()
for i in words:
for letter in i:
if([Link]()):
print(letter)
57
[Link] a program that copies a text file “[Link]” onto “[Link]” barring the lines
starting with a “@” sign.
def filter(oldfile,newfile):
fin = open(oldfile, “r”)
fout = open (newfile,”w”)
while True:
text = [Link]()
if len(text) !=0:
if text[0] !=”@”:
[Link](text)
[Link]()
[Link]()
filter(“[Link]”,”[Link]”)
[Link] is learning to work with binary files in Python using a process known as
picking/de-pickling. Help her to create binary file namely [Link] and then open,read
and display the content of the created file
import pickle
sqlist = list()
for k in range(10):
[Link](k*k)
fout = open(“[Link]”,’wb’)
[Link](sqlist,fout)
[Link]()
fin=open(“[Link]”,’rb’)
mylist = [Link](fin)
[Link]()
print(“Data from file:”,mylist)
58
UNIT 3: DATABASE MANGEMENT SYSTEM
DATABASE CONCEPTS
Database concepts and Needs:
A database is tabular organization of data. Each table comprises of rows (records) and
columns (attributes). Each record contains values for the corresponding attributes. The
values of the attributes for a record are interrelated. For example, different cases have
different values for the same specifications (length, color, engine capacity etc).
The database oriented approach supports multiple views of the same data. For example, a
clerk may only be able to see his details, whereas the manager can view the details of all the
clerks working under hum.
In database oriented approach, we store the common data in one table and access it from
the required tables. Thus, the redundancy of data decreases.
Multiple views of the same database may exist for different users. This is defined in the view
level of abstraction.
The logical level of abstraction defines the type of data that is stored in the database and the
relationship between them.
The design of the database is known as the database schema.
The instance of the database is the data contained by it at that particular moment.
The database administrator has the total control of the database and is responsible for setting
up and updating the database
Hierarchical Model
The hierarchical model was developed by IBM in 1968.
The data is organized in a tree structure where the nodes represent the records and the
branches of the tree represent the fields.
Since the data is organized in a tree structure, the parent node has the links to its child nodes.
This is called (PCR) parent child relation.
If we want to search a record, we have to traverse the tree from the root through all its parent
node to reach the specific record. Thus, searching for a record is very time consuming.
The hashing function is used to locate the root.
Network Model
Data is represented by collection of records and relationships among data are represented
by links.
Recording of relationship in the network model is implemented by using pointers.
Recording of relationship implementation is very complex since pointers are used. It supports
many-to-many relationship and simplified searching of record, since a record has many
access paths.
Relational Model
The Relational model, organizes data in the form of independent tables that are related to
each other.
59
A relation is a two-dimensional table. It contains number of rows (tuples) and columns
(attributes).
A table consists of a number of rows and columns. Each record contains values for the
attributes.
A single entry in a table is called a Tuple or Record or Row.
A database attribute is a column or field in a database table.
The degree of the table denotes the number of columns.
Cardinality is defined as the number of rows in a table.
A DBMS or database management system is a software used to create and manage databases.
{manage = insert new records, display, modify, delete , provide access control etc. } Database
= Collection of inter-related tables and other objects.
DBMS = DB + MS, DataBase + software to handle the DB
RDBMS = Relational Database Management System
RDBMS = database is organised in the form of relations (i.e. tables)
Examples of popular RDBMS – MySQL, Oracle, Sybase, DB2
TERMINOLOGY (RDBMS)
Table : CUSTOMER
Cust_Id CNAME AADHAR_NO ADDRESS PHONE
C01 ANUJ KUMAR 345612348912 GAUTAM VIHAR 8765432190
C03 NEHA SINGH 367823458904 RANI BAGH 7722334673
C04 NAREN GARG 453627980423 MAHESH NAGAR 6345612566
C07 BHARAT VERMA 516782245679 MALVIYA NAGAR 9818624567
Primary Key - An attribute or set of attributes that uniquely identify a record in a table /
relation. E.g. in table customer the attribute cust_id is primary key
Candidate Key - An attribute or set of attributes that can become primary key of the table /
relation. Eg. The attribute cust_id and aadhar_ no are candidate keys.
Alternate Key - The candidate which is not chosen as primary key. E,g in table customer, the
attribute cust_id is chosen as primary key, then aadhar_no will be alternate
key.
Foreign Key - A non-key attribute of a table whose values are derived from primary key of
some other table is known as foreign key in current table. Eg. Table Customer
(cust_id, cname , address, phone) Table Orders (Order_id, order_dt,
cust_id, amount) Customer.cust_id = primary key. Orders.cust_id = foreign
key
Advantages of SQL
Faster Query Processing
User-friendly language
no coding
skills necessary
Standardised Language with uniform platform
Interactive language
Portable
Multiple data view
60
Categories of SQL Commands
DDL = Data Definition Language. Used to create/modify table structure (CREATE , ALTER , DROP
etc)
DML = Data Manipulation Language. Used to change table data (INSERT, UPDATE, SELECT,
DELETE etc)
DCL = Data Control Language. (GRANT, REVOKE)
TCL = Transaction Control Language. (COMMIT, ROLLBACK, SAVEPOINT)
Two ways of using insert command ( A and B) : B = INSERT INTO <table-name> (<col1-name> ,
<col2-name> , - - -) VALUES (<col1-value> , <col2-value> , - - - ) ; - - useful when inserting partial
record or change the order of insertion
as per A= insert into pupil values(114, 'ANITA MATHUR', '2002-06-20' , 'FEMALE', 3150.0, 91.2) ;
12- SELECT Query (DML Command) - to view data (content) of a table / view
General syntax - SELECT <col-list> FROM <table-name> [ ,<table2-name> , - - - ]
[WHERE <condition> ] [ ORDER BY ASC | DESC ] [ GROUP BY <col-name> [ HAVING
<conditionbased-on-group-col> ] ] ;
Examples -
select admno , dob , name from pupil ;
select * from pupil ;
select name , 'was born on' , dob from pupil ;
select name , dob AS "Date of Birth" from pupil ;
Column ALIAS NAME – keyword AS used. <col_name> AS <alias-name>
select admno, name, dob AS BIRTHDATE from pupil ;
USE “ ” or ‘ ‘ (quotes) if alias name is more than one word long
Following are the clauses/operators which can be used with SELECT command:
WHERE - Used to specify the condition based on which rows of a table are displayed
OPERATORS USED IN WHERE CLAUSE - > , < , < = , = , != , AND (&&) , OR (||), NOT
To view name, dob, grade of students with ‘B’ grade.
select name, dob, grade from pupil WHERE grade = ‘B’ ;
To view data of admission number 126
SELECT * FROM pupil WHERE admno = 126 ;
To view name, admission number and date_of_birth of those students who have fees more than
3000
select name , admno , dob from pupil where fees > 3000 ;
BETWEEN - Used to define the range of values within which the column values must fall to make a
condition true. Range includes both the upper and the lower values.
select * from pupil where fees BETWEEN 3000 AND 3500 ;
Same command using AND , relational operators
select * from pupil where fees >= 3000 AND fees <= 3500 ;
IN - Used to select values that match any value in a list of Specified values
62
select admno, name from pupil where name IN ( ‘RAVINDER’ , ‘NAVNEET ‘ ) ;
Same command using OR operator
select admno, name from pupil where name = ‘RAVINDER’ name = ‘NAVNEET ‘ ;
LIKE - Used for pattern matching of string data using wildcard characters % and _ % = zero,
one or many characters _ = single character (underscore symbol)
To view data from pupil for names begin with letter ‘P’
select * from pupil where name LIKE ‘P%’ ;
To view details of those students whose fees is more than 3000 and name ends with ‘R’ select *
from pupil where fees > 3000 AND name LIKE ‘%R’ ;
‘A%’ = the string begins with character ‘A’
‘_ _a%’ = the third character is ‘a’
‘_ _ a’ = any three letter string that ends in ‘a’
‘_ _ _ _’ = Any four letter string
select * from pupil where name LIKE ‘A%’ ORDER BY name ;
select empno , ename, salary+comm AS “TOTAL_PAY” from employee where name LIKE ‘R%’
ORDER BY total_pay ;
IS NULL / IS NOT NULL - Used to select rows in which the specified column is NULL (or IS NOT
NULL)
To view the details of those students whose dob is not entered / dob datavalue is not available.
select * from pupil where dob IS NULL ;
ORDER BY - Used to display the selected rows in ascending or in descending order of the specified
column/expression
select * from pupil ORDER BY name ; OR select * from pupil ORDER BY name ASC ;
by default the ORDER is ASC i.e. ascending order. For descending order, must specify DESC
select admno, dob, name, grade from pupil ORDER BY name DESC ;
select * from pupil ORDER BY grade , name DESC ;
GROUP BY – To apply a SQL SELECT query on a group of records instead of whole table. GROUP
BY <column-name> is used
A group column is generally that column of the table which has repeating values.
For example, columns fees, gender , grade in table pupil have repeating values – you can group
the values of these columns.
select gender, count(*) from pupil GROUP BY gender ;
select max(fees) from pupil GROUP By grade ;
HAVING - To add condition to GROUP BY column. ( i.e. Use only with Group By )
select grade, avg(marks) from pupil group by grade HAVING count(*) > 1 ;
AGGREGATE FUNCTIONS
SUM() Returns the sum of the column
MIN() Returns the minimum value in the given column or set of values
MAX() Returns the maximum in the given column or set of values
AVG() Returns the average value of data in the given column or set of values
COUNT() Returns the total number of values / records as per the given column
NATURAL_JOIN – like equi-join, difference is that the common column of tables appears only once
in the result
select * from books NATURAL JOIN issued;
Example , To display the Book Name, Quantity_Issued and Price for all books of TDH publishers-
select book_name , qty_issued , price from books B , issued S where B.book_id = S.book_id and
publishers = ‘TDH’ ; ( Here B , S are table ALIAS NAMES)
64
MCQ
[Link] commands provide definitions for creating table structure, deleting relations, and
modifying relation schemas.
a. DDL b. DML c. DCL d. DQL
[Link] of the following language was designed for managing and accessing data in RDBMS?
[Link] B. DDL C. DML D. SQL
[Link] of the following commands are used to manage the changes made to the data in table by
DML statements?
A. TCL B. DML C. DDL D. DLL
[Link] SQL TCL command saves any transaction into the data permanently is
A. Save point B. Commit C. Save D. Save As
[Link] SQL DQL command used to display all the records from the table is
A. Select B. Display C. Show D. Select all
[Link] expansion is
A. Data Defined Language B. Data Definition Language
C. Definition Data Language D. Dictionary Data Language
65
[Link] of the following processing skills of SQL provides commands for defining relation
schemes?
A. MySQL B. DDL C. DML D. DCL
19. Which of the following command used to retrieve data from a database?
A. DDL B. DQL C. DML D. DCL
[Link] data in a database is stored based on the kind of value stored is known as
A. Language B. Function C. Record D. Datatype
21. Which of the following SQL standard recognized only Text and Number data type?
A. ANSI B. TCL C. DML D. DCL
[Link] of the following data type same as real expect the precision may exceed 64?
A. Float B. Real C. Double D. Long Real
[Link] open a connector to Mysql database, which statement is used to connect with mysql?
(a) Connector b) Connect c)password d)username
[Link] connector is used for linking the database with Python code?
a)MySQL-connector b)YesSQL: connector c)PostSQL: connector d)None of these
31. Which method of cursor class is used to fetch limited rows from the table?
a) [Link](SIZE) b) [Link](SIZE)
(c) [Link](SIZE) d) [Link](SIZE)
[Link] method of cursor class is used to insert or update multiple rows using a single Query?
a) [Link](query,rows) b) [Link](query,rows)
c) [Link](query,rows) d) [Link](query,rows)
[Link] 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) [Link] b) [Link]
c) [Link] d) [Link]
66
[Link] of the following is not a legal method for fetching records from database?
a) fetchone() b) fetchtwo() c) fetchall() d) fetchmany()
[Link] reflect the changes made in the database permanently you need to run……..
a) done() b) reflect() c) commit() d) final
1. Assertion: A database is centrally stored data and a DBMS is a system to manage the database.
Reason: DBMS is a database management system, which is a software managing the databases.
4. Assertion: A primary key is used to uniquely identify the rows in a data table.
Reason: A primary key is a field or attribute which has a unique value for each row or tuple.
6. Assertion: There can be multiple options for choosing a primary key in a data table.
Reason: All attribute combinations inside a data table that contain unique values for each
row, are the candidate keys.
7. Assertion: All types of keys contain unique values for each row.
Reason: A foreign-key attribute of a table is the primary key of another table.
8. Assertion: The foreign-keys of tables are used to establish relationships with other tables
and must be handled carefully.
Reason: Referential integrity is a system of rules that a DBMS uses to ensure that the
relationships between tables remain valid and no accidental change or deletion occurs
in the related data.
67
9. Assertion: A unique value that identifies each row uniquely is the primary key.
Reason: Only one column can be made the primary key.
10. Assertion: There is a difference between a fields being empty or storing NULL value in a field.
Reason: The NULL value is a legal way of signifying that no value exists in the field.
[Link]: The ALL and DISTINCT clauses of a SELECT query are related.
Reason: The ALL clause is the opposite of the DISTINCT clause of a SELECT Query.
12. Assertion: The WHERE and HAVING clauses are used for the same thing in a SELECT query.
Reason: Both WHERE and HAVING clauses are used to specify conditions at different levels.
13. Assertion: Both WHERE and HAVING clauses are used to specify conditions.
Reason: The WHERE and HAVING clauses are interchangeable.
16. Assertion: Both BETWEEN and IN operators can choose from a list of values.
Reason: The value ranges and a list of values are interpreted in the some way in SQL.
17. Assertion: The PRIMARY KEY and UNIQUE constraints are the same.
Reason: The columns with PRIMARY KEY or UNIQUE constraints have unique values for
each row.
[Link]: The treatment of NULL values is different with PRIMARY KEY and UNIQUE
constraints.
Reason: The column(s) with PRIMARY KEY do not allow the NULL value even in a single
row but UNIQUE constraint allows NULL for one of the rows.
[Link]: There is no restriction on the number of columns that can have PRIMARY KEY
constraint or UNIQUE constraints.
Reason: There can be multiple columns with UNIQUE constraint but PRIMARY KEY
[Link]: Both DELETE and DROP TABLE carry out the same thing - deletion in tables.
Reason: The DELETE command deletes the rows and DROP TABLE deletes the whole table.
22. Assertion: Both UPDATE and ALTER TABLE commands are similar.
Reason: The UPDATE command as well ALTER TABLE command make changes in the table
23. Assertion: SQL SELECT's GROUP BY clause is used to divide the result in groups.
Reason: The GROUP BY clause combines all those records that have identical values
in a particular field or in group by fields.
68
25. Assertion: SQL SELECT query can also fetch rows from multiple tables.
Reason: A join is a query that combines rows from two or more tables.
26. Assertion: Generally, a join query combines rows from multiple tables having some
common column(s) and a joining condition, but not always.
Reason: A Cartesian product is an unrestricted join where all possible combinations
of rows from multiple tables are created without any condition on them.
27. Assertion: The join, in which columns are compared for equality, is called Equi-join.
Reason: The join queries only produce combined rows from tables having some common
column, when compared for equality.
28. Assertion: In the result produced by a join query, there may be multiple identical columns
in the final result, but not always.
Reason: The join in which only one of the identical columns (coming from the joined tables)
exists, is called a Natural join.
29. Assertion: In order to carry out the join operation, there should be a governing condition.
Reason: A join condition may be based on equality, less than, greater than or non-equality.
31. Assertion: A database cursor receives all the records retrieved as per the query.
Reason: A resultset refers to the records in the database cursor and allows processing of
individual records in it.
32. Assertion: The database cursor and resultset have the same data yet they are different.
Reason: The database cursor is a control structure and the resultset is a logical set of records.
33. Assertion: One by one the records can be fetched from the database directly through
the database connection.
Reason: The database query results into a set of records known as the resultset.
34. Assertion: The cursor rowcount returns how many rows have been retrieved so far
through fetch...() methods.
Reason: The number of rows in a resultset and the rowcount are always equal.
69
3. Which command is used to modify the records of the table?
Ans: UPDATE
5. Which declaration doesn’t use the same number of bytes and consumption of bytes depend on
the input data?
Ans Varchar
7. In SQL, name the clause that is used to display the tuples in ascending order of an attribute
Ans: ORDER BY
10. In SQL, write the query to display the list of tables stored in a database.
Ans: SHOW TABLES
12. Give one point of difference between an equi-join and a natural join.
Ans: Equi-join
The join which columns from two table are compared for equality
Duplicate columns are show
Natural join
The join which only of the identical columns existing in both table is present
No duplicate of columns
13. A table, ITEM has been created in a database with the following field:
ITEMCODE, ITEMNAME, QTY, PRICE
Given the SQL command to add a new field, DISCOUNT to the ITEM table.
Ans: ALTER TABLE ITEM ADD (Discount INT);
70
17. [Link] want to interface python with mysql and write some code help him to write the code
import_____________.connector #Line1
mydb=[Link].________(host=”localhost”,user=”root”,
passwd=”tiger”,database=”school”) #Line2
cursor=mydb.___________() #Line3
cursor._______________(“select * from stud”) #Line4
data=cursor.__________() # Line 5 To retrieved all records
count=cursor.__________ #Line6 To count total rows
Ans: Line1:-mysql,
Line2:-connect,
Line3:cursor ,
Line4: execute,
Line5: fetchall,
Line6: rowc
[Link] the following employee table. Write SQL commands for the questions.(i) to (v).
(ii) To display all employees whose allowance is between 5000 and 7000.
SELECT * FROM employee WHERE allow BETWEEN 5000 and 7000 ;
(iii) To remove the employees who are mechanic.
Question 1: You have two tables: Students and Courses. You need to list all students along with
the courses they are enrolled in. Each student has a CourseID in the Students table that matches
the CourseID in the Courses table.
Answer :- SELECT [Link], [Link]
FROM Students, Courses WHERE [Link] = [Link];
71
Case Study 2: Employees and Departments
Question 2: You have two tables: Employees and Departments. You need to list all employees
along with their department names. The DepartmentID in the Employees table matches the
DepartmentID in the Departments table.
Question 3: You have two tables: Movies and Directors. You need to list all movies along with the
names of their directors. The DirectorID in the Movies table matches the DirectorID in the Directors
table.
Case Study 4 :
Consider three tables in a database: employees, departments, and projects. Each table contains
information as follows:
The employees table includes columns for employee_id, employee_name, and department_id.
The departments table includes columns for department_id and department_name. The projects
table includes columns for project_id, project_name, and department_id.
a) Write an SQL query to perform a Cartesian product between the employees and
projects tables, displaying all possible combinations of employees and projects.
b) Write an SQL query to retrieve the names of employees along with the names of their
corresponding departments using an equijoin between the employees and departments
tables.
c) Write an SQL query to retrieve the names of projects along with the names of their
corresponding departments using a natural join between the projects and departments
tables.
Answer
a) SELECT [Link], authors.author_name, genres.genre_name FROM books ,authors
WHERE books.author_id = authors.author_id ;
b) SELECT customers.customer_name, COUNT(orders.order_id) AS total_orders FROM
customersLEFT JOIN orders ON customers.customer_id = orders.customer_id GROUP
BY customers.customer_name;
c) SELECT DISTINCT authors.author_name FROM authors
JOIN books ON authors.author_id = books.author_id JOIN genres ON books.genre_id =
genres.genre_id WHERE genres.genre_name = 'Science Fiction';
Case Study 7:
Let's consider two tables, "doctors" and "patients", and generate SQL join queries
based on them.
Table Structures:
doctors: Contains information about doctors. Columns( doctor_id, doctor_name, specialization,
hospital_id)
Answer
a) SELECT p.patient_id, p.patient_name, d.doctor_name FROM patients p, doctors d
WHERE p.doctor_id = d.doctor_id;
Case Study 8 :-
let's consider two tables, "railway" and "passenger", and generate SQL join queries
based on them.
Table Structures:
railway: Contains information about railway trips. Columns: (trip_id, source_station,
destination_station, departure_time, arrival_time)
1) List all passengers along with the details of their corresponding railway trips.
2) Display the source and destination stations for all railway trips along with
the names of passengers on each trip.
3) Show the names of passengers who traveled between 'Station A' and 'Station B'.
4) List all railway trips along with the total number of passengers on each trip.
5) Find the total number of passengers who traveled from each source station.
Answer
1) SELECT p.passenger_id, p.passenger_name, r.source_station, r.destination_station,
r.departure_time, r.arrival_time FROM passenger p, railway r WHERE p.trip_id = r.trip_id;
Case Study 9: Consider the Following tables and write sql query .
Table Customers
CustomerI CustomerName ContactName Country
D
1 Alfreds Maria Germany
2 Ana Anil Mexico
3 Antonio Antonio Moreno Mexico
4 Rajsons Thomas UK
5 Benzeer Christina Sweden
Table : Orders
OrderID CustomerID OrderDate
10308 2 2024-03-01
10309 37 2024-03-03
10310 77 2024-03-04
10311 3 2024-03-05
10312 5 2024-03-06
a) Write an SQL query to find the orders along with the customer names for only
those orders that have matching customer records.
b) Write an SQL query to find all customers and their orders, including customers
who do not have any orders.
c) Write an SQL query to find all orders and their customer details, including orders
that do not have a matching customer.
d) Write an SQL query to find all customers and all orders, matching them when
possible.
Answer
a) SELECT [Link], [Link], [Link] FROM Orders
,Customers WHERE [Link] = [Link];
75
Case Study 7: Bank Database
Consider a bank named "SafeBank" that manages accounts, customers, and transactions. The
bank maintains data about accounts, customers, transactions, and branches in its database.
Here are the tables in the SecureBank database:
1. accounts: Contains information about bank accounts, including account_number,
customer_id, balance, and branch_id.
2. customers: Stores details about bank customers, such as customer_id, customer_name,
email, and phone_number.
3. transactions: Contains information about transactions, including transaction_id,
account_number, transaction_type, amount, and transaction_date.
4. branches: Stores details about bank branches, including branch_id, branch_name,
location, and manager.
Query
a) List all accounts along with the names of their account holders and their current
balances.
b) Find the total balance of all accounts in each branch.
c) Display the names of branches along with the names of their managers.
d) Find the average balance of accounts for each customer.
Answer
a) SELECT a.account_number, c.customer_name, [Link]
FROM accounts a , customers c WHERE a.customer_id = c.customer_id;
76
MYSQL - WORKSHEET – 1
1. Consider the following table and answer the given questions.
Table Name: student
Admno Name DOB Marks Age DOA City
101 Abir 2000-11-01 98 19 2010-08-16 Delhi
102 Ram 1999-10-02 65.8 18 2020-05-12 Kolkata
103 Amit 2000-05-01 99 20 2020-04-01 Delhi
104 Sam 1998-10-12 69.8 17 2022-04-01 NULL
77
4. Consider the following table and answer the given questions.
Table Name : STUD
Admno S_name Adm_date Marks
501 Arup 2000-11-01 98
502 Raj 1999-10-02 65.8
503 Aman 2000-05-01 99
504 Saroj 1998-10-02 69.8
What will be the output of the following query?
a. SELECT MAX(Adm_date) from stud;
b. SELECT MIN(Admno) from STUD;
c. SELECT AVG(marks) from stud where s_name like ‘A%’;
d. SELECT COUNT(*) FROM STUD;
78
MYSQL - WORKSHEET - 2
1. Write the output of the following SQL command. Select round(49.88);
(a) 49.88 (b) 9.8 (c) 49.0 (d) 50
2. Which one of the following SQL queries will display all Employee records containing the word
“Amit”, regardless of case (whether it was stored as AMIT, Amit or amit etc.)?
(a) Select * from Employees WHERE Emp Name like UPPER ‘%AMIT’;
(b) Select * from Employees WHERE Emp Name like ‘%AMIT%’ or ‘%Amit%’ or “%amit%’;
(c) Select * from Employees WHERE UPPER(EmpName) like ‘%AMIT%’;
(d) None of the above
8. Write the output of the following sql command. Select left(“Jammu Region”, 5);
(a) Region (b) Jammu (c) Jammu Region (d) None of the above
11. Write the output of the following SQL command select round(15.857,-1);
(a) 15.8 (b) 15.9 (c) 16.0 (d) 20
13. Write the output of the following SQL command ______ Select truncate(192.672,-1);
(a) 1925.7 (b) 190 (c) 193 (d) 192.6
14. Write the output of the following SQL command. Select substr(“COMPUTER”, 3,4);
(a) MPUT (b) PUTE (c) PU (d) MP
15. The string function that returns the index of the first occurrence of substring is ___
(a) insert() (b) instr() (c) instring() (d) infstr()
79
16. What is returned by INSTR(‘JAVAT POINT’, ‘P’)?
(a) 6 (b) 7 (c) POINT (d) JAVAT
19. State true or false: SQL does not permit distinct with count(*) (a) True (b) False
20. We apply the aggregate function to a group of sets of tuples using the clause.
(a) group by (b) group (c) group set (d) group attribute
21. Which of the following aggregation operation adds up all the values of the attribute?
(a) add (b) avg (c) max (d) sum
30. Nested grouping can be done by providing _____ in the GROUP BY expression.
(a) Single row (b) Multiple fields (c) Single column (d) Multiple tables
80
MYSQL WORKSHEET -3
1. Consider a table SALESMAN with the following data:
[Link]. SNAME SALARY BONUS DATE_OF_JOIN
A01 Beena Mehta 30000 45.23 29-10-2019
A02 K.L. Sahay 50000 25.34 13-03-2018
B03 Nisha Thakkar 30000 35.00 18-03-2017
B04 Leela Yadav 80000 NULL 31-12-2018
C05 Gautam Gola 20000 NULL 23-01-1989
C06 Traotu Garg 70000 12.37 15-06-1987
D07 Neena Sharma 50000 27.89 18-03-1999
Write SQL queries using SQL functions to perform the following operations:
a. Display salesman name and bonus after rounding off to zero decimal places.
b. Display the position of occurrence of the string “ta” in salesman names.
c. Display the four characters from salesman name starting from second characters.
d. Display the month name for the date of join of salesman.
e. Display the name of the weekday for the date of join of salesman.
2. Write the SQL functions which will perform the following operations:
(i) Display the string “chest” from the string “Manchester United”
(ii) To display the name of the month eg, January or February from the current date.
(iii) Select instr (“Hello World”, “he”);
7. Consider the following table Activity. Write SQL commands for the statements (i) to (ii) and
output for SQL queries (iii) to (v).
PID PARTICIPANT GRADE EVENT POINTS EVENTDATE HOUSE
101 Amit Dubey A Running 200 2018-12-19 Gandhi
102 Shivraj Singh B Hopping bag 300 2019-01-12 Bose
103 Raj Arora B Skipping 200 2018-12-19 Gandhi
104 Kapil raj A Bean bag 250 2018-12-19 Bhagat
105 Deepshikha A Obstacle 350 2018-03-31 Bose
Sen
106 Saloni Raj Egg&Spoon 200 2018-12-20 Bose
82