0% found this document useful (0 votes)
71 views82 pages

Identifying Python Code Errors

Uploaded by

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

Identifying Python Code Errors

Uploaded by

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

UNIT 1: COMPUTATIONAL THINKING AND PROGRAMMING – 2

PYTHON REVISION TOUR

 Python is a widely used high-level programming language for general-purpose programming,


created by Guido Van Rossum and first released in 1991. My first program in Python is:
 print(“Hello World”)
 Python shell can be used in two ways: interactive mode and script mode.
 Interactive mode does not save commands in the form of a program. It is used for testing code.
 Script mode is useful for creating programs and then trying the programs later and getting
complete output.
 Python is an interpreted language.
 Python is a case-sensitive language.

TOKENS IN PYTHON (Lexical Unit)


Smallest individual unit in a program.

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: /=, +=, -=, *=, %=, **=, //=

PRECEDENCE OF ARITHMETIC OPERATORS


PE(MD) (AS) = read PEMDAS
P=parenthesis () → E=exponential →M, D = multiplication and division → A, S=addition and
subtraction
Ex: 12*(3%4)//2+6 = 24 (Try at your end)

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 PROCESSING AND OTHER FUNCTIONS

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

Command Output Explanation


S KENDRIYA Will print entire string.
S[:] KENDRIYA Will print entire string.
S[::] KENDRIYA Will print entire string.
S[2] N Will print element at index no 2.
S[2:6] NDRI From index number 2 to (6-1) i.e. 5.
S[Link] EDI From index 1 to 5 every 2nd letter.
3
S[::2] KNRY From start to end … every 2nd letter.
S[::3] KDY From start to end … every 3rd letter.
S[::-1] AYIRDNEK Will print reverse of the string.
S[ : -1] KENDRIY Will print entire string except last letter
S[ -1] A Will print only last letter
S[-5::] DRIYA From index no -5 to end of the string.
S[-7:-4:] END From index no -7 to -5.
Stride when slicing string
 When the slicing operation, you can specify a third argument as the stride, which refers to
the number of characters to move forward after the first character is retrieved from the string.
The default value of stride is 1.
Example
>>> str1 = "Welcome to learn Python"
>>> print (str1[10:16])
learn
>>> print (str1[Link])
r
>>> print (str1[Link])
er
>>> print (str1[::3])
Wceoenyo

String Function Description


len(<string>) Retruns the length of its argument string
<string>.capitalize() Returns a copy of the string with its first character capitalized
<string>.count(sub[,start[,end]]) Returns the number of occurrences of the substring sub in the
string
<string>.find(sub[,start[,end]]) Returns the lowest index in the string where the substring sub
is found within the slice range
<string>.index(sub[,start[,end]]) Returns the lowest index where the specified substring is
found
<string>.isalnum() Returns True if the characters in the string are alphanumeric
and there is at least one character, False otherwise.
<string>.isalpha() Returns True if all characters in the string are alphanumeric
<string>.isdigit() Returns True if all the characters in the string are digits
<string>.islower() Returns True if all the characters in the string are lowercase
<string>.isupper() Returns True if all the characters in the string are uppercase
<string>.isspace() Returns True if there are only whitespace characters in the
string
<string>.lower() Returns a copy of the string converted to lowercase
<string>.upper() Returns a copy of the string converted to uppercase
<string>.lstrip() Returns a copy of the string with leading white-spaces
removed
<string>.rstrip() Returns a copy of the string with trailing white-spaces removed
<string>.strip() Returns a copy of the string with leading and trailing
whitespaces removed
<string>.startswith() Returns True if the string starts with the substring sub
<string>.endswith() Returns True if the string ends with the substring sub
<string>.title() Returns a title-cased version of the string where all words start
with uppercase characters and all remaining letters are
lowercase
<string>.istitle() Returns True if the string has the title case
<string>.replace(old,new) Returns a copy of the string will all occurrences of substring
old replaced by new string
4
<string>.join(<string iterable>) Joins a string or character after each member of the string
iterator
<string>.split(<string/char>) Splits a string based on the given string or characters and
returns a list containing split strings as members
<string>.partition(<sep/string>) Splits the string at the first occurrence of separator, and returns
a tuple containing three items as string till separation,
separator and the string after separator

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]

SLICING THE LIST


>>> L=[10, 11, 12, 13, 14, 15, 16, 18]
>>> seq=L[2:6]
# it will take from index no 2 to (6-1) i.e. 5
>>> seq # output: [12, 13, 14, 15]
General syntax for slicing is L[start : end : step]

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]

BUILT-IN FUNCTIONS OF LIST


Function with syntax Description
len(<list>) Returns the number of elements in the passed list
<list>(<elements>) Returns a list created from the passed arguments of sequence of
elements
<list>.index(<item>) Returns the index of first matched item from the list
<list>.append(<item>) Adds an item to the end of the list
<list>.extend(<list>) Adding multiple elements to a list
<list>.insert(<ind>,<item>) Inserts the given item in the given index
<list>.pop(<index>) Removes an element from the given position in the list
<list>.remove(<item>) Removes the first occurrence of given item
<list>.clear() Removes all the items from the list
<list>.count(<item>) Returns the count of the item in the list
<list>.reverse() Reverses the items of the list
<list>.sort() Sorts the items of the list, by default in ascending order
min(<list>) Returns minimum value from the list
max(<list>) Returns maximum value from the list
sum(<list>) Returns the sum of the elements of the list

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,…)

Creating Single Element Tuple


t=(1) # (1) was treated as integer, not a tuple
t=(3,) # Now t stores a tuple, not integer

Creating Tuples from Existing Sequence


T= Tuple(<sequence>)

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)

Slicing the Tuples


Tuple slices, like-slices or string slices are the sub part of the tuple extracted out.
seq = T[start:stop]
>>>T1=(10,20,30,40,50,60,70,80,90,100,110)
>>> seq=T1[4:-4]
(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

ADDING ELEMENT TO DICTIONARY


>>>d[4]=’four’ # will add a new element
>>> print(d)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

DELETING ELEMENTS FROM DICTIONARY


7
>>> del d[3]
# will delete entire key:value whose key is 3
>>> print(d) # op: {1: 'one', 2: 'two', 4: 'four'}

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] Python prompt indicates that Interpreter is ready to accept instruction.


(A)>>> (B)<<< (C)# (D)<<

[Link] of the following shortcut is used to create new Python Program?


(A) Ctrl+C (B) Ctrl +F (C) Ctrl +B (D) Ctrl +N

[Link] of the following character is used to give comments in Python Program?


(A)# (B)& (C)@ (D)$

[Link] symbol is used to print more than one item on a single line.
(A)Semicolon(;) (B) Dollor($) (C)comma(,) (D) Colon(:)

[Link] of the following is not a token?


(A)Interpreter (B) Identifiers (C)Keyword (D) Operators

[Link] of the following is not a Keyword in Python?


(A)break (B) while (C)continue (D) operators

[Link] operator is also called as Comparative operator?


(A)Arithmetic (B)Relational (C)Logical (D) Assignment

[Link] of the following is not logical operator?


(A) AND (B) OR (C)Not (D)Assignment

10. Python language was released in the year


a) 1992 b) 1994 c) 2001 d) 1991

11. Escape sequences starts with a


a) / b) // c) \” d) \
8
[Link] Python, the script mode programs can be stored with the extension.
a) .pyt b) .py c) .pyh d) .pon

[Link] mode displays the python code result immediately?


a) Compiler b) Script c) Interactive d) Program

[Link] operator replaces multiline if-else in Python?


a)Logical b) Conditional c) Relational d) Assignment

15. Which of the following is a sequence of characters surrounded by quotes?


a) Complex b) String literal c) Boolean d) Octal

[Link] python, comments begin with


a) / b) # c) \ d) \\

[Link] python _________ is a simple assignment operator.


a) != b) = c) == d) >>>

18. Python uses the symbols and symbol combinations as _____ in expressions
a) literals b) keywords c) delimiters d) identifiers

19. All data values in Python are__________


a) class b) objects c) octal d) functions

20. Hexadecimal number contains _____


a) h b) o c) d d) x

[Link] of the following command is used to execute Python Script?


a) Run → Python Module b) File → Run Module
c) Run → Module Run d) Run → Run Module

22. In Python shell window opened by pressing


a) Alt + N b) Shift + N c) Ctrl + N d) Ctrl+Shift+N

23. elif can be considered to be abbreviation of


(A)nested if (B)if..else (C)else if (D)if..elif

24. What plays a vital role in Python programming?


(A)Statements (B) Control (C)Structure (D) Indentation

25. The condition in the if statement should be in the form of


(A) Arithmetic or Relational expression (B) Arithmetic or Logical expression
(C) Relational or Logical expression (D) Arithmetic

26. What is the output of the following snippet?


i=1
while True:
if i%3 ==0:
break
print(i,end='')
i +=1
(A)12 (B)123 (C)1234 (D)124

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

28. Which amongst is not a jump statement?


(A)for (B)goto (C)continue (D)break

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

31 Pick odd one in connection with collection data type


(a) List (b)Tuple (c)Dictionary (d)Loop

32. Let l i s t 1= [2,4,6,8,10], t h e n p r i n t (List1[-2]) will result in


(a)10 (b)8 (c)4 (d)6

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()

[Link] List= [10,20,30,40,50] then List [2]=35 will result


(a)[35,10,20,30,40,50] (b)[10,20,30,40,50,35]
(c)[10,20,35,40,50] (d)[10,35,30,40,50]

[Link] List=[17,23,41,10] then [Link](32) will result


(a)[32,17,23,41,10] (b)[17,23,41,10,32]
(c)[10,17,23,32,41] (d)[41,32,23,17,10]

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()

[Link] will be the result of the following Python code?


S = [ x**2 for x in range(5)]
print (S)
a) [0,1,2,4,5] b) [0,1,4,9,16] c) [0,1,4,9,16,25] d) [1,4,9,16,25]

[Link] is the use of type() function in Python?


a) To create a Tuple b) To know the type of an element in tuple
c) To know the data type of python object d) To create a list

39. Which of the following statement is not correct?


(a) A list is mutable b)A tuple is immutable
(c) The append() function is used to add an element.
(d)The extend() function is used in tuple to add elements in a list.
40. The keys in Python, dictionary is specified by
a) = b) ; c) + d) :
41. Which of the following is an ordered collection of values?
(a)Set (b)Tuples (c)List (d)Dictionary

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()

44. Which of the following argument is optional in sort()?


(a)Reverse (b)Key (c)True/false (d)a and b

45. Which is a powerful feature in python.


(a)Tuple assignment (b)List assignment (c)Assignment statement (d)Set

46. While creating a tuple from a list, the element should been closed within
(a)[] (b)() (c){} (d)[()]

47. Write the output for the [Link]=(1,2,4,4,5,6) print(Tu[4:])


(a)4,5,6 (b)6 (c)5,6 (d)4,4,5,6

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

50. Which of the following operator is used for concatenation?


(a) + (b) & (c) * (d) =

51. Defining strings within triple quotes allows creating:


(a) Single line Strings (b) Multiline Strings
(c) Double line Strings (d) Multiple Strings

52. Strings in python:


(a) Changeable (b) Mutable (c) Immutable (d) flexible

53. Which of the following is the slicing operator?


(a) { } (b) [ ] (c) <> (d) ( )

54. What is stride?


(a) index value of slide operation (b) first argument of slice operation
(c) second argument of slice operation (d) third argument of slice operation

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) ^^

57. The subscript of a string may be:


(a) Positive (b) Negative (c) Both (a) and (b) (d) Either (a) or (b)

58. Which of the following is used to handle array of characters in python?


a) Functions b) Composition c) Arguments d) String
11
59. String index values are also called as
a) class b) function c) subscript d) arguments

60. A substring can be taken from the original string by using


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.

2. Assertion: """"A Sample Python String"""" is a valid Python String.


Reason: Triple Quotation marks are not valid in Python.

3. Assertion: If and For are legal statements in Python.


Reason: Python is case sensitive and its basic selection and looping statements are in
lower case.

4. Assertion: if and for are legal statements in Python.


Reason: Python is case sensitive and its basic selection and looping statements are in
lower case.

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.

12. Assertion: In Insertion Sort, a part of the array is always sorted.


Reason: In insertion sort, each successive element is picked and inserted at an appropriate
position in the sorted part of the array.

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.

17. Assertion: Python standard library consists of number of modules.


Reasoning: A function in a module is used to simplify the code and avoids repetition.

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

1. Find the invalid identifier(s) from the following:


a) MyName b) True c) 2ndName d) My_Name
Ans: b) True, as it is a keyword c) 2ndName, Because it is starting with a digit.

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.

3. Identify the valid arithmetic operator in Python from the following:


a) ? b) < c) ** d) and
Ans: c) ** as it is used to find power

4. Suppose tuple T is T = (10, 12, 43, 39), Find incorrect?


a) print(T[1]) b) T[2] = -29 c) print(max(T)) d) print(len(T))
Ans : b) T[2]= -29 (as tuple is immutable and we can’t change its value)

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'}

6. A tuple is declared asT = (2, 5, 6, 9, 8) What will be the value of sum(T)?


Ans : It will give the sum of all elements of tuple i.e. 2+5+6+9+8 = 30 abs()

7. Name the built-in mathematical function / method that is used to return an absolute value of a
number.
Ans : Abs()

8. Identify declaration of L = [‘Mon’,‘23’,‘Bye’, ’6.5’]


a) dictionary b) string c) tuple d) list
Ans: d) list, as a list is collection of heterogeneous data.

9. Find the output of the following code?


>>>name="ComputerSciencewithPython"
>>>print(name[3:10])
Ans : It will print string from index no 3 to (10-1) i.e. 9 means 7 characters.
So output will be puterSc

10. Find the output:


>>>A = [17, 24, 15, 30]
>>>[Link](2, 33)
>>>print (A[-4])
Ans : [Link](2,33) will insert 33 at index no 2. Now the list is [17, 24, 33, 15, 30]. So print(A[-4))
will start counting from last element starting from -1, -2…
Hence will give 24.

11. What will be the result of the following code?


>>>d1 = {“abc” : 5, “def” : 6, “ghi” : 7}
>>>print (d1[0])
(a) abc (b) 5 (c) {“abc”:5} (d) Error
Ans : (d) Error, because dictionary works on the principle of key:value. These is no key as 0,
so it will produce an error.

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'].

13. Suppose list L is declared as


L = [5 * i for i in range (0,4)], list L is
a) [0, 1, 2, 3,] b) [0, 1, 2, 3, 4] c) [0, 5, 10, 15] d) [0, 5, 10, 15, 20]
Ans : It is List Comprehension. Expression L = [i for i in range (0,4)] will generate [0, 1, 2, 3].
Since here we are writing 5*i, so correct answer will be c) [0, 5, 10, 15]
14. Find possible output(s) at the time of execution of the program from the following code?
Also specify the maximum values of variables Lower and Upper.
import random as r
AR=[20, 30, 40, 50, 60, 70]
Lower = [Link](1,3)
Upper =[Link](2,
for K in range(Lower, Upper +1):
print (AR[K],end=”#“)
(i) 10#40#70# (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#

15. How do you convert a string into an int in python?


 If a string contains only numerical characters, we can convert it into an integer using the
int() function, however, we cannot convert alphabetic and alphanumeric strings to integer in
Python.
16. How do you convert a number to a string?
 To convert a number into a string, we can use the inbuilt function str(). For octal or
Hexadecimal representation, we can use the inbuilt function oct() or hex().
17. What is Indentation?
 Python uses whitespace such as spaces and tabs to define program blocks of codes for
selection, loop, functions and class.
 The indentation is not fixed, but all statements within block must by indented with same
amount spaces
18. What are the assignment operators that can be used in Python?
 In Python, = is a simple assignment operator to assign values to variable.
 There are various compound operators in Python like +=, -=, *=, /=, **= and //= are also
available.
 Let us consider a=5 i.e. the value 5 from right side is assigned to the variable a to the left
side
 Assume a+=5 i.e. the value 5 is added to the operand a and assign back the result to the left
operand a itself (a=a+5)
[Link] a short note on comment statement.
 In Python, comments begin with hash symbol(#).
 The lines that begin with # are considered as comments and ignored by the Python
interpreter.
 Comments may be single line or multiline.
 The multiline comments should be enclosed within a set of ‘’’ ‘’’(triple quotes)

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")

[Link] a program to check if the year is leap year or not


def leap(year):
if((year%4==0 and year%100!=0) or (year%400==0)):
print(year, " is a Leap year")
else:
print(year, " is not a Leap year")

y=int(input("Enter a year : "))


leap(y)

25. Write a program to display all 3 digit odd numbers.


for i in range(101,1000,2):
print (i,end='\t')
[Link] a program to display multiplication table for a given number.
num=int(input("Display of Multiplication Table for : "))
for i in range(1,11):
print(num," X ", i, " = ", num*i)
Output:
Display of Multiplication Table for : 7
7 X 1 = 7
7 X 2 = 14
16
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70

27. What is the use of format( )? Give an example.


 The format() function used with strings is very versatile and powerful function used for
formatting strings.
 The curly braces {} are used as placeholders or replacement fields which get replaced along
with format() function.
Example:
num1=int (input("Number 1: "))
num2=int (input("Number 2: "))
print ("The sum of {} and {} is {}".format(num1, num2,(num1+num2)))
output :
Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88

28. How index value allocated to each character of a string in Python?


 Once you define a string, python allocate an index value for its each character. These index
values are otherwise called as subscript which are used to access and manipulate the strings.
The subscript can be positive or negative integer numbers.
 The positive subscript 0 is assigned to the first character and n-1 to the last character, where
n is the number of characters in the string. The negative index assigned from the last
character to the first character in reverse order begins with -1.

 Example

29. Write the output


tup = (10)
print(type (tup))
tup1 = (10,)
print(type(tup1))
Output: <class‘int’>
<class‘tuple’>

30 Give an example of joining two tuples.


Tup1=(2,4,6,8,10)
Tup2=(1,3,5,7,9)
Tup3=Tup1+Tup2
print(Tup3)
Output :
(2,4,6,8,10,1,3,5,7,9)
31. What is nested tuple? Explain with an example.
 In Python, a tuple can be defined inside another tuple; called Nestedtuple.
 In a nested tuple, each tuple is considered as anelement.
 The for loop will be useful to access all the elements in a nestedtuple.
17
Example:
Toppers =(("Vinodini", "XII-F", 98.7),("Soundarya", "XII- H",97.5),("Tharani","XII-F",95.3),
("Saisri","XII-G",93.8))
for i in Toppers:
print(i)

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)

print(“Two given dictionaries are: “)


print(dct1)
print(dct2)
print(“The resultant dictionary”)
print(dct3)

33. What is the output of the following code?

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)

36. What is the output of the following code?


i=4
while True:
if i% 0o8 == 0:
break
print(i, end = '')
i += 1
The above code will give Error because 0o8 is not a valid integer. Any number beginning with 0 is
treated as an octal number and octal numbers cannot have digits 8 and 9. Hence 0o8 is an invalid
integer.

37. What is the output of the following code?

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

40. What is the error in the following code?


x=12
for i in x:
print(i)
The above code will produce an error as x is an integer and is used in place of a sequence
or iterable in a for loop, hence the error as integer values cannot be used as iterables.

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

DEFINING AND CALLING FUNCTION


 Re-usability of the code
In python, a function may be declared as:
def function_name([Parameter list]) :
“””Doc-string i.e. documentation of fn”””
Body of the function
return value
Remember: Implicitly, Python returns None, which is also a built-in, immutable data type. Ex:
>>> def f(a,b):
“””demo of a function””” #doc-string
c=a+b
return c
>>>f(10, 20) # calling of function
def is a keyword to declare a function f is the name of the function a, b – parameter/argument
of the function return is a keyword

Functions can be categorized in three types:


1. Built-in function 2. Modules 3. User-defined

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')

4. VARIABLE LENGTH ARGUMENTS


In certain situations, we can pass variable number of arguments to a function. Such types of
arguments are called variable length argument.
They are declared with * (asterisk) symbol.
def findSum(*n):
sm=0
for i in n:
sm=sm+i
print('Sum is ',sm)
22
#main-program
findSum() #output – Sum is 0
findSum(10) #output – Sum is 10
findSum(10,20,30) #output – Sum is 60
PASSING STRINGS TO FUNCTION
def countVowel(s):
vow='AEIOUaeiou'
ctr=0
for ch in s:
if ch in vow:
ctr=ctr+1
print('Number of vowels in', s ,'are', ctr)
#main-program
data=input('Enter a word to count vowels :')
countVowel(data)

PASSING LIST TO FUNCTION


def calAverage(L):
sm=0
for i in range(len(L)):
sm=sm+L[i]
av=sm/len(L)
return av
#main-program
marks=[25, 35, 32, 36, 28]
print('Marks are :',marks)
avg=calAverage(marks)
print('The average is', avg)

PASSING TUPLES TO FUNCTION


def midPoint(t1, t2):
m=((t1[0]+t2[0])/2.0,
(t1[1]+t2[1])/2.0)
return m
#main-program
p1=(2, 4)
p2=(6, 6)
mp=midPoint(p1,p2)
print('The Mid-Point of is', mp)

PASSING DICTIONARY TO FUNCTION


def printMe(d):
"""Function to print values of given dictionary"""
for key in d:
print(d[key])
#main-program
d={1:'mon', 2:'tue', 3:'wed' }
printMe(d)

Returning values from Functions


Functions in Python may or may not return a value.

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)

Returning Multiple Values


Python functions allows us to return multiple values
return <value1/variable1/expression1>,<value2/variable2/expression2>,..
The function call statement should receive or use the returned values

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)

FUNCTIONS USING LIBRARIES


Math library (import math)
Function Description Example
pi value of pi 3.14159
ceil(x) integer >=x ceil(1.2) → 2.0
floor(x) integer <=x floor(1.2) → 1.0
pow(x,y) x raise y pow(3,2) →9
sqrt(n) square root sqrt(2) → 1.414

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

Random library (import random)


random() Return floating value between 0 and 1.
randrange(0,N) This generates integer number from 0 to (N-1).
randint(a, b) Return any number b/w given number a and b including them
uniform(a, b) Return floating number b/w given numbers a and b.

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

2. Which of the following keyword is used to begin the function block?


(a) define (b) for (c) finally (d) def

3. Which of the following keyword is used to exit a function block?


(A)define (B) return (C)finally (D)def

4. While defining a function which of the following symbol is used.


(A);(semicolon) (B) .(dot) (C):(colon) (D) $(dollar)

[Link] which arguments the correct positional order is passed to a function?


(A)Required (B) Keyword (C)Default (D) Variable-length

[Link] the following statement and choose the correct statement(s).


(I) In Python, you don’t have to mention the specific data types while defining function.
(II) Python keywords can be used as function name.
A) I is correct and II is wrong B)Both are correct
C) I is wrong and II is correct D) Both are wrong

[Link] the correct one to execute the given statement successfully.


if _________ :
print(x, " is a leap year")
(A)x%2=0 (B) x%4==0 (C)x/4=0 (D)x%4=0

[Link] of the following keyword is used to define the function testpython():?


(A)define (B)pass (C)def (D)while
9. Which of the following special character is used to define variable length arguments?
(a) & (b) $ (c) * (d) #
10. What will be the output of the following Python program?
c=5
def add():
c=c+5
print(c)
add()
(a) 5
,
(b) 10 (c) 15 (d) Error
11. A variable declared inside the function's body is known as
(a) global variable (b) local variable (c) built in scope ( d) arguments

12. What is the output of the function print (sqrt(25))?


(a)5 (b) 50 (c) 75 (d) 100

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):

[Link] is the result of this code?


def prit(x):
print(2**x)
prit(3)
a) 10 b) 6 c) 4 d) 8
17. Which of the given argument types can be skipped from a function call?
a) positional arguments b) keyword arguments
c) named arguments d) default arguments

18. Which of the following is not correct in context of scope of variables?


a) Global keyword is used to change value of a global variable in a local scope.
b) Local keyword is used to change value of a local variable in a global scope.
c) Global variables can be accessed without using the global keyword in a local scope
d) Local variables cannot be used outside its scope

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

20. What is a variable defined inside a function 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

ASSERTIONS AND REASONS

1. Assertion: A function is a subprogram.


Reason: A function exists within a program and works within it when called.

2. Assertion: Non-default arguments cannot follow default arguments in a function call.


Reason: A function call can have different types of arguments.

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.

4. Assertion: A variable declared inside a function cannot be used outside it.


Reason: A variable created inside a function has a function scope.

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

Question and Answers


1. What is function?
 Functions are named blocks of code that are designed to do specific job.
 Functions are nothing but a group of related statements that perform a specific task.

2. What are the main advantages of function?


 It avoids repetition and makes high degree of code reusing.
 It provides better modularity for your application.

3. What is meant by scope of variable? Mention its types.


 Scope of variable refers to the part of the program, where it is accessible, i.e., area where you
can refer (use)it.
 Types of scopes: Local scope and Global scope.

4. Define global scope.


 A variable, with global scope can be used anywhere in the program.
 It can be created by defining a variable outside the scope of any function/block.

5. Write the rules of local variable.


 A variable with local scope can be accessed only within the function/block that it is created
in.
 When a variable is created inside the function/block, the variable becomes local to it.
 A local variable only exists while the function is executing.
 The format arguments are also local to function.
Example:
def loc():
y=0
print(y)
loc()

6. Write the basic rules for global keyword in python.


 When we define a variable outside a function, it’s global by default. You don’t have to use global
keyword.
 We use global keyword to read and write a global variable inside a function.
 Use of global keyword outside a function has no effect

27
Example:
c=1
def add():
print(c)
add()

7. What happens when we modify global variable inside the function?


 Without using the global keyword we cannot modify the global variable inside the function
but we can only access the global variable.

8. What are the points to be noted while defining a function?

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

syntax of creating a user defined function:


def<function_name([parameter1,parameter2……])>:
<block of statements>
return <expression/None>

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.

name = input("Enter your name: ")


name_length = len(name)
print("Length of your name:", name_length)

def calculate_area(length, width):


area = length * width
return area

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)

(i) When the code above is executed, what gets printed?


Nothing gets printed(as print() is after the return statement)
(ii) What is variable output equal to after the code is executed?
25

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)

Function header : def processNumber(a,b): in line 1


Function call : processNumber(x,y) in line 6
Arguments : x,y in line 6
Parameters : a,b in line 1
Function body : c=a+b in lines 2 and 3
return c
Main program : x,y=54,65 in lines 5 and 6
res=processNumber(x,y)

13. Write the output of the following code:


def Change(P,Q=30)
P= P+Q
Q = P-Q
print(P,”#”,Q)
return(P)
R=150
S=100
R=Change(R,S)
print(R,”#”,S)
S = Change(S)

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)

Flow of execution for above code will be:


1→5→9→10→5→6→1→2→3→6→7→10→1→2→3→10→11
Output : 52
15. Consider below given function headers. Identify which of these will cause error and
why?
i. def func(a=1,b):
ii. def func(a=1,b, c=2):
iii. def func(a=1,b=1,c=2):
iv. def func(a=1,b=1,c=2,d):

Function headers i,ii and iv will cause error because non-default arguments cannot follow
default arguments.

Only function header iii. Will not cause any error

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)]

18. What will be the output of the following functions

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

6. What is being passed to function fun() in the following code?


int a=20
lst = [10,20,30,40,50,60]
fun(a,lst)

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.

 Some standard Python exceptions.


 TypeError: Occurs when the expected type doesn’t match with the given type of a variable.
 ValueError: When an expected value is not given- if you are expecting 4 elements in a list
and you gave 2.
 NameError: When trying to access a variable or a function that is not defined.
 IOError: When trying to access a file that does not exist.
 IndexError: Accessing an invalid index of a sequence will throw an IndexError.
 KeyError: When an invalid key is used to access a value in the dictionary.
 ImportError: When an import statement fails to find the module definition.
 ZeroDivisionError: When the second argument of a division operation is zero
 OverflowError: When the result of an arithmetic operation is too large to be represented.
 KeyboardInterrupt: When Keys ESC, DEL, CTRL+C is pressed during program execution.
 KeyError: When the key is not found in the set of existing keys in the dictionary.
 EOFError: When the built-in function hits an end-of-file (EOF) condition without reading
any data.

33
MCQ:

1. How many except statements can try-except block have?


a) Zero b) One c) More than one d) More than zero

2. When will the else part of try-except-else be executed?


a) Always b) When an exception occurs
c) When no exception occurs d) When an exception occurs in to except block

3. Is the following Python code valid?


try:
print(“Hello Raja”)
except:
print(“This is except”)
finally:
print(“ The Program is valid”)
a) No b) No, finally cannot be used with except
c) No, finally must come before except d) Yes
4. When is the finally block executed?
a) When there is no exception b) When there is an exception
c) Only if some condition that has been specified is satisfied d) Always

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


def myfunction():
try:
return1
finally:
return 2
k = myfunction()
print(k)
a) 1 b) 2 c) 3
d) error, there is more than one return statement in a single try-finally block

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


def myfunction():
try:
print(1)
finally:
print(2)
k = myfunction()
print(k)
a) 1 2 b) 1 c) 2 d) 1 2 None

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


try:
if ‘1’ != 1:
raise “someError”
else:
print(“someError has not occurred”)
except “someError”:
print(“someError has occurred”)
a) someError has occurred b) someError has not occurred
c) invalid code d) none of the mentioned
34
8. What happens if the file is not found in the following Python code?
a = False
while not a:
try:
f_n = input("Enter file name")
i_f = open(f_n,'r')
except:
print("Input file not found")
a) No error b) Assertion error c) Input output error d) Name error

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


lst = [1,2,3]
lst[3]
a) NameError b) ValueError c) IndexError d) TypeError

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


t[5]
a) IndexError b) NameError c) TypeError d) ValueError

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

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


int(’65.43’)
a) ImportError b) ValueError c) TypeError d) NameError

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

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


def getMonth(m):
if m<1 or m>12:
raise ValueError(“Invalid”)
print(m)
getMonth(6)
a) ValueError b) Invalid c) 6 d) ValueError(“Invalid”)

15. Identify the type of error in the following Python codes.


Print(“Good Morning”)
print(“Good night)
a) Syntax, Syntax b) Semantic, Syntax c) Semantic, Semantic d) Syntax, Semantic
35
16. What is the output of the following program?
value = [1,2,3,4,5]
try:
value = value[5]/0
except (IndexError, ZeroDivisionError):
print(“Exception”,end=’’)
else:
print(“EXC”,end=’’)
finally:
print(“Excep”,end=’’)
a) Compilation error b) Runtime error c) Exception EXC Excep d) ExceptionExcep

17. What is the output of the following program?


value = [1,2,3,4]
data = 0
try:
data = value[4]
except IndexError:
print(‘EXC’,end=’’)
except:
print(‘Exceptions’,end=’’)
a) Exceptions b) EXC c) EXC Exceptions d) Compilation error

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

19. Which of the following block is a ‘must-execute’ block?


a) try b) finally c) except d) else

20. Which keyword is used to force an exception?


a) raise b) finally c) try d) except

State True or False

1. All types of errors can be found during compile time.


2. An unexpected rare condition occurring during runtime which disrupts a program's execution is
an exception.
3. A program running properly but producing the wrong output is an exception.
4. The except block deals with the exception, if it occurs.
5. try, except, finally is the correct order of blocks in exception handling.
6. Exception and error are the same.

ASSERTIONS AND REASONS

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

2. Assertion: Exception handling code is separate from normal code.


Reason: Program logic is different while exception handling code uses specific keywords to
handle 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

ASSERTIONS AND REASONS


1. c 2. a 3. a 4. a

Question and Answers

1. Differentiate between Syntax Error and Exception.


Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads
to the termination of the program.
Example:
amount = 10000
if (amount > 2999)
print(“You are eligible to purchase Self Paced”)

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)

2. What are the common Syntax errors in Python?


 Missing or Misplaced Symbols such as a Colon, comma, parentheses
 Incorrect Indentation
 Unbalanced Parentheses, Brackets or Braces
 Mismatched Quotes
 Invalid variable Names
 Using Reserved words instead of variables
 Empty if, else, while, for, function, class, method
 Incorrect number of positional arguments

3. Give some common examples of Exceptions.


 Divide by zero errors
 Accessing the elements of an array beyond its range
 Invalid Input
 Hard disk crash
 Opening a non-existent file
 Heap memory exhausted

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.

6. When do you need multiple except handlers – exception-catching blocks?


 When the program has more than one condition to throw exceptions, we can associate more
than one except blocks with a try block

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

Answer: a) ValueError b) ZeroDivisionError c) ImportError d) NameError


e) IndexError f) OverflowError g) IOError

[Link] an example program for assert statement.

a=int(input(“Enter the value for a”))


b=int(input(“Enter the value for b”))
assert b!=0,”Value for b must be non-zero”
print(“The result of a divided by b is ”,a/b)

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'

This Program to test Invalid arguments for MATH functions


Enter the Positive Integer number six
Please enter only Positive Integers
Enter Integer 3.0
Please enter only valid Integers
This Program Tested only Invalid arguments for Math functions 'sqrt' and 'pow'

10. Write the output of the following code.


try:
lst=[10,20,30,40,50]
for num in lst:
i = int(num)
j=i*i
print(i,j)
except NameError:
print([Link])
else:
print('Total Numbers processed',len(lst))
del(lst)

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:

Text file Binary CSV Description


mode File Mode File
Mode
‘r’ ‘rb’ ‘r’ By default Read. Opens a file for reading, error
if the file does not exist.
‘w’ ‘wb’ ‘w’ Write - Opens a file for writing, creates the file
if it does not exist
‘a’ ‘ab’ ‘a’ Append - Opens a file for appending, creates
the file if it does not exist
‘r+’ ‘rb+’ Read and Write-File must exist, otherwise
error is raised.
‘w+’ ‘wb+’ Read and Write-File is created if does not exist.
‘a+’ ‘ab+’ Read and write-Append new data
‘x’ ‘xb’ Create - Creates the specified file, returns an error if the
file exists

Opening and closing a file:To open a file we use open() method and to close file, we use close()
method.

Standard syntax for open a file in two way:


(i) file_object=open(“file name”,mode name)
(ii) with open(“file name”,access mode) as file object:
7
Close a file: file_object.close()
Example: f = open("[Link]",’r’) where f is file object/file handle and open() is method, name of file-
[Link] mode-read(by default file open in read mode indicated by ‘r’) another way to open file is :-
With open(“[Link]”,’r’) as f :

Modules required in files:


 OS module: we used for remove(), rename() and getcwd() methods.
 remove(): To delete a file, rename(): To rename a file, getcwd(): To find the current directory

 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).

csv module: - we used in csv file for reader(),writer(),writerow(),writerows() methods.

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

CSV stands for Comma Separated values.


41
e.g.
rno, name, marks
11, Kush, 55
12, Abhijeet, 59

rno name marks


11 Kush 55
12 Abijeet 59

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

OPEN CSV FILE


There are two ways to open a csv file
a. file variable/ file handler = open(csv_file_name, access_mode)
b. using with function with
open( csv_file_name, access_mode) as file variable/ file handler :

CLOSE CSV FILE


file variable/ file [Link]( )
#working with csv files
import csv
f = open("[Link]", "r")
rec = [Link](f)
for r in rec:
print(r)
[Link]()

READING CSV FILE


The csvreader( ) 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]() function in default
mode of csv file having comma delimiter.

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", “,”)

WRITING TO CSV FILE


To write csv file in python, we can use [Link]() function.
The [Link]() function returns a writer object that converts the user’s data into delimiter string. The
string can later be used to write into CSV File using writerow( ) function.
#writing to csv file
import csv
with open("[Link]", "w", newline='') as fw:
wrec = [Link](fw)
[Link](["Rno", "Sname", "marks" ])
[Link](["201", "Shruti", "62" ])
[Link](["202", "Monika", "76" ])
[Link](["203", "Aditi", "83" ])
print("\ndata sucessfully written")
[Link]()

WRITE MULTIPLE ROWS WITH WRITEROWS( ) FUNCTION


If we need to write the content of 2‐Dimensional list into csv file, instead of using writerow() function
many times, we can write writerows() function.
#writing Multiple records to csv file
import csv
L= (["Rno", "Sname", "marks"],
["301", "Anamika", "40" ],
["302", "Kanika", "50" ],
["303", "Bhumika", "60" ])
with open("[Link]", "w", newline='') as fw:
wrec = [Link](fw)
[Link](L)
print("\nMultiple rows sucessfully written")
[Link]()

CONTENT OF CSV FILE : [Link]


APPEND DATA TO CSV FILE
Append data means, previous data will exists. After all previous data, new data will be inserted after
last record. ACCESS MODE will be “a”
#Append data to csv file
import csv
Fa =open("[Link]", "a", newline=''):
wrec = [Link](fw)
[Link](["207", "Akash", "99" ])
print("\ndata sucessfully Appended")
[Link]()

APPEND DATA TO CSV FILE FROM USER


Append data means, previous data will exists. After all previous data, new data will be inserted after
last record. ACCESS MODE will be “a”
Record will be given by user when program is run and will be added to csv file.
43
#Append data to csv file
import csv
Fu =open("[Link]", "a", newline='') w = [Link](Fu)
N = int(input("Enter no of record to add : ")) for x in range(N):
rn = int(input("Enter rollno : "))
nm = input("Enter Name : ")
mrk = int(input("Enter Marks : "))
L = [rn, nm, mrk]
[Link](L)
print("\nRow sucessfully Added")
print("\nAll rows are added")
[Link]()

SINGLE FILE TO FIRST CREATE FILE USING WRITE AND THEN READ RECORD

#Read and write in a single csv file import csv

F = open("[Link]", "w", newline ='')


W = [Link](F)
N = int(input("No. of records to enter : "))
for i in range(N):
ino = int(input("Enter Item No. : "))
iname= input("Enter Item Name : ")
iprice = int(input("Enter Item Price : "))
L = [ino, iname, iprice]
[Link](L)
print("Records successfully added\n")
[Link]()
F = open("[Link]","r")
rec = [Link](F)
print("\nRecords in file")
for i in rec:
print(i)
[Link]()

APPEND RECORD

#append data from user in csv file import csv

F = open("[Link]", "a", newline ='') W = [Link](F)


N = int(input("No. of records to enter : "))
for i in range(N):
ino = int(input("Enter Item No. : "))
iname= input("Enter Item Name : ")
iprice = int(input("Enter Item Price : "))
L = [ino, iname, iprice]
[Link](L)
print("Records successfully added\n")
[Link]()

44
MCQs

1. Which of the following is a function/method of the pickle module?


a) reader() b) writer c) load() d) read()

2. A text file opened using the following statement:


MyFile = open(‘[Link]’)
Which of the following is the correct Python statement to close it?
a) MyFile = close(“[Link]”) b) MyFile = close(‘[Link] ‘)
c) [Link]() d) [Link]()

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))

4. Suppose the content of a text file “[Link]” is as follows:


Jack & Jill
went up the hill
what will be the output of the following Python code?
F = open(“[Link]”)
L = [Link]()
for i in L:
S=[Link]()
print(len(S),end=”#”)
a) 2#4# b) 3#4# c) 3# d) 7#
5. What will be the output of the following Python code?
f = None
for i in range(5):
with open("[Link]","w") as f:
if i > 2:
break
print([Link])
a) True b) False c) None d) Error

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.

7. What is the significance of the seek() method?


a) It seeks the absolute path of the file
b) It tells the current byte position of the file pointer within the file
c) It places the file pointer at a desired offset within the file
d) It seeks the entire content of the file

8. A CSV file is known as a ----------------


a). flat file b) 3D file c)string file d) random 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

11. CSV file cannot store


a) String b) text c) graph or charts d) none of these

12. Files saved in excel cannot be opened or edited by ------------


a) Excel b)text editor c) starcalc d) none of these

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

16. csv files have been used extensively in ------------- application


a) elearning b) ecommerce c) eshopping d)none

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)

18. The command used to skip a row in a CSV file is


a) next() b)skip() c)omit() d)bounce

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]()

23. The readlines method returns__________


a) a str b) a list of lines c) a list of single characters d) a list of integers

24. To read twelve characters from a file object fle, we use


a) [Link](12) b) [Link]() c) [Link]() d) [Link](12)

[Link] read the remaining lines of the file from a file object fh,we use
a) [Link](all) b) [Link]() c) [Link]() d) [Link]()

Fill in the blanks:


1. The default file-open mode is_______ mode.
2. A______governs the type of operations (e.g., read/write/append) possible in the opened file.
3. The two types of data files can be _____files and ______files.
4. The______file mode will open a file for read and write purpose.

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.

Assertions and Reasons


1. Assertion: The file modes ‘r’, ’w’, ’a’, also reveal the type of files these are being used with.
Reason: The binary file modes have ‘b’ suffix with regular file modes.

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

Fill in the blanks


1. read 2. File mode 3. Text,binary 4. r+ 5. w+ or a+ 6. close() 7.
readlines()
8. writelines() 9. flush() 10. pickle 11. dump() 12. load() 13. Pickling,serialisation
14. newline 15. rb+ 16. wb+

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

Assertions and Reasons


1. a 2. b 3. b 4. a 5. a 6. a 7. a 8. b 9. b 10. a 11. a

Question and Answers

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)

3. Suppose the content of a text file [Link] is:


“The way to get started is to quit talking and begin doing”
What will be the output of the following Python code?
F = open(“[Link]”)
[Link](29)
S = [Link]()
print(S)
Output: quit talking and begin doing

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])

6. What is pickling process? What is its need?


 Objects have a specific structure which must be maintained while storing or accessing them.
 Python provides a special module – the pickle module to take care of that.
 The pickling process serializes the objects(serialization) and converts them into byte stream
so that they can be stored in binary files

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)

9. Identify the error in the following code:


import pickle
data = [‘one’,2,[3,4,5]]
with open(‘[Link]’,’rb’) as f:
[Link](data,f)
The file is opened in read mode and dump() function tries to write onto file, hence the error.
So the line 3 should
be changed as:
with open(‘[Link]’,’wb’) as f:
49
10. What does the writeline() function do?
 Syntax: <filehandle>.writelines(L)
 It writes all strings in list L as lines to file referenced by <filehandle>

11. What is the use of the flush() function?


 The flush() function forces the writing of data on the disc still pending in output buffers.
 This function is implicitly called by the close() function. But if you want to flush the data before
close any file, the syntax to use flush() function is:
<fileobject>.flush()

12. What is the use of load() method?


This method is used for reading data from the binary file. The syntax is
<object> = [Link](<filehandle>)

13. What is the use of dump() method?


The dump() function of pickle module writes an object on to a binary file opened in the write
mode.
Syntax: [Link](<object-to-be-written>,<filehandle-of-open-file>)

14. Explain seek() method.


The seek() function changes the position of the file-pointer by placing the file-pointer at the
specified position in the open file.
<file-object>.seek(offset[,mode])
The offset argument indicates the number of bytes to be moved. mode, 0 for beginning of
file, 1 for current position of file-pointer, 2- for end of file
Example: ch=open(“[Link]”,”r”)
[Link](30,1) # will place the file pointer at 30th byte ahead of current file-
pointer position
15. What is tell() function.
The tell() function returns the current position of file pointer in the file. It is used as per syntax:
<file-object>.tell()

16. Write statements to place the file handle fp1:


i) to beginning of file
ii) to 25th byte from the beginning
iii) to 10 byte behind the current position of the pointer
iv) to 25 bytes behind the EOF position
i) [Link](0)
ii) [Link](25,0)
iii) [Link](10,1)
iv) [Link](25,2)

17. How will you open a new binary file [Link] in write and read mode?
File1 = open(“[Link]”,”wb+”)

18. Differentiate between a Text File and a Binary File


Sl. Text File Binary File
No.
1 It stores information in ASCII or It stores information just in the form as
Unicode characters it is stored in memory
2 In text file, each line of text is In binary files, there is no delimiter for
terminated with a special character lines.
known as EOL

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

v. The number 65 in ASCII character set represents


a) D b) A c) C d) B

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

i) In which mode Arun should open the file in Statement-1?


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

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

Need for a Database


Data is stored in the form of files. A number of application programs are written by programmers to
insert, delete, modify and retrieve data from these files. New application programs will be added to
the system as the need arises.
 A data model is the methodology used by a particular DBMS to organize and access the
data.
 Hierarchical, Network and Relational model are the three popular data models. However, the
relational model is more widely used.

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

Structured Query Language (SQL)


 When a user wants to get some information from a database file, he can issue a query.
 A query is a user-request to retrieve data or information with a certain condition.
 SQL is a query language that allows user to specify the conditions.

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)

DATATYPES COMMONLY USED IN SQL –


For Text - CHAR ( n ) VARCHAR ( n )
Numeric Data - INT ( n ) or INTEGER ( n ) DECIMAL( n, d) or FLOAT (n)
Date - Date format ‘yyyy-dd-mm’
Boolean values - tinyint(1) ( value = 0 means False , 1 means True)

SQL Commands at a glance


1 - CREATE DATABASE = to create tables and work with them.
create database <database-name> ; work with them

2 – VIEW LIST OF EXISTING DATABASES ON YOUR MACHINE = show databases ;

3 – OPEN A DATABASE FOR WORK = use <database-name> ;

4 – VIEW LIST OF EXISTING TABLES AND / OR VIEWS = show tables ;

5 – VIEW THE STRUCTURE OF AN EXISTING TABLE =


desc <table-name> ; OR describe <table-name> ;

6 - CREATE TABLE ( DDL command )= CREATE TABLE <table-name> ( <col1-name> datatype


[(size)] [constraint] , <col2-name> datatype[(size)] [constraint] , - - - - - );
CREATE TABLE PUPIL ( admno integer(4) primary key , name varchar(18) not null,
dob date, gender char(6) DEFAULT 'MALE',fees decimal (7,2), avgmark decimal(5,2) ) ;

7- INSERT Records ( DML Command )= A = INSERT INTO <table-name> VALUES


(<value-1> , <value-2> , - - - ) ; - - order of data-values same as table structure i.e. columns order

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) ;

as per B = insert into pupil(name,admno,dob) values('DEV SHARMA',112,'2003-01-03') ;

8 - ALTER TABLE ( DDL command)- to add a column


ALTER TABLE <table-name> ADD <col-name> <datatype>[(<size>)] [constraint] ;
e.g. - ALTER TABLE pupil ADD grade char(2);
-to add integrity constraint-ALTER TABLE <table-name>ADD <constraint> (<col-name>);
-to redefine a column (datatype , size, default-value)
ALTER TABLE <TABLE-NAME>
MODIFY (<COL-NAME> NEWdatatype [(<size>)] ) [ FIRST | AFTER colname] ;
Example - ALTER TABLE PUPIL Modify name varchar(20);
ALTER TABLE <TABLE-NAME>
61
MODIFY <old_col_name> <new_col_name > < new_col_definition> ;

9- DROP COMMAND – To delete a table as well as its structure from database.


DROP TABLE <table-name> ; OR DROP TABLE [IF EXISTS] <table-name> ;
DROP TABLE FLIGHT ;
DROP is also used as a CLAUSE in ALTER TABLE command
ALTER TABLE book DROP disc_amt ;
ALTER TABLE flight DROP PRIMARY KEY ;

10- UPDATE Query (DML Command) - UPDATE <table-name>


SET <col-name> = <value> [ , <col2-name> = <value> , - - - ] [WHERE <condition>] ;
To modify existing record(s) update pupil set avgmark = 89.7 , grade = 'B' where admno = 107 or
admno = 112 ;

11- DELETE Query (DML Command )- To remove a record(S)


DELETE FROM <table-name> [ WHERE <condition> ] ;
Example - delete from pupil where admno = 126 ;

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:

DISTINCT - Used to display distinct values from a column of a table.


select DISTINCT name from pupil;
To view data of names (without repetition) of the students

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

WORKING WITH MORE THAN ONE TABLE -


CARTESIAN PRODUCT OR CROSS JOIN
Cross Join of two tables is obtained by pairing up each row of one table with each row of the other
table.
63
Table A ( 3 rows, 4 columns) Table B ( 2 rows, 3 columns)
A X B = 6 rows, 7 columns ( 3 x2 , 4 + 3 ) (degree = total columns , cardinality = total rows in a
table)

EQUI_JOIN – joining based on common column (use it in WHERE clause, <table1>.<common-


column> = table2.<common-column> )
select * from books ,issued where books.book_id = issued.book_id ;

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)

INTERFACE OF PYTHON WITH AN SQL DATABASE

When we want to design real life applications to manipulate


Data stored in database we need interface python with MySQL. The steps are
 We use pip install [Link] :This command we use to install library of MySQL with
python.
 import [Link]: This statement run on python to access the module of MySQL if we
don’t get Any error means this module working properly.
 mydb=[Link](host=”localhost”,user=”root”,passwd=”tiger”,database=”school
”) : To make the connection with MySQL database using connect() function where user,
password and database as per our system which we assign during installing of MySQL. Mydb is
connection object.
 A cursor is a Python object that enables you to work with the database. In database terms, the
cursor is positioned at a particular location within a table or tables in a database.
 To get a cursor you need to call the cursor() method on the database object.
 cursor=[Link]()-a database cursor is useful control structure for row by row processing of
records
 [Link](“select * from stud”):It will execute the SQL query and store the retrieved records.
 To save your changes to the database, you must commit the transaction using commit()
 When you are done with the script, close the cursor and then the connection to free up the
resources.
 The DB-API’s include a defined set of exceptions.
 Database Object Methods
 close() – closes the connection to the database
 commit - Commits any pending transaction to the database
 cursor() - Returns a database cursor object through which queries can be executed
 rollback - Rolls back any pending transaction to the state the existed before the
transaction began.
 data=[Link]():Extract data from result set using fetch() functions.
 fetchall() : It will return all the records retrieved in tuple form.
 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.
 count=[Link] It is the property of cursor object that return number of rows retrieved.

64
MCQ

[Link] commands provide definitions for creating table structure, deleting relations, and
modifying relation schemas.
a. DDL b. DML c. DCL d. DQL

2. Which command lets to change the structure of the table?


a. SELECT b. ORDER BY c. MODIFY d. ALTER

3. The command to delete a table is


A) DROP B) DELETE C) DELETE ALL D) ALTER TABLE

4. Queries can be generated using


a. SELECT b. ORDER BY c. MODIFY d. ALTER

5. The clause used to sort data in a database


a. SORT BY b. ORDER BY c. GROUP BY d. SELECT

[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 is not a RDBMS package?


A. Oracle B. Sybase C. Dbase D. MySQL

[Link] data in RDBMS, is stored in database objects called


A. Queries B. Languages C. Relations D. Tables

[Link] of the following is a collection of data entries?


A. Database B. Table C. Dbase 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] of the following is not a SQL TCL command?


A. Commit B. Roll back C. Revoke D. Save point

[Link] SQL DQL command used to display all the records from the table is
A. Select B. Display C. Show D. Select all

[Link] SQL TCL command save a transaction temporarily


A. Commit B. Roll Back C. Save point D. None of these

[Link] expansion is
A. Data Defined Language B. Data Definition Language
C. Definition Data Language D. Dictionary Data Language

[Link] stand for


A. Data Manipulation Language B. Data Meaningful Language
C. Directional Manipulate Language D. Data Management Language

65
[Link] of the following processing skills of SQL provides commands for defining relation
schemes?
A. MySQL B. DDL C. DML D. DCL

[Link] of the following is not a SQL DDL commands?


A. Alter B. Drop C. Grant D. Truncate

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] odd one.


A. Record B. Row C. Tuple D. Field

[Link] SQL command to make a database as current active database


A. CURRENT B. USE C. DATABASE [Link]

[Link] type for variable width string values:


a. string b. char c. varchar d. varstr

[Link] constraint helps to set a limit value place for a field:


a. unique b. default c. check d. primary key

27. The primary key does not allow


a. data b. null c. char d. space

[Link] clause used to rename a field with ALTER command:


a. rename b. alter c. modify d. change

[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

36. A database________controls the connection to an actual database , established in program.


a) database object b) connection object c)fetch object d) query object

[Link] method is used to retrieve N number of records


a) fetchone() b) fetchall() c) fetchmany() d) fetchN()

[Link] python, execute() method can execute only .


a) Only DQL & DML statements b) Only DML statements
c) Only DQL statements. d) DDL, DML & DQL statements.

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

2. Assertion: Data redundancy may lead to data inconsistency.


Reason: When redundant data or the multiple copies of data mismatch, it makes the data
inconsistent.

3. Assertion: Data redundancy may lead to may problems.


Reason: In RDBMS, data redundancy is 100% removed.

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.

5. Assertion: A data table can have only one primary key.


Reason: In a data table, there can be only one attribute/field containing unique values for each
row.

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.

14. Assertion: DDL and DML are not the same.


Reason: DDL and DML are two subcategories of SQL where DDL creates the objects
and DML manipulates the data.

15. Assertion: DDL and DML both are part of SQL.


Reason. Both DDL and DML 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

constraint can be defined only once for one or more columns.


[Link]: There are different commands for creating and changing table design.
Reason: The CREATE TABLE command creates the tables while ALTER TABLE
command changes the design of an existing table.

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

24. Assertion: A GROUP BY query can also include functions.


Reason: ALL SQL functions can be used in a GROUP BY query.

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.

30. Assertion: A database connection object controls the connection to a database.


Reason: A connection object represents a unique session with a database, connected
from within a script/program.

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.

Answer for Assertions and Reasons


1. (a) 2. (a) 3. (c) 4. (a) 5. (c) 6. (a) 7. (d) 8. (a) 9. (c) 10. (a) 11. (a) 12. (a) 13.(b)
14. (a) 15. (b) 16. (c) 17. (d) 18. (a) 19. (d) 20. (a) 21. (d) 22. (e) 23. (a) 24. (c) 25. (a) 26. (a)
27. (c) 28.(a) 29. (d) 30. (a) 31. (a) 32. (a) 33. (d) 34. (c)

QUESTIONS AND ANSWERS

1. Which keyword is used to sort the records of a table in descending order?


Ans: DESC

2. Which clause is used to sort the records of a table?


Ans: ORDER BY

69
3. Which command is used to modify the records of the table?
Ans: UPDATE

4. Which clause is used to remove the duplicating rows of the table?


Ans: DISTINCT

5. Which declaration doesn’t use the same number of bytes and consumption of bytes depend on
the input data?
Ans Varchar

6. Which of the following is DDL Command?


a) SELECT b) ALTER c) INSERT d) UPDATE
Ans: b) ALTER

7. In SQL, name the clause that is used to display the tuples in ascending order of an attribute
Ans: ORDER BY

8. In SQL, what is the use of IS NULL operator?


Ans: To Check if the column has null value / no value.

9. Write any one aggregate function used in SQL.


Ans: MIN()

10. In SQL, write the query to display the list of tables stored in a database.
Ans: SHOW TABLES

11. Which command is used to view the list of tables 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);

14. Which command is use to install MySQL library in python?


Ans: pip install MySQL. Connector with path of python

15. Which method we use to establish the connection?


Ans: connect() method with connection object.
16. Which statement we use to access the MySQL module?
Ans: import [Link]

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

Emp Code Name Desig Pay Allowance


S1001 Hariharan Supervisor 29000 12000
P1002 Shaji Operator 10000 5500
P1003 Prasad Operator 12000 6500
C1004 Manjima Clerk 8000 4500
M1005 Ratheesh Mechanic 20000 7000

(i) To display the details of all employees in descending order of pay.


SELECT * FROM employee ORDER BY pay DESC;

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

DELETE FROM employee WHERE design = ‘Mechanic’;

(iv) To add a new row.

INSERT INTO employee VALUES(‘C1006’,’Krishna’,’Clerk’,16000,7800);

(v) To display the details of all employees who are operators


SELECT * FROM employee WHERE design =’Operator’;

Case Study Based Questions

Case Study 1: Students and Courses

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.

Answer :- SELECT [Link], [Link] FROM Employees


JOIN Departments ON [Link] = [Link];
Or
SELECT [Link], [Link] FROM Employees,
Departments WHERE [Link] = [Link];

Case Study 3: Movies and Directors

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.

Answer:- SELECT [Link], [Link]


FROM Movies, Directors WHERE [Link] = [Link];

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 employees.employee_id, employees.employee_name, projects.project_id,


projects.project_name FROM employees CROSS JOIN projects;
b) SELECT employees.employee_name, departments.department_name FROM
employees ,departments WHERE employees.department_id =
departments.department_id;
c) SELECT projects.project_name, departments.department_name FROM projects
NATURAL JOIN departments;

Case Study 5:-


Let's say we have a database for a small online bookstore having following tables
books: ( book_id, title, author_id, genre_id, price). authors: (author_id, author_name, birth_year)
genres: (genre_id , genre_name).
customers: (customer_id, customer_name, email)
orders: (order_id, customer_id, order_date, total_amount) order_details: (order_id, book_id,
quantity, unit_price).
72
a) List all books along with their corresponding authors.
b) Display the total number of orders placed by each customer.
c) List all authors who have written books in the 'Science Fiction' genre.
d) Find the total revenue generated from each genre

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';

d) SELECT genres.genre_name, SUM(order_details.quantity * order_details.unit_price) AS


total_revenue FROM genres JOIN books ON genres.genre_id = books.genre_id
JOIN order_details ON books.book_id = order_details.book_id GROUP BY
genres.genre_name;

Case Study 6 : Student and Teacher


Let's consider two tables, "students" and "teachers", and generate SQL join queries based on
them.
Table Structures:
students: Contains information about students. Columns( student_id, student_name, class_id, age)
teachers: Stores details about teachers. Columns: (teacher_id, teacher_name, subject_taught)
a) List all students along with their corresponding class names.
b) Display the names of teachers along with the subjects they teach.
c) Show the names of students who are enrolled in the 'Mathematics' class.
d) List all subjects along with the names of classes they are taught in.
e) Find the total number of students in each class.
Answer
a) SELECT s.student_id, s.student_name, c.class_name FROM students s ,classes c
WHERE s.class_id = c.class_id;
b) SELECT t.teacher_id, t.teacher_name, t.subject_taught FROM teachers t;
c) SELECT s.student_name FROM students s, classes c WHERE s.class_id = c.class_id
and c.class_name = 'Mathematics';
d) SELECT c.class_name, t.subject_taught FROM classes c ,teachers t
WHERE c.class_id = t.class_id;
e) SELECT c.class_name, COUNT(s.student_id) AS total_students FROM classes c ,
students s WHERE c.class_id = s.class_id GROUP BY c.class_name;

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)

patients: Stores details about patients. Columns: (patient_id, patient_name, doctor_id,


admission_date)
73
a) List all patients along with the names of their treating doctors.
b) Show the names of patients who are treated by doctors specializing in 'Cardiology'.
c) List all doctors along with the number of patients they are treating.
d) Find the total number of patients treated in each hospital.
e) Display the names of patients along with their admission dates and the names of their
treating doctors.

Answer
a) SELECT p.patient_id, p.patient_name, d.doctor_name FROM patients p, doctors d
WHERE p.doctor_id = d.doctor_id;

b) SELECT p.patient_name FROM patients p, doctors d WHERE p.doctor_id = d.doctor_id


and [Link] = 'Cardiology';

c) SELECT d.doctor_name, COUNT(p.patient_id) AS num_patients FROM doctors d


LEFT JOIN patients p ON d.doctor_id = p.doctor_id GROUP BY d.doctor_name;

d) SELECT d.hospital_id, COUNT(p.patient_id) AS num_patients FROM doctors d


,patients p WHERE d.doctor_id = p.doctor_id GROUP BY d.hospital_id;

e) SELECT p.patient_name, p.admission_date, 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)

passenger: Stores details about passengers on railway [Link]( passenger_id, trip_id,


passenger_name, ticket_number, seat_number)

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;

2) SELECT r.trip_id, r.source_station, r.destination_station, p.passenger_name FROM


railway r , passenger p WHERE r.trip_id = p.trip_id;

3) SELECT p.passenger_name FROM passenger p, railway r WHERE p.trip_id = r.trip_id


and r.source_station = 'Station A' AND r.destination_station = 'Station B';

4) SELECT r.trip_id, COUNT(p.passenger_id) AS num_passengers FROM railway r,


74
passenger p WHERE r.trip_id = p.trip_id GROUP BY r.trip_id;

5) SELECT r.source_station, COUNT(p.passenger_id) AS num_passengers FROM


railway r, passenger p WHERE r.trip_id = p.trip_id GROUP BY r.source_station;

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];

b) SELECT [Link], [Link], [Link]


FROM Customers LEFT JOIN Orders ON [Link] = [Link];

c) SELECT [Link], [Link], [Link]


d) FROM Orders RIGHT JOIN Customers ON [Link] = [Link];

e) SELECT [Link], [Link], [Link] FROM Customers


FULL OUTER JOIN Orders ON [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;

b) SELECT b.branch_id, b.branch_name, SUM([Link]) AS total_balance FROM


branches b, accounts a WHERE b.branch_id = a.branch_id
GROUP BY b.branch_id, b.branch_name;
c) SELECT b.branch_name, m.manager_name
FROM branches b ,managers m WHERE b.manager_id = m.manager_id;

d) SELECT c.customer_id, c.customer_name, AVG([Link]) AS avg_balance FROM


customers c, accounts a WHERE c.customer_id = a.customer_id GROUP BY
c.customer_id, c.customer_name;

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

What will be the output of the following query?


a. SELECT MONTHNAME(DOA) FROM student where Admno = 101;
b. SELECT YEAR(DOB) from student where Name like ‘%r’;
c. SELECT DAY(DOB) from student where city = ‘Kolkata’;
d. SELECT DAY(DOA) + DAY(DOB) from student where Admno = 102;
e. SELECT YEAR(DOA) – YEAR(DOB) from student where Admno = 102;

2. Consider the following table and answer the given questions.


Table Name: LIBRARY
Acsn_no B_name DOB Price Chapter City
101 Abed 2000-11-01 98 19 Delhi
102 Rxyz 1999-10-02 65.8 18 Kolkata
103 Azxc 2000-05-01 99 20 Delhi
104 Sven 1998-10-12 69.8 17 NULL

What will be the output of the following query?


a. SELECT LEFT(city,3) FROM LIBRARY WHERE chapter = 18;
b. SELECT LENGTH(B_name) FROM LIBRARY WHERE B_name LIKE ‘%b%’;
c. SELECT MID(city,4,3) from LIBRARY where Acsn_no = 102;
d. SELECT UCASE(city) from LIBRARY where Acsn_no=103;

3. Consider the following table and answer the given questions.


Table Name: Comp
EmpNo Emp- DOB Perc Age DOJ City
name
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

What will be the output of the following query?


a. SELECT LENGTH(city) FROM Comp where Empno = 104;
b. SELECT LEFT(DOA,4) FROM Comp Where Age = 18;
c. SELECT CONCAT (LEFT (empname,2), RIGHT (city,2)) From Comp where Empno = 101;
d. SELECT UCASE(CONCAT (RIGHT(empname,2), MID(city,2,2))) from comp where EmpNo =
102;
e. SELECT SUM(INSTR(city,’ol’)) from comp where empname like ‘_ _ _’;

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;

5. Consider the following table and answer the given questions.


Table Name: Dept
Acsnno D_name DOB Rank Num_years DOJ
1 Comp 2000-11-01 98 19 2010-18-16
2 Elec 1999-10-02 65.8 18 2020-05-12
3 Fin 2000-05-01 99 20 2020-04-01
4 Safety 1998-10-02 69.8 17 2022-04-01
What will be the output of the following query?
a. SELECT D_name from Dept where DOJ = (SELECT MAX(DOJ) From Dept);
b. SELECT D_name from Dept where Num_years >= 20;
c. SELECT AVG(Num_years) from Dept where Num_years < 20;
d. SELECT COUNT(Acsnno) from Dept where Num_years < 20 or Num_years > 18;
e. SELECT count (*) from Dept where D_name like ‘%e%’;

6. Consider the following table and answer the given questions.


Table Name : Student
EmpNo Emp-name DOB Perc Age DOJ 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
What will be the output of the following query?
a. Select count(city) from student;
b. Select count(distinct city) from student;
c. SELECT COUNT(*) from student;
d. SELECT city from student group by city having count(*)>1;
e. SELECT COUNT(*) from student group by city having Age > 20;

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

[Link] of the following is a DML command?


(a) Select (b) Update (c) Insert (d) All of these

4. Which command is used to delete a table? (in SQL)


(a) Delete (b) Drop (c) can’t be deleted (d) Remove

5. The char() function in MySql is an example of ____


(a) Math function (b) Text function (c) Date Function (d) Aggregate Function

6. Write the output of the following sql command. Select round(85.86);


(a) 85.00 (b) 85.87 (c) 85.0 (d) 86

7. Write the output of the following sql command. Select round(458.46,1);


(a) 458 (b) 458.5 (c) 459 (d) 458.6

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

9. Write the output of the following sql command. Select round(458.45,-1);


(a) 450 (b) 460 (c) 458 (d) 500

10. The substr() function in Mysql is an example of ___


(a) Math function (b) Text function (c) Date Function (d) Aggregate Function

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

12. The now() function in MySql is an example of ___


(a) Math function (b) Text function (c) Date Function (d) Aggregate Function

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

17. The avg() function in MySql is an example of _______


(a) Math function (b) Text function (c) Date Function (d) Aggregate Function

18. Which of the following is not a built in aggregate function in SQL?


(a) avg (b) max (c) total (d) count

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

22. What values does the count(*) function ignore?


(a) Repetitive values (b) Null values (c) Characters (d) integers

23. What is the meaning of “group by” clause in MySql?


(a) Group date by column values (b) Group date by row values
(c) Group data by column and row values (d) None of the above

24. Which clause is similar to “Having” Clause in MySql?


(a) SELECT (b) WHERE (c) FROM (d) None of the above

25. What is the meaning of “HAVING” clause in Mysql?


(a) To filter out the row values (b) To filter out the column values
(c) To filter out the row and column values (d) None of the above

26. “COUNT” keyword belongs to which categories in Mysql?


(a) Aggregate Functions (b) Operators (c) Clauses (d) All of the mentioned

27. Which among the following belongs to an “aggregate function”?


(a) COUNT (b) UPPER (c) LOWER (d) All of the mentioned

28. To specify condition with a GROUP BY clause, _____ clause is used.


(a) USE (b) WHERE (c) HAVING (d) LIKE

29. Only ________ functions are used with GROUP BY clause.


(a) Math function (b) Text function (c) Date/Time Function (d) Aggregate Function

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”);

3. Consider the below mentioned table of ‘CLOTH’


Decode Description Price Mcode Launch date
10001 Formal shirt 1250 M001 12-Jan-08
10020 Frock 760 M004 09-Sep-07
10012 Informal Shirt 1450 M002 16-Jun-08
10019 Evening Gown 850 M003 06-Jun-08
10090 Tulip Skirt 860 M002 31-Mar-07
10023 Pencil Skirt 1250 M003 19-Dec-08
10089 Slacks 860 M003 20-Oct-08
Write the commands for the following:
(i) Display first three letters of description e.g. ‘FRO’ for ‘FROCK’.
(ii) Display the description after removing leading spaces if any.
(iii) Display number of characters taken by each description.
(iv) Display the number of MCODE in the table.
(v) Display the day of the LAUNCHDATE. Eg. ‘Monday’,’Tuesday’ etc

4. Write the SQL statement for the following:


(i) To display names “Mr. James” and “Ms. Smith” in lower case.
(ii) To display current date and time.
(iii) To extract date from a given datetime value ‘2020-12-21 [Link]”.
(iv) To remove trailing spaces from string “Technology works”.

5. Consider the following table Teacher:


Tid Tname Department Salary NoofPeriods
100 Joseph Physics 45000 25
101 Lakshmi Hindi 55000 25
102 Neetu Chemistry 66000
103 John Physics 40000 25
Write SQL commands to:
a. Select record of teacher whose name starts with ‘N’.
b. Increase the salary of all the teachers by 10%
81
c. Display all the departments name.
d. Display all the teachers whose salary is less than 50000.
e. Display the name of the teachers who are getting salary between 40000 and 70000.

6. Consider the table TRAVEL given below:


No. Name TDate Km Code NOP
101 Janish Kin 2015-11-13 200 101 32
103 Vedika 2016-04-21 100 103 45
Sahai
105 Tarun Ram 2016-03-23 350 102 42
102 John Fen 2016-02-13 90 102 40
107 Ahmed Khan 2015-01-10 75 104 2
104 Raveena 2016-05-28 80 105 4

a. Write the correct query to give the following output:


No. Name TDate Km
101 Janish Kin 2015-11-13 200
105 Tarun Ram 2016-03-23 350

b. Write query to display maximum km from travel table.


c. Shaid had given the following command to arrange the data in ascending order of date.
Select * from travel where order by tdate; But he is not getting the desired result. Help him
by writing the correct command.
d. Write the query to count the number of codes in each code type from travel table.
e. Help Nuzut to write the command to display the name of the traveler whose travel date is in year
2016.

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

i. To display names of participants and points in descending order of points.


ii. To display House wise total points scored along with House name.
iii. Select average(points) from activity where house = “Gandhi” or House = “Bose”;
iv. Select count(distinct points) from activity;
v. select sum(points) from activity;

82

You might also like