You are on page 1of 601

This set of Advanced Python Interview Questions & Answers focuses on “Strings”.

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


1. class father:
2. def __init__(self, param):
3. self.o1 = param
4. class child(father):
5. def __init__(self, param):
6. self.o2 = param
7. >>>obj = child(22)
8. >>>print "%d %d" % (obj.o1, obj.o2)
a) None None
b) None 22
c) 22 None
d) Error is generated
Answer: d
Explanation: self.o1 was never created.
2. What will be the output of the following Python code?
1. class tester:
2. def __init__(self, id):
3. self.id = str(id)
4. id="224"
5. >>>temp = tester(12)
6. >>>print(temp.id)
a) 224
b) Error
c) 12
d) None
Answer: c
Explanation: Id in this case will be the attribute of the class.
3. What will be the output of the following Python code?
1. >>>example = "snow world"
2. >>>print("%s" % example[4:7])
a) wo
b) world
c) sn
d) rl
Answer: a
Explanation: Execute in the shell and verify.
4. What will be the output of the following Python code?
1. >>>example = "snow world"
2. >>>example[3] = 's'
3. >>>print example
a) snow
b) snow world
c) Error
d) snos world
Answer: c
Explanation: Strings cannot be modified.
5. What will be the output of the following Python code?
1. >>>max("what are you")
a) error
b) u
c) t
d) y
Answer: d
Explanation: Max returns the character with the highest ascii value.
6. Given a string example=”hello” what is the output of example.count(‘l’)?
a) 2
b) 1
c) None
d) 0
Answer: a
Explanation: l occurs twice in hello.
7. What will be the output of the following Python code?
1. >>>example = "helle"
2. >>>example.find("e")
a) Error
b) -1
c) 1
d) 0
Answer: c
Explanation: Returns lowest index.
8. What will be the output of the following Python code?
1. >>>example = "helle"
2. >>>example.rfind("e")
a) -1
b) 4
c) 3
d) 1
Answer: b
Explanation: Returns highest index.
9. What will be the output of the following Python code?
1. >>>example="helloworld"
2. >>>example[::-1].startswith("d")
a) dlrowolleh
b) True
c) -1
d) None
Answer: b
Explanation: Starts with checks if the given string starts with the parameter that is passed.
10. To concatenate two strings to a third what statements are applicable?
a) s3 = s1 . s2
b) s3 = s1.add(s2)
c) s3 = s1.__add__(s2)
d) s3 = s1 * s2
Answer: c
Explanation: __add__ is another method that can be used for concatenation.
To practice all advanced interview questions on Python, .
This set of Advanced Python Questions & Answers focuses on “While and For Loops – 2”.
1. What will be the output of the following Python code?
i=0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print(0)
a) 0 1 2 0
b) 0 1 2
c) error
d) none of the mentioned
Answer: b
Explanation: The else part is not executed if control breaks out of the loop.
2. What will be the output of the following Python code?
i=0
while i < 3:
print(i)
i += 1
else:
print(0)
a) 0 1 2 3 0
b) 0 1 2 0
c) 0 1 2
d) error
Answer: b
Explanation: The else part is executed when the condition in the while statement is false.
3. What will be the output of the following Python code?
x = "abcdef"
while i in x:
print(i, end=" ")
a) a b c d e f
b) abcdef
c) i i i i i i …
d) error
Answer: d
Explanation: NameError, i is not defined.
4. What will be the output of the following Python code?
x = "abcdef"
i = "i"
while i in x:
print(i, end=" ")
a) no output
b) i i i i i i …
c) a b c d e f
d) abcdef
Answer: a
Explanation: “i” is not in “abcdef”.
5. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")
a) no output
b) i i i i i i …
c) a a a a a a …
d) a b c d e f
Answer: c
Explanation: As the value of i or x isn’t changing, the condition will always evaluate to True.
6. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x:
print('i', end = " ")
a) no output
b) i i i i i i …
c) a a a a a a …
d) a b c d e f
Answer: b
Explanation: Here i i i i i … printed continuously because as the value of i or x isn’t changing, the condition will always evaluate to
True. But also here we use a citation marks on “i”, so, here i treated as a string, not like a variable.
7. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x:
x = x[:-1]
print(i, end = " ")
a) i i i i i i
b) a a a a a a
c) a a a a a
d) none of the mentioned
Answer: b
Explanation: The string x is being shortened by one character in each iteration.
8. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x[:-1]:
print(i, end = " ")
a) a a a a a
b) a a a a a a
c) a a a a a a …
d) a
Answer: c
Explanation: String x is not being altered and i is in x[:-1].
9. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x:
x = x[1:]
print(i, end = " ")
a) a a a a a a
b) a
c) no output
d) error
Answer: b
Explanation: The string x is being shortened by one character in each iteration.
10. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x[1:]:
print(i, end = " ")
a) a a a a a a
b) a
c) no output
d) error
Answer: c
Explanation: i is not in x[1:].
To practice all advanced questions on Python, .
This set of Basic Python Questions & Answers focuses on “Strings”.
1. What will be the output of the following Python code?
print("abc DEF".capitalize())
a) abc def
b) ABC DEF
c) Abc def
d) Abc Def
Answer: c
Explanation: The first letter of the string is converted to uppercase and the others are converted to lowercase.
2. What will be the output of the following Python code?
print("abc. DEF".capitalize())
a) abc. def
b) ABC. DEF
c) Abc. def
d) Abc. Def
Answer: c
Explanation: The first letter of the string is converted to uppercase and the others are converted to lowercase.
3. What will be the output of the following Python code?
print("abcdef".center())
a) cd
b) abcdef
c) error
d) none of the mentioned
Answer: c
Explanation: The function center() takes at least one parameter.
4. What will be the output of the following Python code?
print("abcdef".center(0))
a) cd
b) abcdef
c) error
d) none of the mentioned
Answer: b
Explanation: The entire string is printed when the argument passed to center() is less than the length of the string.
5. What will be the output of the following Python code?
print('*', "abcdef".center(7), '*')
a) * abcdef *
b) * abcdef *
c) *abcdef *
d) * abcdef*
Answer: b
Explanation: Padding is done towards the left-hand-side first when the final string is of odd length. Extra spaces are present
since we haven’t overridden the value of sep.
6. What will be the output of the following Python code?
print('*', "abcdef".center(7), '*', sep='')
a) * abcdef *
b) * abcdef *
c) *abcdef *
d) * abcdef*
Answer: d
Explanation: Padding is done towards the left-hand-side first when the final string is of odd length.
7. What will be the output of the following Python code?
print('*', "abcde".center(6), '*', sep='')
a) * abcde *
b) * abcde *
c) *abcde *
d) * abcde*
Answer: c
Explanation: Padding is done towards the right-hand-side first when the final string is of even length.
8. What will be the output of the following Python code?
print("abcdef".center(7, 1))
a) 1abcdef
b) abcdef1
c) abcdef
d) error
Answer: d
Explanation: TypeError, the fill character must be a character, not an int.
9. What will be the output of the following Python code?
print("abcdef".center(7, '1'))
a) 1abcdef
b) abcdef1
c) abcdef
d) error
Answer: a
Explanation: The character ‘1’ is used for padding instead of a space.
10. What will be the output of the following Python code?
print("abcdef".center(10, '12'))
a) 12abcdef12
b) abcdef1212
c) 1212abcdef
d) error
Answer: d
Explanation: The fill character must be exactly one character long.
To practice all basic questions on Python, .
This set of Python Aptitude Test focuses on “Random module”.
1. What the does random.seed(3) return?
a) True
b) None
c) 3
d) 1
Answer: b
Explanation: The function random.seed() always returns a None.
2. Which of the following cannot be returned by random.randrange(4)?
a) 0
b) 3
c) 2.3
d) none of the mentioned
Answer: c
Explanation: Only integers can be returned.
3. Which of the following is equivalent to random.randrange(3)?
a) range(3)
b) random.choice(range(0, 3))
c) random.shuffle(range(3))
d) random.select(range(3))
Answer: b
Explanation: It returns one number from the given range.
4. The function random.randint(4) can return only one of the following values. Which?
a) 4
b) 3.4
c) error
d) 5
Answer: c
Explanation: Error, the function takes two arguments.
5. Which of the following is equivalent to random.randint(3, 6)?
a) random.choice([3, 6])
b) random.randrange(3, 6)
c) 3 + random.randrange(3)
d) 3 + random.randrange(4)
Answer: d
Explanation: random.randint(3, 6) can return any one of 3, 4, 5 and 6.
6. Which of the following will not be returned by random.choice(“1 ,”)?
a) 1
b) (space)
c) ,
d) none of the mentioned
Answer: d
Explanation: Any of the characters present in the string may be returned.
7. Which of the following will never be displayed on executing print(random.choice({0: 1, 2: 3}))?
a) 0
b) 1
c) KeyError: 1
d) none of the mentioned
Answer: a
Explanation: It will not print 0 but dict[0] i.e. 1 may be printed.
8. What does random.shuffle(x) do when x = [1, 2, 3]?
a) error
b) do nothing, it is a placeholder for a function that is yet to be implemented
c) shuffle the elements of the list in-place
d) none of the mentioned
Answer: c
Explanation: The elements of the list passed to it are shuffled in-place.
9. Which type of elements are accepted by random.shuffle()?
a) strings
b) lists
c) tuples
d) integers
Answer: b
Explanation: Strings and tuples are immutable and an integer has no len().
10. What is the range of values that random.random() can return?
a) [0.0, 1.0]
b) (0.0, 1.0]
c) (0.0, 1.0)
d) [0.0, 1.0)
Answer: d
Explanation: Any number that is greater than or equal to 0.0 and lesser than 1.0 can be returned.
To practice all aptitude test on Python, .
This set of Python Certification Questions & Answers focuses on “Files”.
1. Which are the two built-in functions to read a line of text from standard input, which by default comes from the keyboard?
a) Raw_input & Input
b) Input & Scan
c) Scan & Scanner
d) Scanner
Answer: a
Explanation: Python provides two built-in functions to read a line of text from standard input, which by default comes from the
keyboard. These functions are:
raw_input and input
2. What will be the output of the following Python code?
1. str = raw_input("Enter your input: ");
2. print "Received input is : ", str
a)
Enter your input: Hello Python
Received input is : Hello Python
b)
Enter your input: Hello Python
Received input is : Hello
c)
Enter your input: Hello Python
Received input is : Python
d) None of the mentioned
Answer: a
Explanation: The raw_input([prompt]) function reads one line from standard input and returns it as a string. This would prompt you
to enter any string and it would display same string on the screen. When I typed “Hello Python!”
3. What will be the output of the following Python code?
1. str = input("Enter your input: ");
2. print "Received input is : ", str
a)
Enter your input: [x*5 for x in range(2,10,2)]
Received input is : [x*5 for x in range(2,10,2)]
b)
Enter your input: [x*5 for x in range(2,10,2)]
Received input is : [10, 30, 20, 40]
c)
Enter your input: [x*5 for x in range(2,10,2)]
Received input is : [10, 10, 30, 40]
d) None of the mentioned
Answer: a
Explanation: None.
4. Which one of the following is not attributes of file?
a) closed
b) softspace
c) rename
d) mode
Answer: c
Explanation: rename is not the attribute of file rest all are files attributes.
Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true otherwise.
5. What is the use of tell() method in python?
a) tells you the current position within the file
b) tells you the end position within the file
c) tells you the file is opened or not
d) none of the mentioned
Answer: a
Explanation: The tell() method tells you the current position within the file; in other words, the next read or write will occur at that
many bytes from the beginning of the file.
6. What is the current syntax of rename() a file?
a) rename(current_file_name, new_file_name)
b) rename(new_file_name, current_file_name,)
c) rename(()(current_file_name, new_file_name))
d) none of the mentioned
Answer: a
Explanation: This is the correct syntax which has shown below.
rename(current_file_name, new_file_name)
7. What is the current syntax of remove() a file?
a) remove(file_name)
b) remove(new_file_name, current_file_name,)
c) remove(() , file_name))
d) none of the mentioned
Answer: a
Explanation: remove(file_name)
8. What will be the output of the following Python code?
1. fo = open("foo.txt", "rw+")
2. print "Name of the file: ", fo.name
3. # Assuming file has following 5 lines
4. # This is 1st line
5. # This is 2nd line
6. # This is 3rd line
7. # This is 4th line
8. # This is 5th line
9. for index in range(5):
10. line = fo.next()
11. print "Line No %d - %s" % (index, line)
12. # Close opened file
13. fo.close()
a) Compilation Error
b) Syntax Error
c) Displays Output
d) None of the mentioned
Answer: c
Explanation: It displays the output as shown below. The method next() is used when a file is used as an iterator, typically in a
loop, the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit.
Output:
Name of the file: foo.txt
Line No 0 - This is 1st line

Line No 1 - This is 2nd line

Line No 2 - This is 3rd line

Line No 3 - This is 4th line

Line No 4 - This is 5th line


9. What is the use of seek() method in files?
a) sets the file’s current position at the offset
b) sets the file’s previous position at the offset
c) sets the file’s current position within the file
d) none of the mentioned
Answer: a
Explanation: Sets the file’s current position at the offset. The method seek() sets the file’s current position at the offset.
Following is the syntax for seek() method:
fileObject.seek(offset[, whence])
Parameters
offset — This is the position of the read/write pointer within the file.
whence — This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative
to the current position and 2 means seek relative to the file’s end.
10. What is the use of truncate() method in file?
a) truncates the file size
b) deletes the content of the file
c) deletes the file size
d) none of the mentioned
Answer: a
Explanation: The method truncate() truncates the file size. Following is the syntax for truncate() method:
fileObject.truncate( [ size ])
Parameters
size — If this optional argument is present, the file is truncated to (at most) that size.
To practice all certification questions on Python, .
This set of Python Coding Interview Questions & Answers focuses on “Lists”.
1. What will be the output of the following Python code?
1. >>>names = ['Amir', 'Bear', 'Charlton', 'Daman']
2. >>>print(names[-1][-1])
a) A
b) Daman
c) Error
d) n
Answer: d
Explanation: Execute in the shell to verify.
2. What will be the output of the following Python code?
1. names1 = ['Amir', 'Bear', 'Charlton', 'Daman']
2. names2 = names1
3. names3 = names1[:]
4. names2[0] = 'Alice'
5. names3[1] = 'Bob'
6. sum = 0
7. for ls in (names1, names2, names3):
8. if ls[0] == 'Alice':
9. sum += 1
10. if ls[1] == 'Bob':
11. sum += 10
12. print sum
a) 11
b) 12
c) 21
d) 22
Answer: b
Explanation: When assigning names1 to names2, we create a second reference to the same list. Changes to names2 affect
names1. When assigning the slice of all elements in names1 to names3, we are creating a full copy of names1 which can be
modified independently.
3. Suppose list1 is [1, 3, 2], What is list1 * 2?
a) [2, 6, 4]
b) [1, 3, 2, 1, 3]
c) [1, 3, 2, 1, 3, 2]
d) [1, 3, 2, 3, 2, 1]
Answer: c
Explanation: Execute in the shell and verify.
4. Suppose list1 = [0.5 * x for x in range(0, 4)], list1 is:
a) [0, 1, 2, 3]
b) [0, 1, 2, 3, 4]
c) [0.0, 0.5, 1.0, 1.5]
d) [0.0, 0.5, 1.0, 1.5, 2.0]
Answer: c
Explanation: Execute in the shell to verify.
5. What will be the output of the following Python code?
1. >>>list1 = [11, 2, 23]
2. >>>list2 = [11, 2, 2]
3. >>>list1 < list2 is
a) True
b) False
c) Error
d) None
Answer: b
Explanation: Elements are compared one by one.
6. To add a new element to a list we use which command?
a) list1.add(5)
b) list1.append(5)
c) list1.addLast(5)
d) list1.addEnd(5)
Answer: b
Explanation: We use the function append to add an element to the list.
7. To insert 5 to the third position in list1, we use which command?
a) list1.insert(3, 5)
b) list1.insert(2, 5)
c) list1.add(3, 5)
d) list1.append(3, 5)
Answer: b
Explanation: Execute in the shell to verify.
8. To remove string “hello” from list1, we use which command?
a) list1.remove(“hello”)
b) list1.remove(hello)
c) list1.removeAll(“hello”)
d) list1.removeOne(“hello”)
Answer: a
Explanation: Execute in the shell to verify.
9. Suppose list1 is [3, 4, 5, 20, 5], what is list1.index(5)?
a) 0
b) 1
c) 4
d) 2
Answer: d
Explanation: Execute help(list.index) to get details.
10. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1.count(5)?
a) 0
b) 4
c) 1
d) 2
Answer: d
Explanation: Execute in the shell to verify.
To practice all coding interview questions on Python, .
This set of Python Coding Questions & Answers focuses on “Strings”.
1. What is “Hello”.replace(“l”, “e”)?
a) Heeeo
b) Heelo
c) Heleo
d) None
Answer: a
Explanation: Execute in shell to verify.
2. To retrieve the character at index 3 from string s=”Hello” what command do we execute (multiple answers allowed)?
a) s[]
b) s.getitem(3)
c) s.__getitem__(3)
d) s.getItem(3)
Answer: c
Explanation: __getitem(..) can be used to get character at index specified as parameter.
3. To return the length of string s what command do we execute?
a) s.__len__()
b) len(s)
c) size(s)
d) s.size()
Answer: a
Explanation: Execute in shell to verify.
4. If a class defines the __str__(self) method, for an object obj for the class, you can use which command to invoke the __str__
method.
a) obj.__str__()
b) str(obj)
c) print obj
d) all of the mentioned
Answer: d
Explanation: Execute in shell to verify.
5. To check whether string s1 contains another string s2, use ________
a) s1.__contains__(s2)
b) s2 in s1
c) s1.contains(s2)
d) si.in(s2)
Answer: a
Explanation: s2 in s1 works in the same way as calling the special function __contains__ .
6. Suppose i is 5 and j is 4, i + j is same as ________
a) i.__add(j)
b) i.__add__(j)
c) i.__Add(j)
d) i.__ADD(j)
Answer: b
Explanation: Execute in shell to verify.
7. What will be the output of the following Python code?
1. class Count:
2. def __init__(self, count = 0):
3. self.__count = count
4. c1 = Count(2)
5. c2 = Count(2)
6. print(id(c1) == id(c2), end = " ")
7. s1 = "Good"
8. s2 = "Good"
9. print(id(s1) == id(s2))
a) True False
b) True True
c) False True
d) False False
Answer: c
Explanation: Execute in the shell objects cannot have same id, however in the case of strings its different.
8. What will be the output of the following Python code?
1. class Name:
2. def __init__(self, firstName, mi, lastName):
3. self.firstName = firstName
4. self.mi = mi
5. self.lastName = lastName
6. firstName = "John"
7. name = Name(firstName, 'F', "Smith")
8. firstName = "Peter"
9. name.lastName = "Pan"
10. print(name.firstName, name.lastName)
a) Peter Pan
b) John Pan
c) Peter Smith
d) John Smith
Answer: b
Explanation: Execute in the shell to verify.
9. What function do you use to read a string?
a) input(“Enter a string”)
b) eval(input(“Enter a string”))
c) enter(“Enter a string”)
d) eval(enter(“Enter a string”))
Answer: a
Explanation: Execute in shell to verify.
10. Suppose x is 345.3546, what is format(x, “10.3f”) (_ indicates space).
a) __345.355
b) ___345.355
c) ____345.355
d) _____345.354
Answer: b
Explanation: Execute in the shell to verify.
To practice all coding questions on Python, .
This set of Python Developer Interview Questions & Answers focuses on “Math – 3”.
1. What is the result of math.trunc(3.1)?
a) 3.0
b) 3
c) 0.1
d) 1
Answer: b
Explanation: The integral part of the floating point number is returned.
2. What is the output of print(math.trunc(‘3.1’))?
a) 3
b) 3.0
c) error
d) none of the mentioned
Answer: c
Explanation: TypeError, a string does not have __trunc__ method.
3. Which of the following is the same as math.exp(p)?
a) e ** p
b) math.e ** p
c) p ** e
d) p ** math.e
Answer: b
Explanation: math.e is the constant defined in the math module.
4. What is returned by math.expm1(p)?
a) (math.e ** p) – 1
b) math.e ** (p – 1)
c) error
d) none of the mentioned
Answer: a
Explanation: One is subtracted from the result of math.exp(p) and returned.
5. What is the default base used when math.log(x) is found?
a) e
b) 10
c) 2
d) none of the mentioned
Answer: a
Explanation: The natural log of x is returned by default.
6. Which of the following aren’t defined in the math module?
a) log2()
b) log10()
c) logx()
d) none of the mentioned
Answer: c
Explanation: log2() and log10() are defined in the math module.
7. What is returned by int(math.pow(3, 2))?
a) 6
b) 9
c) error, third argument required
d) error, too many arguments
Answer: b
Explanation: math.pow(a, b) returns a ** b.
8. What is output of print(math.pow(3, 2))?
a) 9
b) 9.0
c) None
d) None of the mentioned
Answer: b
Explanation: math.pow() returns a floating point number.
9. What is the value of x if x = math.sqrt(4)?
a) 2
b) 2.0
c) (2, -2)
d) (2.0, -2.0)
Answer: b
Explanation: The function returns one floating point number.
10. What does math.sqrt(X, Y) do?
a) calculate the Xth root of Y
b) calculate the Yth root of X
c) error
d) return a tuple with the square root of X and Y
Answer: c
Explanation: The function takes only one argument.
To practice all developer interview questions on Python, .
This set of Python Developer Questions & Answers focuses on “Mathematical Functions”.
1. What does the function math.frexp(x) return?
a) a tuple containing the mantissa and the exponent of x
b) a list containing the mantissa and the exponent of x
c) a tuple containing the mantissa of x
d) a list containing the exponent of x
Answer: a
Explanation: It returns a tuple with two elements. The first element is the mantissa and the second element is the exponent.
2. What is the result of math.fsum([.1 for i in range(20)])?
a) 2.0
b) 20
c) 2
d) 2.0000000000000004
Answer: a
Explanation: The function fsum returns an accurate floating point sum of the elements of its argument.
3. What is the result of sum([.1 for i in range(20)])?
a) 2.0
b) 20
c) 2
d) 2.0000000000000004
Answer: d
Explanation: There is some loss of accuracy when we use sum with floating point numbers. Hence the function fsum is
preferable.
4. What is returned by math.isfinite(float(‘inf’))?
a) True
b) False
c) None
d) error
Answer: b
Explanation: float(‘inf’) is not a finite number.
5. What is returned by math.isfinite(float(‘nan’))?
a) True
b) False
c) None
d) error
Answer: b
Explanation: float(‘nan’) is not a finite number.
6. What is x if x = math.isfinite(float(‘0.0’))?
a) True
b) False
c) None
d) error
Answer: a
Explanation: float(‘0.0’) is a finite number.
7. What will be the output of the following Python code?
>>> -float('inf') + float('inf')
a) inf
b) nan
c) 0
d) 0.0
Answer: b
Explanation: The result of float(‘inf’)-float(‘inf’) is undefined.
8. What will be the output of the following Python code?
print(math.isinf(float('-inf')))
a) error, the minus sign shouldn’t have been inside the brackets
b) error, there is no function called isinf
c) True
d) False
Answer: c
Explanation: -float(‘inf’) is the same as float(‘-inf’).
9. What is the value of x if x = math.ldexp(0.5, 1)?
a) 1
b) 2.0
c) 0.5
d) none of the mentioned
Answer: d
Explanation: The value returned by ldexp(x, y) is x * (2 ** y). In the current case x is 1.0.
10. What is returned by math.modf(1.0)?
a) (0.0, 1.0)
b) (1.0, 0.0)
c) (0.5, 1)
d) (0.5, 1.0)
Answer: a
Explanation: The first element is the fractional part and the second element is the integral part of the argument.
To practice all developer questions on Python, .
This set of Python Questions & Answers for Exams focuses on “Operating System”.
1. What does os.name contain?
a) the name of the operating system dependent module imported
b) the address of the module os
c) error, it should’ve been os.name()
d) none of the mentioned
Answer: a
Explanation: It contains the name of the operating system dependent module imported such as ‘posix’, ‘java’ etc.
2. What does print(os.geteuid()) print?
a) the group id of the current process
b) the user id of the current process
c) both the group id and the user of the current process
d) none of the mentioned
Answer: b
Explanation: os.geteuid() gives the user id while the os.getegid() gives the group id.
3. What does os.getlogin() return?
a) name of the current user logged in
b) name of the superuser
c) gets a form to login as a different user
d) all of the mentioned
Answer: a
Explanation: It returns the name of the user who is currently logged in and is running the script.
4. What does os.close(f) do?
a) terminate the process f
b) terminate the process f if f is not responding
c) close the file descriptor f
d) return an integer telling how close the file pointer is to the end of file
Answer: c
Explanation: When a file descriptor is passed as an argument to os.close() it will be closed.
5. What does os.fchmod(fd, mode) do?
a) change permission bits of the file
b) change permission bits of the directory
c) change permission bits of either the file or the directory
d) none of the mentioned
Answer: a
Explanation: The arguments to the function are a file descriptor and the new mode.
6. Which of the following functions can be used to read data from a file using a file descriptor?
a) os.reader()
b) os.read()
c) os.quick_read()
d) os.scan()
Answer: b
Explanation: None of the other functions exist.
7. Which of the following returns a string that represents the present working directory?
a) os.getcwd()
b) os.cwd()
c) os.getpwd()
d) os.pwd()
Answer: a
Explanation: The function getcwd() (get current working directory) returns a string that represents the present working directory.
8. What does os.link() do?
a) create a symbolic link
b) create a hard link
c) create a soft link
d) none of the mentioned
Answer: b
Explanation: os.link(source, destination) will create a hard link from source to destination.
9. Which of the following can be used to create a directory?
a) os.mkdir()
b) os.creat_dir()
c) os.create_dir()
d) os.make_dir()
Answer: a
Explanation: The function mkdir() creates a directory in the path specified.
10. Which of the following can be used to create a symbolic link?
a) os.symlink()
b) os.symb_link()
c) os.symblin()
d) os.ln()
Answer: a
Explanation: It is the function that allows you to create a symbolic link.
To practice all exam questions on Python, .
This set of Python Interview Questions and Answers for Experienced people focuses on “Operator Overloading”
1. Which function is called when the following Python code is executed?
f = foo()
format(f)
a) format()
b) __format__()
c) str()
d) __str__()
Answer: d
Explanation: Both str(f) and format(f) call f.__str__().
2. Which of the following Python code will print True?
a = foo(2)
b = foo(3)
print(a < b)
a)
class foo:
def __init__(self, x):
self.x = x
def __lt__(self, other):
if self.x < other.x:
return False
else:
return True
b)
class foo:
def __init__(self, x):
self.x = x
def __less__(self, other):
if self.x > other.x:
return False
else:
return True
c)
class foo:
def __init__(self, x):
self.x = x
def __lt__(self, other):
if self.x < other.x:
return True
else:
return False
d)
class foo:
def __init__(self, x):
self.x = x
def __less__(self, other):
if self.x < other.x:
return False
else:
return True
Answer: c
Explanation: __lt__ overloads the < operator>.

3. Which function overloads the + operator?


a) __add__()
b) __plus__()
c) __sum__()
d) none of the mentioned
Answer: a
Explanation: Refer documentation.
4. Which operator is overloaded by __invert__()?
a) !
b) ~
c) ^
d) –
Answer: b
Explanation: __invert__() overloads ~.
5. Which function overloads the == operator?
a) __eq__()
b) __equ__()
c) __isequal__()
d) none of the mentioned
Answer: a
Explanation: The other two do not exist.
6. Which operator is overloaded by __lg__()?
a) <
b) >
c) !=
d) none of the mentioned
Answer: d
Explanation: __lg__() is invalid.
7. Which function overloads the >> operator?
a) __more__()
b) __gt__()
c) __ge__()
d) none of the mentioned
Answer: d
Explanation: __rshift__() overloads the >> operator.
8. Let A and B be objects of class Foo. Which functions are called when print(A + B) is executed?
a) __add__(), __str__()
b) __str__(), __add__()
c) __sum__(), __str__()
d) __str__(), __sum__()
Answer: a
Explanation: The function __add__() is called first since it is within the bracket. The function __str__() is then called on the object
that we received after adding A and B.
9. Which operator is overloaded by the __or__() function?
a) ||
b) |
c) //
d) /
Answer: b
Explanation: The function __or__() overloads the bitwise OR operator |.
10. Which function overloads the // operator?
a) __div__()
b) __ceildiv__()
c) __floordiv__()
d) __truediv__()
Answer: c
Explanation: __floordiv__() is for //.
To practice all interview questions on Python for experienced people, .
This set of Python Interview Questions and Answers for freshers focuses on “Mapping Functions”.
1. What will be the output of the following Python code?
x = [[0], [1]]
print((' '.join(list(map(str, x)))))
a) (‘[0] [1]’,)
b) (’01’,)
c) [0] [1]
d) 01
Answer: c
Explanation: (element) is the same as element. It is not a tuple with one item.
2. What will be the output of the following Python code?
x = [[0], [1]]
print((' '.join(list(map(str, x))),))
a) (‘[0] [1]’,)
b) (’01’)
c) [0] [1]
d) 01
Answer: a
Explanation: (element,) is not the same as element. It is a tuple with one item.
3. What will be the output of the following Python code?
x = [34, 56]
print((''.join(list(map(str, x))),))
a) 3456
b) (3456)
c) (‘3456’)
d) (‘3456’,)
Answer: d
Explanation: We have created a tuple with one string in it.
4. What will be the output of the following Python code?
x = [34, 56]
print((''.join(list(map(str, x)))),)
a) 3456
b) (3456)
c) (‘3456’)
d) (‘3456’,)
Answer: a
Explanation: We have just created a string.
5. What will be the output of the following Python code?
x = [34, 56]
print(len(map(str, x)))
a) [34, 56]
b) [’34’, ’56’]
c) 34 56
d) error
Answer: d
Explanation: TypeError, map has no len.
6. What will be the output of the following Python code?
x = 'abcd'
print(list(map(list, x)))
a) [‘a’, ‘b’, ‘c’, ‘d’]
b) [‘abcd’]
c) [[‘a’], [‘b’], [‘c’], [‘d’]]
d) none of the mentioned
Answer: c
Explanation: list() is performed on each character in x.
7. What will be the output of the following Python code?
x = abcd
print(list(map(list, x)))
a) [‘a’, ‘b’, ‘c’, ‘d’]
b) [‘abcd’]
c) [[‘a’], [‘b’], [‘c’], [‘d’]]
d) none of the mentioned
Answer: d
Explanation: NameError, we have not defined abcd.
8. What will be the output of the following Python code?
x = 1234
print(list(map(list, x)))
a) [1, 2, 3, 4]
b) [1234]
c) [[1], [2], [3], [4]]
d) none of the mentioned
Answer: d
Explanation: TypeError, int is not iterable.
9. What will be the output of the following Python code?
x = 1234
print(list(map(list, [x])))
a) [1, 2, 3, 4]
b) [1234]
c) [[1], [2], [3], [4]]
d) none of the mentioned
Answer: d
Explanation: TypeError, int is not iterable.
10. What will be the output of the following Python code?
x = 'abcd'
print(list(map([], x)))
a) [‘a’, ‘b’, ‘c’, ‘d’]
b) [‘abcd’]
c) [[‘a’], [‘b’], [‘c’], [‘d’]]
d) none of the mentioned
Answer: d
Explanation: TypeError, list object is not callable.
11. Is Python code compiled or interpreted?
a) Python code is only compiled
b) Python code is both compiled and interpreted
c) Python code is only interpreted
d) Python code is neither compiled nor interpreted
Answer: b
Explanation: Many languages have been implemented using both compilers and interpreters, including C, Pascal, and Python.
12. Which of these is the definition for packages in Python?
a) A folder of python modules
b) A set of programs making use of Python modules
c) A set of main modules
d) A number of files containing Python definitions and statements
Answer: a
Explanation: A folder of python programs is called as a package of modules.
13. Which of these is false about a package?
a) A package can have subfolders and modules
b) Each import package need not introduce a namespace
c) import folder.subfolder.mod1 imports packages
d) from folder.subfolder.mod1 import objects imports packages
Answer: b
Explanation: Packages provide a way of structuring Python namespace. Each import package introduces a namespace.
To practice all interview questions on Python for freshers, .
This set of Python Interview Questions & Answers focuses on “Mapping Functions”.
1. What will be the output of the following Python code?
elements = [0, 1, 2]
def incr(x):
return x+1
print(list(map(elements, incr)))
a) [1, 2, 3]
b) [0, 1, 2]
c) error
d) none of the mentioned
Answer: c
Explanation: The list should be the second parameter to the mapping function.
2. What will be the output of the following Python code?
elements = [0, 1, 2]
def incr(x):
return x+1
print(list(map(incr, elements)))
a) [1, 2, 3]
b) [0, 1, 2]
c) error
d) none of the mentioned
Answer: a
Explanation: Each element of the list is incremented.
3. What will be the output of the following Python code?
x = ['ab', 'cd']
print(list(map(upper, x)))
a) [‘AB’, ‘CD’]
b) [‘ab’, ‘cd’]
c) error
d) none of the mentioned
Answer: c
Explanation: A NameError occurs because upper is a class method.
4. What will be the output of the following Python code?
def to_upper(k):
return k.upper()
x = ['ab', 'cd']
print(list(map(upper, x)))
a) [‘AB’, ‘CD’]
b) [‘ab’, ‘cd’]
c) none of the mentioned
d) error
Answer: d
Explanation: A NameError occurs because upper is a class method.
5. What will be the output of the following Python code?
def to_upper(k):
return k.upper()
x = ['ab', 'cd']
print(list(map(to_upper, x)))
a) [‘AB’, ‘CD’]
b) [‘ab’, ‘cd’]
c) none of the mentioned
d) error
Answer: a
Explanation: Each element of the list is converted to uppercase.
6. What will be the output of the following Python code?
def to_upper(k):
k.upper()
x = ['ab', 'cd']
print(list(map(to_upper, x)))
a) [‘AB’, ‘CD’]
b) [‘ab’, ‘cd’]
c) none of the mentioned
d) error
Answer: c
Explanation: A list of Nones is printed as to_upper() returns None.
7. What will be the output of the following Python code?
x = ['ab', 'cd']
print(map(len, x))
a) [‘ab’, ‘cd’]
b) [2, 2]
c) [‘2’, ‘2’]
d) none of the mentioned
Answer: d
Explanation: A map object is generated by map(). We must convert this to a list to be able to print it in a human readable form.
8. What will be the output of the following Python code?
x = ['ab', 'cd']
print(list(map(len, x)))
a) [‘ab’, ‘cd’]
b) [2, 2]
c) [‘2’, ‘2’]
d) none of the mentioned
Answer: b
Explanation: The length of each string is 2.
9. What will be the output of the following Python code?
x = ['ab', 'cd']
print(len(map(list, x)))
a) [2, 2]
b) 2
c) 4
d) none of the mentioned
Answer: d
Explanation: A TypeError occurs as map has no len().
10. What will be the output of the following Python code?
x = ['ab', 'cd']
print(len(list(map(list, x))))
a) 2
b) 4
c) error
d) none of the mentioned
Answer: a
Explanation: The outer list has two lists in it. So it’s length is 2.
To practice all interview questions on Python, .
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Basic Operators”.

1. Which is the correct operator for power(x y )?


a) X^y
b) X**y
c) X^^y
d) None of the mentioned
Answer: b
Explanation: In python, power operator is x**y i.e. 2**3=8.
2. Which one of these is floor division?
a) /
b) //
c) %
d) None of the mentioned
Answer: b
Explanation: When both of the operands are integer then python chops out the fraction part and gives you the round off value, to
get the accurate answer use floor division. This is floor division. For ex, 5/2 = 2.5 but both of the operands are integer so answer
of this expression in python is 2. To get the 2.5 answer, use floor division.
3. What is the order of precedence in python?
i) Parentheses
ii) Exponential
iii) Multiplication
iv) Division
v) Addition
vi) Subtraction
a) i,ii,iii,iv,v,vi
b) ii,i,iii,iv,v,vi
c) ii,i,iv,iii,v,vi
d) i,ii,iii,iv,vi,v
Answer: a
Explanation: For order of precedence, just remember this PEMDAS (similar to BODMAS).
4. What is the answer to this expression, 22 % 3 is?
a) 7
b) 1
c) 0
d) 5
Answer: b
Explanation: Modulus operator gives the remainder. So, 22%3 gives the remainder, that is, 1.
5. Mathematical operations can be performed on a string.
a) True
b) False
Answer: b
Explanation: You can’t perform mathematical operation on string even if the string is in the form: ‘1234…’.
6. Operators with the same precedence are evaluated in which manner?
a) Left to Right
b) Right to Left
c) Can’t say
d) None of the mentioned
Answer: a
Explanation: None.
7. What is the output of this expression, 3*1**3?
a) 27
b) 9
c) 3
d) 1
Answer: c
Explanation: First this expression will solve 1**3 because exponential has higher precedence than multiplication, so 1**3 = 1 and
3*1 = 3. Final answer is 3.
8. Which one of the following has the same precedence level?
a) Addition and Subtraction
b) Multiplication, Division and Addition
c) Multiplication, Division, Addition and Subtraction
d) Addition and Multiplication
Answer: a
Explanation: “Addition and Subtraction” are at the same precedence level. Similarly, “Multiplication and Division” are at the
same precedence level. However, Multiplication and Division operators are at a higher precedence level than Addition and
Subtraction operators.
9. The expression Int(x) implies that the variable x is converted to integer.
a) True
b) False
Answer: a
Explanation: None.
10. Which one of the following has the highest precedence in the expression?
a) Exponential
b) Addition
c) Multiplication
d) Parentheses
Answer: d
Explanation: Just remember: PEMDAS, that is, Parenthesis, Exponentiation, Division, Multiplication, Addition, Subtraction. Note
that the precedence order of Division and Multiplication is the same. Likewise, the order of Addition and Subtraction is also the
same.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Core Data Types”.
1. Which of these in not a core data type?
a) Lists
b) Dictionary
c) Tuples
d) Class
Answer: d
Explanation: Class is a user defined data type.
2. Given a function that does not return any value, What value is thrown by default when executed in shell.
a) int
b) bool
c) void
d) None
Answer: d
Explanation: Python shell throws a NoneType object back.
3. What will be the output of the following Python code?
1. >>>str="hello"
2. >>>str[:2]
3. >>>
a) he
b) lo
c) olleh
d) hello
Answer: a
Explanation: We are printing only the 1st two bytes of string and hence the answer is “he”.
4. Which of the following will run without errors?
a) round(45.8)
b) round(6352.898,2,5)
c) round()
d) round(7463.123,2,1)
Answer: a
Explanation: Execute help(round) in the shell to get details of the parameters that are passed into the round function.
5. What is the return type of function id?
a) int
b) float
c) bool
d) dict
Answer: a
Explanation: Execute help(id) to find out details in python shell.id returns a integer value that is unique.
6. In python we do not specify types, it is directly interpreted by the compiler, so consider the following operation to be
performed.
1. >>>x = 13 ? 2
objective is to make sure x has a integer value, select all that apply (python 3.xx)
a) x = 13 // 2
b) x = int(13 / 2)
c) x = 13 % 2
d) All of the mentioned
Answer: d
Explanation: // is integer operation in python 3.0 and int(..) is a type cast operator.
7. What error occurs when you execute the following Python code snippet?
apple = mango
a) SyntaxError
b) NameError
c) ValueError
d) TypeError
Answer: b
Explanation: Mango is not defined hence name error.
8. What will be the output of the following Python code snippet?
1. def example(a):
2. a = a + '2'
3. a = a*2
4. return a
5. >>>example("hello")
a) indentation Error
b) cannot perform mathematical operation on strings
c) hello2
d) hello2hello2
Answer: a
Explanation: Python codes have to be indented properly.
9. What data type is the object below?
L = [1, 23, 'hello', 1]
a) list
b) dictionary
c) array
d) tuple
Answer: a
Explanation: List data type can store any values within it.
10. In order to store values in terms of key and value we use what core data type.
a) list
b) tuple
c) class
d) dictionary
Answer: d
Explanation: Dictionary stores values in terms of keys and values.
11. Which of the following results in a SyntaxError?
a) ‘”Once upon a time…”, she said.’
b) “He said, ‘Yes!'”
c) ‘3\’
d) ”’That’s okay”’
Answer: c
Explanation: Carefully look at the colons.
12. The following is displayed by a print function call. Select all of the function calls that result in this output.
1. tom
2. dick
3. harry
a)
print('''tom
\ndick
\nharry''')
b) print(”’tomdickharry”’)
c) print(‘tom\ndick\nharry’)
d)
print('tom
dick
harry')
Answer: c
Explanation: The \n adds a new line.

13. What is the average value of the following Python code snippet?
1. >>>grade1 = 80
2. >>>grade2 = 90
3. >>>average = (grade1 + grade2) / 2
a) 85.0
b) 85.1
c) 95.0
d) 95.1
Answer: a
Explanation: Cause a decimal value of 0 to appear as output.
14. Select all options that print.
hello-how-are-you
a) print(‘hello’, ‘how’, ‘are’, ‘you’)
b) print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4)
c) print(‘hello-‘ + ‘how-are-you’)
d) print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ + ‘you’)
Answer: c
Explanation: Execute in the shell.
15. What is the return value of trunc()?
a) int
b) bool
c) float
d) None
Answer: a
Explanation: Execute help(math.trunc) to get details.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Dictionaries”.
1. Which of the following statements create a dictionary?
a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) All of the mentioned
Answer: d
Explanation: Dictionaries are created by specifying keys and values.
2. What will be the output of the following Python code snippet?
1. d = {"john":40, "peter":45}
a) “john”, 40, 45, and “peter”
b) “john” and “peter”
c) 40 and 45
d) d = (40:”john”, 45:”peter”)
Answer: b
Explanation: Dictionaries appear in the form of keys and values.
3. What will be the output of the following Python code snippet?
1. d = {"john":40, "peter":45}
2. "john" in d
a) True
b) False
c) None
d) Error
Answer: a
Explanation: In can be used to check if the key is int dictionary.
4. What will be the output of the following Python code snippet?
1. d1 = {"john":40, "peter":45}
2. d2 = {"john":466, "peter":45}
3. d1 == d2
a) True
b) False
c) None
d) Error
Answer: b
Explanation: If d2 was initialized as d2 = d1 the answer would be true.
5. What will be the output of the following Python code snippet?
1. d1 = {"john":40, "peter":45}
2. d2 = {"john":466, "peter":45}
3. d1 > d2
a) True
b) False
c) Error
d) None
Answer: c
Explanation: Arithmetic > operator cannot be used with dictionaries.
6. What will be the output of the following Python code snippet?
1. d = {"john":40, "peter":45}
2. d["john"]
a) 40
b) 45
c) “john”
d) “peter”
Answer: a
Explanation: Execute in the shell to verify.
7. Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command do we use?
a) d.delete(“john”:40)
b) d.delete(“john”)
c) del d[“john”]
d) del d(“john”:40)
Answer: c
Explanation: Execute in the shell to verify.
8. Suppose d = {“john”:40, “peter”:45}. To obtain the number of entries in dictionary which command do we use?
a) d.size()
b) len(d)
c) size(d)
d) d.len()
Answer: b
Explanation: Execute in the shell to verify.
9. What will be the output of the following Python code snippet?
1. d = {"john":40, "peter":45}
2. print(list(d.keys()))
a) [“john”, “peter”]
b) [“john”:40, “peter”:45]
c) (“john”, “peter”)
d) (“john”:40, “peter”:45)
Answer: a
Explanation: The output of the code shown above is a list containing only keys of the dictionary d, in the form of a list.
10. Suppose d = {“john”:40, “peter”:45}, what happens when we try to retrieve a value using the expression d[“susan”]?
a) Since “susan” is not a value in the set, Python raises a KeyError exception
b) It is executed fine and no exception is raised, and it returns None
c) Since “susan” is not a key in the set, Python raises a KeyError exception
d) Since “susan” is not a key in the set, Python raises a syntax error
Answer: c
Explanation: Execute in the shell to verify.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “files”.
1. To open a file c:\scores.txt for reading, we use _____________
a) infile = open(“c:\scores.txt”, “r”)
b) infile = open(“c:\\scores.txt”, “r”)
c) infile = open(file = “c:\scores.txt”, “r”)
d) infile = open(file = “c:\\scores.txt”, “r”)
Answer: b
Explanation: Execute help(open) to get more details.
2. To open a file c:\scores.txt for writing, we use ____________
a) outfile = open(“c:\scores.txt”, “w”)
b) outfile = open(“c:\\scores.txt”, “w”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\\scores.txt”, “w”)
Answer: b
Explanation: w is used to indicate that file is to be written to.
3. To open a file c:\scores.txt for appending data, we use ____________
a) outfile = open(“c:\\scores.txt”, “a”)
b) outfile = open(“c:\\scores.txt”, “rw”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\\scores.txt”, “w”)
Answer: a
Explanation: a is used to indicate that data is to be appended.
4. Which of the following statements are true?
a) When you open a file for reading, if the file does not exist, an error occurs
b) When you open a file for writing, if the file does not exist, a new file is created
c) When you open a file for writing, if the file exists, the existing file is overwritten with the new file
d) All of the mentioned
Answer: d
Explanation: The program will throw an error.
5. To read two characters from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
Answer: a
Explanation: Execute in the shell to verify.
6. To read the entire remaining contents of the file as a string from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
Answer: b
Explanation: read function is used to read all the lines in a file.
7. What will be the output of the following Python code?
1. f = None
2. for i in range (5):
3. with open("data.txt", "w") as f:
4. if i > 2:
5. break
6. print(f.closed)
a) True
b) False
c) None
d) Error
Answer: a
Explanation: The WITH statement when used with open file guarantees that the file object is closed when the with block exits.
8. To read the next line of the file from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
Answer: c
Explanation: Execute in the shell to verify.
9. To read the remaining lines of the file from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
Answer: d
Explanation: Execute in the shell to verify.
10. The readlines() method returns ____________
a) str
b) a list of lines
c) a list of single characters
d) a list of integers
Answer: b
Explanation: Every line is stored in a list and returned.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Function – 1”.
1. Which of the following is the use of function in python?
a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity for your application
c) you can’t also create your own functions
d) All of the mentioned
Answer: a
Explanation: Functions are reusable pieces of programs. They allow you to give a name to a block of statements, allowing you to
run that block using the specified name anywhere in your program and any number of times.
2. Which keyword is used for function?
a) Fun
b) Define
c) Def
d) Function
Answer: c
Explanation: None.
3. What will be the output of the following Python code?
1. def sayHello():
2. print('Hello World!')
3. sayHello()
4. sayHello()
a)
Hello World!
Hello World!
b)
'Hello World!'
'Hello World!'
c)
Hello
Hello
d) None of the mentioned
Answer: a
Explanation: Functions are defined using the def keyword. After this keyword comes an identifier name for the function, followed
by a pair of parentheses which may enclose some names of variables, and by the final colon that ends the line. Next follows the
block of statements that are part of this function.
1. def sayHello():
2. print('Hello World!') # block belonging to the function
3. # End of function #
4. sayHello() # call the function
5. sayHello() # call the function again
4. What will be the output of the following Python code?
1. def printMax(a, b):
2. if a > b:
3. print(a, 'is maximum')
4. elif a == b:
5. print(a, 'is equal to', b)
6. else:
7. print(b, 'is maximum')
8. printMax(3, 4)
a) 3
b) 4
c) 4 is maximum
d) None of the mentioned
Answer: c
Explanation: Here, we define a function called printMax that uses two parameters called a and b. We find out the greater number
using a simple if..else statement and then print the bigger number.
5. What will be the output of the following Python code?
1. x = 50
2. def func(x):
3. print('x is', x)
4. x=2
5. print('Changed local x to', x)
6. func(x)
7. print('x is now', x)
a)
x is 50
Changed local x to 2
x is now 50
b)
x is 50
Changed local x to 2
x is now 2
c)
x is 50
Changed local x to 2
x is now 100
d) None of the mentioned
Answer: a
Explanation: The first time that we print the value of the name x with the first line in the function’s body, Python uses the value of
the parameter declared in the main block, above the function definition.
Next, we assign the value 2 to x. The name x is local to our function. So, when we change the value of x in the function, the x
defined in the main block remains unaffected.
With the last print function call, we display the value of x as defined in the main block, thereby confirming that it is actually
unaffected by the local assignment within the previously called function.
6. What will be the output of the following Python code?
1. x = 50
2. def func():
3. global x
4. print('x is', x)
5. x=2
6. print('Changed global x to', x)
7. func()
8. print('Value of x is', x)
a)
x is 50
Changed global x to 2
Value of x is 50
b)
x is 50
Changed global x to 2
Value of x is 2
c)
x is 50
Changed global x to 50
Value of x is 50
d) None of the mentioned
Answer: b
Explanation: The global statement is used to declare that x is a global variable – hence, when we assign a value to x inside the
function, that change is reflected when we use the value of x in the main block.
7. What will be the output of the following Python code?
1. def say(message, times = 1):
2. print(message * times)
3. say('Hello')
4. say('World', 5)
a)
Hello
WorldWorldWorldWorldWorld
b)
Hello
World 5
c)
Hello
World,World,World,World,World
d)
Hello
HelloHelloHelloHelloHello
Answer: a
Explanation: For some functions, you may want to make some parameters optional and use default values in case the user does
not want to provide values for them. This is done with the help of default argument values. You can specify default argument
values for parameters by appending to the parameter name in the function definition the assignment operator (=) followed by the
default value.
The function named say is used to print a string as many times as specified. If we don’t supply a value, then by default, the string
is printed just once. We achieve this by specifying a default argument value of 1 to the parameter times.
In the first usage of say, we supply only the string and it prints the string once. In the second usage of say, we supply both the
string and an argument 5 stating that we want to say the string message 5 times.

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


1. def func(a, b=5, c=10):
2. print('a is', a, 'and b is', b, 'and c is', c)
3. func(3, 7)
4. func(25, c = 24)
5. func(c = 50, a = 100)
a)
a is 7 and b is 3 and c is 10
a is 25 and b is 5 and c is 24
a is 5 and b is 100 and c is 50
b)
a is 3 and b is 7 and c is 10
a is 5 and b is 25 and c is 24
a is 50 and b is 100 and c is 5
c)
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
d) None of the mentioned
Answer: c
Explanation: If you have some functions with many parameters and you want to specify only some of them, then you can give
values for such parameters by naming them – this is called keyword arguments – we use the name (keyword) instead of the
position (which we have been using all along) to specify the arguments to the function.
The function named func has one parameter without a default argument value, followed by two parameters with default argument
values.
In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the value 7 and c gets the default value of 10.
In the second usage func(25, c=24), the variable a gets the value of 25 due to the position of the argument. Then, the parameter
c gets the value of 24 due to naming i.e. keyword arguments. The variable b gets the default value of 5.
In the third usage func(c=50, a=100), we use keyword arguments for all specified values. Notice that we are specifying the value
for parameter c before that for a even though a is defined before c in the function definition.
9. What will be the output of the following Python code?
1. def maximum(x, y):
2. if x > y:
3. return x
4. elif x == y:
5. return 'The numbers are equal'
6. else:
7. return y
8. print(maximum(2, 3))
a) 2
b) 3
c) The numbers are equal
d) None of the mentioned
Answer: b
Explanation: The maximum function returns the maximum of the parameters, in this case the numbers supplied to the function. It
uses a simple if..else statement to find the greater value and then returns that value.
10. Which of the following is a feature of DocString?
a) Provide a convenient way of associating documentation with Python modules, functions, classes, and methods
b) All functions should have a docstring
c) Docstrings can be accessed by the __doc__ attribute on objects
d) All of the mentioned
Answer: d
Explanation: Python has a nifty feature called documentation strings, usually referred to by its shorter name docstrings.
DocStrings are an important tool that you should make use of since it helps to document the program better and makes it easier
to understand.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Lists”.
1. Which of the following commands will create a list?
a) list1 = list()
b) list1 = []
c) list1 = list([1, 2, 3])
d) all of the mentioned
Answer: d
Explanation: Execute in the shell to verify
2. What is the output when we execute list(“hello”)?
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) [‘hello’]
c) [‘llo’]
d) [‘olleh’]
Answer: a
Explanation: Execute in the shell to verify.
3. Suppose listExample is [‘h’,’e’,’l’,’l’,’o’], what is len(listExample)?
a) 5
b) 4
c) None
d) Error
Answer: a
Explanation: Execute in the shell and verify.
4. Suppose list1 is [2445,133,12454,123], what is max(list1)?
a) 2445
b) 133
c) 12454
d) 123
Answer: c
Explanation: Max returns the maximum element in the list.
5. Suppose list1 is [3, 5, 25, 1, 3], what is min(list1)?
a) 3
b) 5
c) 25
d) 1
Answer: d
Explanation: Min returns the minimum element in the list.
6. Suppose list1 is [1, 5, 9], what is sum(list1)?
a) 1
b) 9
c) 15
d) Error
Answer: c
Explanation: Sum returns the sum of all elements in the list.
7. To shuffle the list(say list1) what function do we use?
a) list1.shuffle()
b) shuffle(list1)
c) random.shuffle(list1)
d) random.shuffleList(list1)
Answer: c
Explanation: Execute in the shell to verify.
8. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of the following is correct syntax for slicing operation?
a) print(list1[0])
b) print(list1[:2])
c) print(list1[:-2])
d) all of the mentioned
Answer: d
Explanation: Slicing is allowed in lists just as in the case of strings.
9. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1]?
a) Error
b) None
c) 25
d) 2
Answer: c
Explanation: -1 corresponds to the last index in the list.
10. Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1]?
a) [2, 33, 222, 14]
b) Error
c) 25
d) [25, 14, 222, 33, 2]
Answer: a
Explanation: Execute in the shell to verify.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Strings – 1”.
1. What will be the output of the following Python statement?
1. >>>"a"+"bc"
a) a
b) bc
c) bca
d) abc
Answer: d
Explanation: + operator is concatenation operator.
2. What will be the output of the following Python statement?
1. >>>"abcd"[2:]
a) a
b) ab
c) cd
d) dc
Answer: c
Explanation: Slice operation is performed on string.
3. The output of executing string.ascii_letters can also be achieved by:
a) string.ascii_lowercase_string.digits
b) string.ascii_lowercase+string.ascii_uppercase
c) string.letters
d) string.lowercase_string.uppercase
Answer: b
Explanation: Execute in shell and check.
4. What will be the output of the following Python code?
1. >>> str1 = 'hello'
2. >>> str2 = ','
3. >>> str3 = 'world'
4. >>> str1[-1:]
a) olleh
b) hello
c) h
d) o
Answer: d
Explanation: -1 corresponds to the last index.
5. What arithmetic operators cannot be used with strings?
a) +
b) *
c) –
d) All of the mentioned
Answer: c
Explanation: + is used to concatenate and * is used to multiply strings.
6. What will be the output of the following Python code?
1. >>>print (r"\nhello")
a) a new line and hello
b) \nhello
c) the letter r and then hello
d) error
Answer: b
Explanation: When prefixed with the letter ‘r’ or ‘R’ a string literal becomes a raw string and the escape sequences such as \n
are not converted.
7. What will be the output of the following Python statement?
1. >>>print('new' 'line')
a) Error
b) Output equivalent to print ‘new\nline’
c) newline
d) new line
Answer: c
Explanation: String literal separated by whitespace are allowed. They are concatenated.
8. What will be the output of the following Python statement?
1. >>> print('x\97\x98')
a) Error
b)
97
98
c) x\97
d) \x97\x98
Answer: c
Explanation: \x is an escape sequence that means the following 2 digits are a hexadecimal number encoding a character.
9. What will be the output of the following Python code?
1. >>>str1="helloworld"
2. >>>str1[::-1]
a) dlrowolleh
b) hello
c) world
d) helloworld
Answer: a
Explanation: Execute in shell to verify.
10. What will be the output of the following Python code?
print(0xA + 0xB + 0xC)
a) 0xA0xB0xC
b) Error
c) 0x22
d) 33
Answer: d
Explanation: 0xA and 0xB and 0xC are hexadecimal integer literals representing the decimal values 10, 11 and 12 respectively.
There sum is 33.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Tuples – 1”.
1. Which of the following is a Python tuple?
a) [1, 2, 3]
b) (1, 2, 3)
c) {1, 2, 3}
d) {}
Answer: b
Explanation: Tuples are represented with round brackets.
2. Suppose t = (1, 2, 4, 3), which of the following is incorrect?
a) print(t[3])
b) t[3] = 45
c) print(max(t))
d) print(len(t))
Answer: b
Explanation: Values cannot be modified in the case of tuple, that is, tuple is immutable.
3. What will be the output of the following Python code?
1. >>>t=(1,2,4,3)
2. >>>t[1:3]
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
Answer: c
Explanation: Slicing in tuples takes place just as it does in strings.
4. What will be the output of the following Python code?
1. >>>t=(1,2,4,3)
2. >>>t[1:-1]
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
Answer: c
Explanation: Slicing in tuples takes place just as it does in strings.
5. What will be the output of the following Python code?
1. >>>t = (1, 2, 4, 3, 8, 9)
2. >>>[t[i] for i in range(0, len(t), 2)]
a) [2, 3, 9]
b) [1, 2, 4, 3, 8, 9]
c) [1, 4, 8]
d) (1, 4, 8)
Answer: c
Explanation: Execute in the shell to verify.
6. What will be the output of the following Python code?
1. d = {"john":40, "peter":45}
2. d["john"]
a) 40
b) 45
c) “john”
d) “peter”
Answer: a
Explanation: Execute in the shell to verify.
7. What will be the output of the following Python code?
1. >>>t = (1, 2)
2. >>>2 * t
a) (1, 2, 1, 2)
b) [1, 2, 1, 2]
c) (1, 1, 2, 2)
d) [1, 1, 2, 2]
Answer: a
Explanation: * operator concatenates tuple.
8. What will be the output of the following Python code?
1. >>>t1 = (1, 2, 4, 3)
2. >>>t2 = (1, 2, 3, 4)
3. >>>t1 < t2
a) True
b) False
c) Error
d) None
Answer: b
Explanation: Elements are compared one by one in this case.
9. What will be the output of the following Python code?
1. >>>my_tuple = (1, 2, 3, 4)
2. >>>my_tuple.append( (5, 6, 7) )
3. >>>print len(my_tuple)
a) 1
b) 2
c) 5
d) Error
Answer: d
Explanation: Tuples are immutable and don’t have an append method. An exception is thrown in this case.
10. What will be the output of the following Python code?
1. numberGames = {}
2. numberGames[(1,2,4)] = 8
3. numberGames[(4,2,1)] = 10
4. numberGames[(1,2)] = 12
5. sum = 0
6. for k in numberGames:
7. sum += numberGames[k]
8. print len(numberGames) + sum
a) 30
b) 24
c) 33
d) 12
Answer: c
Explanation: Tuples can be used for keys into dictionary. The tuples can have mixed length and the order of the items in the tuple
is considered when comparing the equality of the keys.
This set of Python MCQs focuses on “Strings”.
1. What will be the output of the following Python code?
print('{0:.2}'.format(1/3))
a) 0.333333
b) 0.33
c) 0.333333:.2
d) Error
Answer: b
Explanation: .2 specifies the precision.
2. What will be the output of the following Python code?
print('{0:.2%}'.format(1/3))
a) 0.33
b) 0.33%
c) 33.33%
d) 33%
Answer: c
Explanation: The symbol % is used to represent the result of an expression as a percentage.
3. What will be the output of the following Python code?
print('ab12'.isalnum())
a) True
b) False
c) None
d) Error
Answer: a
Explanation: The string has only letters and digits.
4. What will be the output of the following Python code?
print('ab,12'.isalnum())
a) True
b) False
c) None
d) Error
Answer: b
Explanation: The character , is not a letter or a digit.
5. What will be the output of the following Python code?
print('ab'.isalpha())
a) True
b) False
c) None
d) Error
Answer: a
Explanation: The string has only letters.
6. What will be the output of the following Python code?
print('a B'.isalpha())
a) True
b) False
c) None
d) Error
Answer: b
Explanation: Space is not a letter.
7. What will be the output of the following Python code snippet?
print('0xa'.isdigit())
a) True
b) False
c) None
d) Error
Answer: b
Explanation: Hexadecimal digits aren’t considered as digits (a-f).
8. What will be the output of the following Python code snippet?
print(''.isdigit())
a) True
b) False
c) None
d) Error
Answer: b
Explanation: If there are no characters then False is returned.
9.What will be the output of the following Python code snippet?
print('my_string'.isidentifier())
a) True
b) False
c) None
d) Error
Answer: a
Explanation: It is a valid identifier.
10. What will be the output of the following Python code snippet?
print('__foo__'.isidentifier())
a) True
b) False
c) None
d) Error
Answer: a
Explanation: It is a valid identifier.
To practice all mcqs on Python, .
This set of Python Multiple Choice Questions and Answers focuses on “Strings”.
1. What will be the output of the following Python code?
print("Hello {name1} and {name2}".format(name1='foo', name2='bin'))
a) Hello foo and bin
b) Hello {name1} and {name2}
c) Error
d) Hello and
Answer: a
Explanation: The arguments are accessed by their names.
2. What will be the output of the following Python code?
print("Hello {0!r} and {0!s}".format('foo', 'bin'))
a) Hello foo and foo
b) Hello ‘foo’ and foo
c) Hello foo and ‘bin’
d) Error
Answer: b
Explanation: !r causes the characters ‘ or ” to be printed as well.
3. What will be the output of the following Python code?
print("Hello {0} and {1}".format(('foo', 'bin')))
a) Hello foo and bin
b) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)
c) Error
d) None of the mentioned
Answer: c
Explanation: IndexError, the tuple index is out of range.
4. What will be the output of the following Python code?
print("Hello {0[0]} and {0[1]}".format(('foo', 'bin')))
a) Hello foo and bin
b) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)
c) Error
d) None of the mentioned
Answer: a
Explanation: The elements of the tuple are accessed by their indices.
5. What will be the output of the following Python code snippet?
print('The sum of {0} and {1} is {2}'.format(2, 10, 12))
a) The sum of 2 and 10 is 12
b) Error
c) The sum of 0 and 1 is 2
d) None of the mentioned
Answer: a
Explanation: The arguments passed to the function format can be integers also.
6. What will be the output of the following Python code snippet?
print('The sum of {0:b} and {1:x} is {2:o}'.format(2, 10, 12))
a) The sum of 2 and 10 is 12
b) The sum of 10 and a is 14
c) The sum of 10 and a is c
d) Error
Answer: b
Explanation: 2 is converted to binary, 10 to hexadecimal and 12 to octal.
7. What will be the output of the following Python code snippet?
print('{:,}'.format(1112223334))
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
d) Error
Answer: a
Explanation: A comma is added after every third digit from the right.
8. What will be the output of the following Python code snippet?
print('{:,}'.format('1112223334'))
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
d) Error
Answer: d
Explanation: An integer is expected.
9. What will be the output of the following Python code snippet?
print('{:$}'.format(1112223334))
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
d) Error
Answer: d
Explanation: $ is an invalid format code.
10. What will be the output of the following Python code snippet?
print('{:#}'.format(1112223334))
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
d) Error
Answer: c
Explanation: The number is printed as it is.
To practice all multiple choice questions on Python, .
This set of Python Objective Questions & Answers focuses on “Math – 1”.
1. What is returned by math.ceil(3.4)?
a) 3
b) 4
c) 4.0
d) 3.0
Answer: b
Explanation: The ceil function returns the smallest integer that is bigger than or equal to the number itself.
2. What is the value returned by math.floor(3.4)?
a) 3
b) 4
c) 4.0
d) 3.0
Answer: a
Explanation: The floor function returns the biggest number that is smaller than or equal to the number itself.
3. What will be the output of print(math.copysign(3, -1))?
a) 1
b) 1.0
c) -3
d) -3.0
Answer: d
Explanation: The copysign function returns a float whose absolute value is that of the first argument and the sign is that of the
second argument.
4. What is displayed on executing print(math.fabs(-3.4))?
a) -3.4
b) 3.4
c) 3
d) -3
Answer: b
Explanation: A negative floating point number is returned as a positive floating point number.
5. Is the output of the function abs() the same as that of the function math.fabs()?
a) sometimes
b) always
c) never
d) none of the mentioned
Answer: a
Explanation: math.fabs() always returns a float and does not work with complex numbers whereas the return type of abs() is
determined by the type of value that is passed to it.
6. What is the value returned by math.fact(6)?
a) 720
b) 6
c) [1, 2, 3, 6]
d) error
Answer: d
Explanation: NameError, fact() is not defined.
7. What is the value of x if x = math.factorial(0)?
a) 0
b) 1
c) error
d) none of the mentioned
Answer: b
Explanation: Factorial of 0 is 1.
8. What is math.factorial(4.0)?
a) 24
b) 1
c) error
d) none of the mentioned
Answer: a
Explanation: The factorial of 4 is returned.
9. What will be the output of print(math.factorial(4.5))?
a) 24
b) 120
c) error
d) 24.0
Answer: c
Explanation: Factorial is only defined for non-negative integers.
10. What is math.floor(0o10)?
a) 8
b) 10
c) 0
d) 9
Answer: a
Explanation: 0o10 is 8 and floor(8) is 8.
To practice all objective questions on Python, .
This set of Online Python Test focuses on “Strings”.
1. What will be the output of the following Python code?
print('#World'.istitle())
a) True
b) False
c) None
d) error
Answer: a
Explanation: It is in the form of a title.
2. What will be the output of the following Python code?
print(''.lower())
a) n
b)
c) rn
d) r
Answer: b
Explanation: Uppercase letters are converted to lowercase. The other characters are left unchanged.
3. What will be the output of the following Python code?
print('''
\tfoo'''.lstrip())
a) \tfoo
b) foo
c)   foo
d) none of the mentioned
Answer: b
Explanation: All leading whitespace is removed.
4. What will be the output of the following Python code?
print('xyyzxxyxyy'.lstrip('xyy'))
a) error
b) zxxyxyy
c) z
d) zxxy
Answer: b
Explanation: The leading characters containing xyy are removed.
5. What will be the output of the following Python code?
print('xyxxyyzxxy'.lstrip('xyy'))
a) zxxy
b) xyxxyyzxxy
c) xyxzxxy
d) none of the mentioned
Answer: a
Explanation: All combinations of the characters passed as an argument are removed from the left hand side.
6. What will be the output of the following Python code?
print('cba'.maketrans('abc', '123'))
a) {97: 49, 98: 50, 99: 51}
b) {65: 49, 66: 50, 67: 51}
c) 321
d) 123
Answer: a
Explanation: A translation table is returned by maketrans.
7. What will be the output of the following Python code?
print('a'.maketrans('ABC', '123'))
a) {97: 49, 98: 50, 99: 51}
b) {65: 49, 66: 50, 67: 51}
c) {97: 49}
d) 1
Answer: b
Explanation: maketrans() is a static method so it’s behaviour does not depend on the object from which it is being called.
8. What will be the output of the following Python code?
print('abcdef'.partition('cd'))
a) (‘ab’, ‘ef’)
b) (‘abef’)
c) (‘ab’, ‘cd’, ‘ef’)
d) 2
Answer: c
Explanation: The string is split into three parts by partition.
9. What will be the output of the following Python code?
print('abcdefcdgh'.partition('cd'))
a) (‘ab’, ‘cd’, ‘ef’, ‘cd’, ‘gh’)
b) (‘ab’, ‘cd’, ‘efcdgh’)
c) (‘abcdef’, ‘cd’, ‘gh’)
d) error
Answer: b
Explanation: The string is partitioned at the point where the separator first appears.
10. What will be the output of the following Python code?
print('abcd'.partition('cd'))
a) (‘ab’, ‘cd’, ”)
b) (‘ab’, ‘cd’)
c) error
d) none of the mentioned
Answer: a
Explanation: The last item is a null string.
To practice all test questions online on Python, .
This set of Python Problems focuses on “Strings”.
1. What will be the output of the following Python code snippet?
print('cd'.partition('cd'))
a) (‘cd’)
b) (”)
c) (‘cd’, ”, ”)
d) (”, ‘cd’, ”)
Answer: d
Explanation: The entire string has been passed as the separator hence the first and the last item of the tuple returned are null
strings.
2. What will be the output of the following Python code snippet?
print('abef'.partition('cd'))
a) (‘abef’)
b) (‘abef’, ‘cd’, ”)
c) (‘abef’, ”, ”)
d) error
Answer: c
Explanation: The separator is not present in the string hence the second and the third elements of the tuple are null strings.
3. What will be the output of the following Python code snippet?
print('abcdef12'.replace('cd', '12'))
a) ab12ef12
b) abcdef12
c) ab12efcd
d) none of the mentioned
Answer: a
Explanation: All occurrences of the first substring are replaced by the second substring.
4. What will be the output of the following Python code snippet?
print('abef'.replace('cd', '12'))
a) abef
b) 12
c) error
d) none of the mentioned
Answer: a
Explanation: The first substring is not present in the given string and hence nothing is replaced.
5. What will be the output of the following Python code snippet?
print('abcefd'.replace('cd', '12'))
a) ab1ef2
b) abcefd
c) ab1efd
d) ab12ed2
Answer: b
Explanation: The first substring is not present in the given string and hence nothing is replaced.
6. What will be the output of the following Python code snippet?
print('xyyxyyxyxyxxy'.replace('xy', '12', 0))
a) xyyxyyxyxyxxy
b) 12y12y1212x12
c) 12yxyyxyxyxxy
d) xyyxyyxyxyx12
Answer: a
Explanation: The first 0 occurrences of the given substring are replaced.
7. What will be the output of the following Python code snippet?
print('xyyxyyxyxyxxy'.replace('xy', '12', 100))
a) xyyxyyxyxyxxy
b) 12y12y1212x12
c) none of the mentioned
d) error
Answer: b
Explanation: The first 100 occurrences of the given substring are replaced.
8. What will be the output of the following Python code snippet?
print('abcdefcdghcd'.split('cd'))
a) [‘ab’, ‘ef’, ‘gh’]
b) [‘ab’, ‘ef’, ‘gh’, ”]
c) (‘ab’, ‘ef’, ‘gh’)
d) (‘ab’, ‘ef’, ‘gh’, ”)
Answer: b
Explanation: The given string is split and a list of substrings is returned.
9. What will be the output of the following Python code snippet?
print('abcdefcdghcd'.split('cd', 0))
a) [‘abcdefcdghcd’]
b) ‘abcdefcdghcd’
c) error
d) none of the mentioned
Answer: a
Explanation: The given string is split at 0 occurances of the specified substring.
10. What will be the output of the following Python code snippet?
print('abcdefcdghcd'.split('cd', -1))
a) [‘ab’, ‘ef’, ‘gh’]
b) [‘ab’, ‘ef’, ‘gh’, ”]
c) (‘ab’, ‘ef’, ‘gh’)
d) (‘ab’, ‘ef’, ‘gh’, ”)
Answer: b
Explanation: Calling the function with a negative value for maxsplit is the same as calling it without any maxsplit specified. The
string will be split into as many substring s as possible.
To practice all problems on Python, .
This set of Python Programming Interview Questions & Answers focuses on “Lists”.
1. What will be the output of the following Python code?
1. def f(i, values = []):
2. values.append(i)
3. return values
4. f(1)
5. f(2)
6. v = f(3)
7. print(v)
a) [1] [2] [3]
b) [1] [1, 2] [1, 2, 3]
c) [1, 2, 3]
d) 1 2 3
Answer: c
Explanation: Execute in the shell to verify
2. What will be the output of the following Python code?
1. names1 = ['Amir', 'Bala', 'Chales']
2. if 'amir' in names1:
3. print(1)
4. else:
5. print(2)
a) None
b) 1
c) 2
d) Error
Answer: c
Explanation: Execute in the shell to verify.
3. What will be the output of the following Python code?
1. names1 = ['Amir', 'Bala', 'Charlie']
2. names2 = [name.lower() for name in names1]
3. print(names2[2][0])
a) None
b) a
c) b
d) c
Answer: d
Explanation: List Comprehension are a shorthand for creating new lists.
4. What will be the output of the following Python code?
1. numbers = [1, 2, 3, 4]
2. numbers.append([5,6,7,8])
3. print(len(numbers))
a) 4
b) 5
c) 8
d) 12
Answer: b
Explanation: A list is passed in append so the length is 5.
5. To which of the following the “in” operator can be used to check if an item is in it?
a) Lists
b) Dictionary
c) Set
d) All of the mentioned
Answer: d
Explanation: In can be used in all data structures.
6. What will be the output of the following Python code?
1. list1 = [1, 2, 3, 4]
2. list2 = [5, 6, 7, 8]
3. print(len(list1 + list2))
a) 2
b) 4
c) 5
d) 8
Answer: d
Explanation: + appends all the elements individually into a new list.
7. What will be the output of the following Python code?
1. def addItem(listParam):
2. listParam += [1]
3. mylist = [1, 2, 3, 4]
4. addItem(mylist)
5. print(len(mylist))
a) 1
b) 4
c) 5
d) 8
Answer: c
Explanation: + will append the element to the list.
8. What will be the output of the following Python code?
1. def increment_items(L, increment):
2. i=0
3. while i < len(L):
4. L[i] = L[i] + increment
5. i=i+1
6. values = [1, 2, 3]
7. print(increment_items(values, 2))
8. print(values)
a)
None
[3, 4, 5]
b)
None
[1, 2, 3]
c)
[3, 4, 5]
[1, 2, 3]
d)
[3, 4, 5]
None
Answer: a
Explanation: Execute in the shell to verify.

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


1. def example(L):
2. ''' (list) -> list
3. '''
4. i=0
5. result = []
6. while i < len(L):
7. result.append(L[i])
8. i=i+3
9. return result
a) Return a list containing every third item from L starting at index 0
b) Return an empty list
c) Return a list containing every third index from L starting at index 0
d) Return a list containing the items from L starting from index 0, omitting every third item
Answer: a
Explanation: Run the code to get a better understanding with many arguments.
10. What will be the output of the following Python code?
1. veggies = ['carrot', 'broccoli', 'potato', 'asparagus']
2. veggies.insert(veggies.index('broccoli'), 'celery')
3. print(veggies)
a) [‘carrot’, ‘celery’, ‘broccoli’, ‘potato’, ‘asparagus’] Correct 1.00
b) [‘carrot’, ‘celery’, ‘potato’, ‘asparagus’]

c) [‘carrot’, ‘broccoli’, ‘celery’, ‘potato’, ‘asparagus’]

d) [‘celery’, ‘carrot’, ‘broccoli’, ‘potato’, ‘asparagus’]


Answer: a
Explanation: Execute in the shell to verify.
To practice all programming interview questions on Python, .
This set of Python Programming Questions & Answers focuses on “Lists”.
1. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.reverse()?
a) [3, 4, 5, 20, 5, 25, 1, 3]
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [25, 20, 5, 5, 4, 3, 3, 1]
d) [3, 1, 25, 5, 20, 5, 4, 3]
Answer: d
Explanation: Execute in the shell to verify.
2. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.extend([34, 5])?
a) [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
b) [1, 3, 3, 4, 5, 5, 20, 25, 34, 5]
c) [25, 20, 5, 5, 4, 3, 3, 1, 34, 5]
d) [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]
Answer: a
Explanation: Execute in the shell to verify.
3. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.pop(1)?
a) [3, 4, 5, 20, 5, 25, 1, 3]
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [3, 5, 20, 5, 25, 1, 3]
d) [1, 3, 4, 5, 20, 5, 25]
Answer: c
Explanation: pop() removes the element at the position specified in the parameter.
4. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.pop()?
a) [3, 4, 5, 20, 5, 25, 1]
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [3, 5, 20, 5, 25, 1, 3]
d) [1, 3, 4, 5, 20, 5, 25]
Answer: a
Explanation: pop() by default will remove the last element.
5. What will be the output of the following Python code?
1. >>>"Welcome to Python".split()
a) [“Welcome”, “to”, “Python”]
b) (“Welcome”, “to”, “Python”)
c) {“Welcome”, “to”, “Python”}
d) “Welcome”, “to”, “Python”
Answer: a
Explanation: split() function returns the elements in a list.
6. What will be the output of the following Python code?
1. >>>list("a#b#c#d".split('#'))
a) [‘a’, ‘b’, ‘c’, ‘d’]
b) [‘a b c d’]
c) [‘a#b#c#d’]
d) [‘abcd’]
Answer: a
Explanation: Execute in the shell to verify.
7. What will be the output of the following Python code?
1. myList = [1, 5, 5, 5, 5, 1]
2. max = myList[0]
3. indexOfMax = 0
4. for i in range(1, len(myList)):
5. if myList[i] > max:
6. max = myList[i]
7. indexOfMax = i
8. >>>print(indexOfMax)
a) 1
b) 2
c) 3
d) 4
Answer: a
Explanation: First time the highest number is encountered is at index 1.
8. What will be the output of the following Python code?
1. myList = [1, 2, 3, 4, 5, 6]
2. for i in range(1, 6):
3. myList[i - 1] = myList[i]
4. for i in range(0, 6):
5. print(myList[i], end = " ")
a) 2 3 4 5 6 1
b) 6 1 2 3 4 5
c) 2 3 4 5 6 6
d) 1 1 2 3 4 5
Answer: c
Explanation: Execute in the shell to verify.
9. What will be the output of the following Python code?
1. >>>list1 = [1, 3]
2. >>>list2 = list1
3. >>>list1[0] = 4
4. >>>print(list2)
a) [1, 3]
b) [4, 3]
c) [1, 4]
d) [1, 3, 4]
Answer: b
Explanation: Lists should be copied by executing [:] operation.
10. What will be the output of the following Python code?
1. def f(values):
2. values[0] = 44
3. v = [1, 2, 3]
4. f(v)
5. print(v)
a) [1, 44]
b) [1, 2, 3, 44]
c) [44, 2, 3]
d) [1, 2, 3]
Answer: c
Explanation: Execute in the shell to verify.
To practice all programming questions on Python, .
This set of Python Puzzles focuses on “Argument Parsing”.
1. What is the type of each element in sys.argv?
a) set
b) list
c) tuple
d) string
Answer: d
Explanation: It is a list of strings.
2. What is the length of sys.argv?
a) number of arguments
b) number of arguments + 1
c) number of arguments – 1
d) none of the mentioned
Answer: b
Explanation: The first argument is the name of the program itself. Therefore the length of sys.argv is one more than the number
arguments.
3. What will be the output of the following Python code?
def foo(k):
k[0] = 1
q = [0]
foo(q)
print(q)
a) [0]
b) [1]
c) [1, 0]
d) [0, 1]
Answer: b
Explanation: Lists are passed by reference.
4. How are keyword arguments specified in the function heading?
a) one-star followed by a valid identifier
b) one underscore followed by a valid identifier
c) two stars followed by a valid identifier
d) two underscores followed by a valid identifier
Answer: c
Explanation: Refer documentation.
5. How many keyword arguments can be passed to a function in a single function call?
a) zero
b) one
c) zero or more
d) one or more
Answer: c
Explanation: Zero keyword arguments may be passed if all the arguments have default values.
6. What will be the output of the following Python code?
def foo(fname, val):
print(fname(val))
foo(max, [1, 2, 3])
foo(min, [1, 2, 3])
a) 3 1
b) 1 3
c) error
d) none of the mentioned
Answer: a
Explanation: It is possible to pass function names as arguments to other functions.
7. What will be the output of the following Python code?
def foo():
return total + 1
total = 0
print(foo())
a) 0
b) 1
c) error
d) none of the mentioned
Answer: b
Explanation: It is possible to read the value of a global variable directly.
8. What will be the output of the following Python code?
def foo():
total += 1
return total
total = 0
print(foo())
a) 0
b) 1
c) error
d) none of the mentioned
Answer: c
Explanation: It is not possible to change the value of a global variable without explicitly specifying it.
9. What will be the output of the following Python code?
def foo(x):
x = ['def', 'abc']
return id(x)
q = ['abc', 'def']
print(id(q) == foo(q))
a) True
b) False
c) None
d) Error
Answer: b
Explanation: A new object is created in the function.
10. What will be the output of the following Python code?
def foo(i, x=[]):
x.append(i)
return x
for i in range(3):
print(foo(i))
a) [0] [1] [2]
b) [0] [0, 1] [0, 1, 2]
c) [1] [2] [3]
d) [1] [1, 2] [1, 2, 3]
Answer: b
Explanation: When a list is a default value, the same list will be reused.
To practice all Puzzles on Python, .
This set of Python Question Bank focuses on “Strings”.
1. What will be the output of the following Python code snippet?
print('abcdefcdghcd'.split('cd', 2))
a) [‘ab’, ‘ef’, ‘ghcd’]
b) [‘ab’, ‘efcdghcd’]
c) [‘abcdef’, ‘ghcd’]
d) none of the mentioned
Answer: a
Explanation: The string is split into a maximum of maxsplit+1 substrings.
2. What will be the output of the following Python code snippet?
print('ab\ncd\nef'.splitlines())
a) [‘ab’, ‘cd’, ‘ef’]
b) [‘ab\n’, ‘cd\n’, ‘ef\n’]
c) [‘ab\n’, ‘cd\n’, ‘ef’]
d) [‘ab’, ‘cd’, ‘ef\n’]
Answer: a
Explanation: It is similar to calling split(‘\n’).
3. What will be the output of the following Python code snippet?
print('Ab!2'.swapcase())
a)
b) ab12
c) aB!2
d)
Answer: c
Explanation: Lowercase letters are converted to uppercase and vice-versa.
4. What will be the output of the following Python code snippet?
print('ab cd ef'.title())
a) Ab cd ef
b) Ab cd eF
c) Ab Cd Ef
d) None of the mentioned
Answer: c
Explanation: The first letter of every word is capitalized.
5. What will be the output of the following Python code snippet?
print('ab cd-ef'.title())
a) Ab cd-ef
b) Ab Cd-ef
c) Ab Cd-Ef
d) None of the mentioned
Answer: c
Explanation: The first letter of every word is capitalized. Special symbols terminate a word.
6. What will be the output of the following Python code snippet?
print('abcd'.translate('a'.maketrans('abc', 'bcd')))
a) bcde
b) abcd
c) error
d) bcdd
Answer: d
Explanation: The output is bcdd since no translation is provided for d.
7. What will be the output of the following Python code snippet?
print('abcd'.translate({97: 98, 98: 99, 99: 100}))
a) bcde
b) abcd
c) error
d) none of the mentioned
Answer: d
Explanation: The output is bcdd since no translation is provided for d.
8. What will be the output of the following Python code snippet?
print('abcd'.translate({'a': '1', 'b': '2', 'c': '3', 'd': '4'}))
a) abcd
b) 1234
c) error
d) none of the mentioned
Answer: a
Explanation: The function translate expects a dictionary of integers. Use maketrans() instead of doing the above.
9. What will be the output of the following Python code snippet?
print('ab'.zfill(5))
a) 000ab
b) 00ab0
c) 0ab00
d) ab000
Answer: a
Explanation: The string is padded with zeros on the left hand side. It is useful for formatting numbers.
10. What will be the output of the following Python code snippet?
print('+99'.zfill(5))
a) 00+99
b) 00099
c) +0099
d) +++99
Answer: c
Explanation: zeros are filled in between the first sign and the rest of the string.
To practice entire question bank on Python, .
This set of Python Question Paper focuses on “Lists”.
1. What will be the output of the following Python code?
1. >>>m = [[x, x + 1, x + 2] for x in range(0, 3)]
a) [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b) [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
c) [1, 2, 3, 4, 5, 6, 7, 8, 9]
d) [0, 1, 2, 1, 2, 3, 2, 3, 4]
Answer: b
Explanation: Execute in the shell to verify.
2. How many elements are in m?
1. m = [[x, y] for x in range(0, 4) for y in range(0, 4)]
a) 8
b) 12
c) 16
d) 32
Answer: c
Explanation: Execute in the shell to verify.
3. What will be the output of the following Python code?
1. values = [[3, 4, 5, 1], [33, 6, 1, 2]]
2. v = values[0][0]
3. for row in range(0, len(values)):
4. for column in range(0, len(values[row])):
5. if v < values[row][column]:
6. v = values[row][column]
7. print(v)
a) 3
b) 5
c) 6
d) 33
Answer: d
Explanation: Execute in the shell to verify.
4. What will be the output of the following Python code?
1. values = [[3, 4, 5, 1], [33, 6, 1, 2]]
2. v = values[0][0]
3. for lst in values:
4. for element in lst:
5. if v > element:
6. v = element
7. print(v)
a) 1
b) 3
c) 5
d) 6
Answer: a
Explanation: Execute in the shell to verify.
5. What will be the output of the following Python code?
1. values = [[3, 4, 5, 1 ], [33, 6, 1, 2]]
2. for row in values:
3. row.sort()
4. for element in row:
5. print(element, end = " ")
6. print()
a) The program prints two rows 3 4 5 1 followed by 33 6 1 2
b) The program prints on row 3 4 5 1 33 6 1 2
c) The program prints two rows 3 4 5 1 followed by 33 6 1 2
d) The program prints two rows 1 3 4 5 followed by 1 2 6 33
Answer: d
Explanation: Execute in the shell to verify.
6. What will be the output of the following Python code?
1. matrix = [[1, 2, 3, 4],
2. [4, 5, 6, 7],
3. [8, 9, 10, 11],
4. [12, 13, 14, 15]]
5. for i in range(0, 4):
6. print(matrix[i][1], end = " ")
a) 1 2 3 4
b) 4 5 6 7
c) 1 3 8 12
d) 2 5 9 13
Answer: d
Explanation: Execute in the shell to verify.
7. What will be the output of the following Python code?
1. def m(list):
2. v = list[0]
3. for e in list:
4. if v < e: v = e
5. return v
6. values = [[3, 4, 5, 1], [33, 6, 1, 2]]
7. for row in values:
8. print(m(row), end = " ")
a) 3 33
b) 1 1
c) 5 6
d) 5 33
Answer: d
Explanation: Execute in the shell to verify.
8. What will be the output of the following Python code?
1. data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
2. print(data[1][0][0])
a) 1
b) 2
c) 4
d) 5
Answer: d
Explanation: Execute in the shell to verify.
9. What will be the output of the following Python code?
1. data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
2. def ttt(m):
3. v = m[0][0]
4. for row in m:
5. for element in row:
6. if v < element: v = element
7. return v
8. print(ttt(data[0]))
a) 1
b) 2
c) 4
d) 5
Answer: c
Explanation: Execute in the shell to verify.
10. What will be the output of the following Python code?
1. points = [[1, 2], [3, 1.5], [0.5, 0.5]]
2. points.sort()
3. print(points)
a) [[1, 2], [3, 1.5], [0.5, 0.5]]
b) [[3, 1.5], [1, 2], [0.5, 0.5]]
c) [[0.5, 0.5], [1, 2], [3, 1.5]]
d) [[0.5, 0.5], [3, 1.5], [1, 2]]
Answer: c
Explanation: Execute in the shell to verify.
To practice all questions papers on Python, .
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Advanced Formatting Tools”.
1. What will be the output of the following Python code?
l=list('HELLO')
'first={0[0]}, third={0[2]}'.format(l)
a) ‘first=H, third=L’
b) ‘first=0, third=2’
c) Error
d) ‘first=0, third=L’
Answer: a
Explanation: In the code shown above, the value for first is substituted by l[0], that is H and the value for third is substituted by l[2],
that is L. Hence the output of the code shown above is: ‘first=H, third=L’. The list l= [‘H’, ‘E’, ‘L’, ‘L’, ‘O’].
2. What will be the output of the following Python code?
l=list('HELLO')
p=l[0], l[-1], l[1:3]
'a={0}, b={1}, c={2}'.format(*p)
a) Error
b) “a=’H’, b=’O’, c=(E, L)”
c) “a=H, b=O, c=[‘E’, ‘L’]”
d) Junk value
Answer: c
Explanation: In the code shown above, the value for a is substituted by l[0], that is ‘H’, the value of b is substituted by l[-1], that is
‘O’ and the value for c is substituted by l[1:3]. Here the use of *p is to unpack a tuple items into individual function arguments.
3. The formatting method {1:<10} represents the ___________ positional argument, _________ justified in a 10 character wide
field.
a) first, right
b) second, left
c) first, left
d) second, right
Answer: b
Explanation: The formatting method {1:<10} represents the second positional argument, left justified in a 10 character wide field.
4. What will be the output of the following Python code?
hex(255), int('FF', 16), 0xFF
a) [0xFF, 255, 16, 255]
b) (‘0xff’, 155, 16, 255)
c) Error
d) (‘0xff’, 255, 255)
Answer: d
Explanation: The code shown above converts the value 255 into hexadecimal, that is, 0xff. The value ‘FF’ into integer. Hence the
output of the code shown is: (‘0xff’, 255, 255).
5. The output of the two codes shown below is the same.
i. bin((2**16)-1)
ii. '{}'.format(bin((2**16)-1))
a) True
b) False
Answer: a
Explanation: The output of both of the codes shown above is ‘0b1111111111111111’. Hence the statement is true.
6. What will be the output of the following Python code?
'{a}{b}{a}'.format(a='hello', b='world')
a) ‘hello world’
b) ‘hello’ ‘world’ ‘hello’
c) ‘helloworldhello’
d) ‘hello’ ‘hello’ ‘world’
Answer: c
Explanation: The code shown above prints the values substituted for a, b, a, in the same order. This operation is performed
using the format function. Hence the output of the code is: ‘helloworldhello’.
7. What will be the output of the following Python code?
D=dict(p='san', q='foundry')
'{p}{q}'.format(**D)
a) Error
b) sanfoundry
c) san foundry
d) {‘san’, ‘foundry’}
Answer: b
Explanation: The code shown above prints the values substituted for p and q in the same order. Note that there is no blank space
between p and q. Hence the output is: sanfoundry.
8. What will be the output of the following Python code?
'The {} side {1} {2}'.format('bright', 'of', 'life')
a) Error
b) ‘The bright side of life’
c) ‘The {bright} side {of} {life}’
d) No output
Answer: a
Explanation: The code shown above results in an error. This is because we have switched from automatic field numbering to
manual field numbering, that is, from {} to {1}. Hence this code results in an error.
9. What will be the output of the following Python code?
'{0:f}, {1:2f}, {2:05.2f}'.format(1.23456, 1.23456, 1.23456)
a) Error
b) ‘1.234560, 1.22345, 1.23’
c) No output
d) ‘1.234560, 1.234560, 01.23’
Answer: d
Explanation: In the code shown above, various formatting options are displayed using the format option. Hence the output of this
code is: ‘1.234560, 1.234560, 01.23’
10. What will be the output of the following Python code?
'%.2f%s' % (1.2345, 99)
a) ‘1.2345’, ‘99’
b) ‘1.2399’
c) ‘1.234599’
d) 1.23, 99
Answer: b
Explanation: In this code, we must notice that since multiple values haven been given, they should be enclosed in a tuple. Since
the formatting format is %.2f, the value 1.2345 is reduced to two decimal places. Hence the output of the code shown above:
‘1.2399’.
11. What will be the output of the following Python code?
'%s' %((1.23,),)
a) ‘(1.23,)’
b) 1.23,
c) (,1.23)
d) ‘1.23’
Answer: a
Explanation: The formatting expression accepts either a single substitution value, or a tuple of one or more items. Since single
item can be given either by itself or within the tuple, a tuple to be formatted must be provided as a tested tuple. Hence the output
of the code is: >>> ‘%s’ %((1.23,),).
12. What will be the output of the following two codes?
i. '{0}'.format(4.56)
ii. '{0}'.format([4.56,])
a) ‘4.56’, ‘4.56,’
b) ‘4.56’, ‘[4.56]’
c) 4.56, [4.56,]
d) 4.56, [4.56,]
Answer: b
Explanation: The code shown above shows the formatting option on the same value, that is 4.56, where in the second case, the
value is enclosed in a list. Hence the output of the code shown above is:
‘4.56’, ‘[4.56]’
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Bitwise – 1”.
1. What will be the output of the following Python code snippet if x=1?
x<<2
a) 8
b) 1
c) 2
d) 4
Answer: d
Explanation: The binary form of 1 is 0001. The expression x<<2 implies we are performing bitwise left shift on x. This shift yields
the value: 0100, which is the binary form of the number 4.
2. What will be the output of the following Python expression?
bin(29)
a) ‘0b10111’
b) ‘0b11101’
c) ‘0b11111’
d) ‘0b11011’
Answer: b
Explanation: The binary form of the number 29 is 11101. Hence the output of this expression is ‘0b11101’.
3. What will be the value of x in the following Python expression, if the result of that expression is 2?
x>>2
a) 8
b) 4
c) 2
d) 1
Answer: a
Explanation: When the value of x is equal to 8 (1000), then x>>2 (bitwise right shift) yields the value 0010, which is equal to 2.
Hence the value of x is 8.
4. What will be the output of the following Python expression?
int(1011)?
a) 1011
b) 11
c) 13
d) 1101
Answer: a
Explanation: The result of the expression shown will be 1011. This is because we have not specified the base in this expression.
Hence it automatically takes the base as 10.
5. To find the decimal value of 1111, that is 15, we can use the function:
a) int(1111,10)
b) int(‘1111’,10)
c) int(1111,2)
d) int(‘1111’,2)
Answer: d
Explanation: The expression int(‘1111’,2) gives the result 15. The expression int(‘1111’, 10) will give the result 1111.
6. What will be the output of the following Python expression if x=15 and y=12?
x& y
a) b1101
b) 0b1101
c) 12
d) 1101
Answer: c
Explanation: The symbol ‘&’ represents bitwise AND. This gives 1 if both the bits are equal to 1, else it gives 0. The binary form
of 15 is 1111 and that of 12 is 1100. Hence on performing the bitwise AND operation, we get 1100, which is equal to 12.
7. Which of the following expressions results in an error?
a) int(1011)
b) int(‘1011’,23)
c) int(1011,2)
d) int(‘1011’)
Answer: c
Explanation: The expression int(1011,2) results in an error. Had we written this expression as int(‘1011’,2), then there would not
be an error.
8. Which of the following represents the bitwise XOR operator?
a) &
b) ^
c) |
d) !
Answer: b
Explanation: The ^ operator represent bitwise XOR operation. &: bitwise AND, | : bitwise OR and ! represents bitwise NOT.
9. What is the value of the following Python expression?
bin(0x8)
a) ‘0bx1000’
b) 8
c) 1000
d) ‘0b1000’
Answer: d
Explanation: The prefix 0x specifies that the value is hexadecimal in nature. When we convert this hexadecimal value to binary
form, we get the result as: ‘0b1000’.
10. What will be the output of the following Python expression?
0x35 | 0x75
a) 115
b) 116
c) 117
d) 118
Answer: c
Explanation: The binary value of 0x35 is 110101 and that of 0x75 is 1110101. On OR-ing these two values we get the output as:
1110101, which is equal to 117. Hence the result of the above expression is 117.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Bitwise – 2”.
1. It is not possible for the two’s complement value to be equal to the original value in any case.
a) True
b) False
Answer: b
Explanation: In most cases the value of two’s complement is different from the original value. However, there are cases in which
the two’s complement value may be equal to the original value. For example, the two’s complement of 10000000 is also equal to
10000000. Hence the statement is false.
2. The one’s complement of 110010101 is:
a) 001101010
b) 110010101
c) 001101011
d) 110010100
Answer: a
Explanation: The one’s complement of a value is obtained by simply changing all the 1’s to 0’s and all the 0’s to 1’s. Hence the
one’s complement of 110010101 is 001101010.
3. Bitwise _________ gives 1 if either of the bits is 1 and 0 when both of the bits are 1.
a) OR
b) AND
c) XOR
d) NOT
Answer: c
Explanation: Bitwise XOR gives 1 if either of the bits is 1 and 0 when both of the bits are 1.
4. What will be the output of the following Python expression?
4^12
a) 2
b) 4
c) 8
d) 12
Answer: c
Explanation: ^ is the XOR operator. The binary form of 4 is 0100 and that of 12 is 1100. Therefore, 0100^1100 is 1000, which is
equal to 8.
5. Any odd number on being AND-ed with ________ always gives 1. Hint: Any even number on being AND-ed with this value
always gives 0.
a) 10
b) 2
c) 1
d) 0
Answer: c
Explanation: Any odd number on being AND-ed with 1 always gives 1. Any even number on being AND-ed with this value always
gives 0.
6. What will be the value of the following Python expression?
bin(10-2)+bin(12^4)
a) 0b10000
b) 0b10001000
c) 0b1000b1000
d) 0b10000b1000
Answer: d
Explanation: The output of bin(10-2) = 0b1000 and that of bin(12^4) is ob1000. Hence the output of the above expression is:
0b10000b1000.
7. Which of the following expressions can be used to multiply a given number ‘a’ by 4?
a) a<<2
b) a<<4
c) a>>2
d) a>>4
Answer: a
Explanation: Let us consider an example wherein a=2. The binary form of 2 is 0010. When we left shift this value by 2, we get
1000, the value of which is 8. Hence if we want to multiply a given number ‘a’ by 4, we can use the expression: a<<2.
8. What will be the output of the following Python code if a=10 and b =20?
a=10
b=20
a=a^b
b=a^b
a=a^b
print(a,b)
a) 10 20
b) 10 10
c) 20 10
d) 20 20
Answer: c
Explanation: The code shown above is used to swap the contents of two memory locations using bitwise X0R operator. Hence
the output of the code shown above is: 20 10.
9. What is the two’s complement of -44?
a) 1011011
b) 11010100
c) 11101011
d) 10110011
Answer: b
Explanation: The binary form of -44 is 00101100. The one’s complement of this value is 11010011. On adding one to this we
get: 11010100 (two’s complement).
10. What will be the output of the following Python expression?
~100?
a) 101
b) -101
c) 100
d) -100
Answer: b
Explanation: Suppose we have an expression ~A. This is evaluated as: -A – 1. Therefore, the expression ~100 is evaluated as -
100 – 1, which is equal to -101.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Boolean”.
1. What will be the output of the following Python code snippet?
bool(‘False’)
bool()
a)
True
True
b)
False
True
c)
False
False
d)
True
False
Answer: d
Explanation: The Boolean function returns true if the argument passed to the bool function does not amount to zero. In the first
example, the string ‘False’ is passed to the function bool. This does not amount to zero and hence the output is true. In the
second function, an empty list is passed to the function bool. Hence the output is false.

2. What will be the output of the following Python code snippet?


['hello', 'morning'][bool('')]
a) error
b) no output
c) hello
d) morning
Answer: c
Explanation: The line of code shown above can be simplified to state that ‘hello’ should be printed if the argument passed to the
Boolean function amounts to zero, else ‘morning’ will be printed.
3. What will be the output of the following Python code snippet?
not(3>4)
not(1&1)
a)
True
True
b)
True
False
c)
False
True
d)
False
False
Answer: b
Explanation: The function not returns true if the argument amounts to false, and false if the argument amounts to true. Hence the
first function returns false, and the second function returns false.

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


['f', 't'][bool('spam')]
a) t
b) f
c) No output
d) Error
Answer: a
Explanation: The line of code can be translated to state that ‘f’ is printed if the argument passed to the Boolean function amount
to zero. Else ‘t’ is printed. The argument given to the Boolean function in the above case is ‘spam’, which does not amount to
zero. Hence the output is t.
5. What will be the output of the following Python code?
l=[1, 0, 2, 0, 'hello', '', []]
list(filter(bool, l))
a) Error
b) [1, 0, 2, 0, ‘hello’, ”, []]
c) [1, 0, 2, ‘hello’, ”, []]
d) [1, 2, ‘hello’]
Answer: d
Explanation: The code shown above returns a new list containing only those elements of the list l which do not amount to zero.
Hence the output is: [1, 2, ‘hello’].
6. What will be the output of the following Python code if the system date is 21st June, 2017 (Wednesday)?
[] or {}
{} or []
a)
[]
{}
b)
[]
[]
c)
{}
[]
d)
{}
{}
Answer: c
Explanation: The code shown above shows two functions. In both the cases the right operand is returned. This is because each
function is evaluated from left to right. Since the left operand is false, it is assumed that the right operand must be true and hence
the right operand is returned in each of the above case.

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


class Truth:
pass
x=Truth()
bool(x)
a) pass
b) true
c) false
d) error
Answer: b
Explanation: If the truth method is not defined, the object is considered true. Hence the output of the code shown above is true.
8. What will be the output of the following Python code?
if (9 < 0) and (0 < -9):
print("hello")
elif (9 > 0) or False:
print("good")
else:
print("bad")
a) error
b) hello
c) good
d) bad
Answer: c
Explanation: The code shown above prints the appropriate option depending on the conditions given. The condition which
matches is (9>0), and hence the output is: good.
9. Which of the following Boolean expressions is not logically equivalent to the other three?
a) not(-6<0 or-6>10)
b) -6>=0 and -6<=10
c) not(-6<10 or-6==10)
d) not(-6>10 or-6==10)
Answer: d
Explanation: The expression not(-6<0 or -6>10) returns the output False.
The expression -6>=0 and -6<=10 returns the output False.
The expression not(-6<10 or -6==10) returns the output False.
The expression not(-6>10 or -6==10) returns the output True.
10. What will be the output of the following Python code snippet?
not(10<20) and not(10>30)
a) True
b) False
c) Error
d) No output
Answer: b
Explanation: The expression not(10<20) returns false. The expression not(10>30) returns true. The and operation between false
and true returns false. Hence the output is false.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Built-in Functions – 1”.
1. Which of the following functions is a built-in function in python?
a) seed()
b) sqrt()
c) factorial()
d) print()
Answer: d
Explanation: The function seed is a function which is present in the random module. The functions sqrt and factorial are a part of
the math module. The print function is a built-in function which prints a value directly to the system output.
2. What will be the output of the following Python expression?
round(4.576)
a) 4.5
b) 5
c) 4
d) 4.6
Answer: b
Explanation: This is a built-in function which rounds a number to give precision in decimal digits. In the above case, since the
number of decimal places has not been specified, the decimal number is rounded off to a whole number. Hence the output will
be 5.
3. The function pow(x,y,z) is evaluated as:
a) (x**y)**z
b) (x**y) / z
c) (x**y) % z
d) (x**y)*z
Answer: c
Explanation: The built-in function pow() can accept two or three arguments. When it takes in two arguments, they are evaluated
as x**y. When it takes in three arguments, they are evaluated as (x**y)%z.
4. What will be the output of the following Python function?
all([2,4,0,6])
a) Error
b) True
c) False
d) 0
Answer: c
Explanation: The function all returns false if any one of the elements of the iterable is zero and true if all the elements of the
iterable are non zero. Hence the output of this function will be false.
5. What will be the output of the following Python expression?
round(4.5676,2)?
a) 4.5
b) 4.6
c) 4.57
d) 4.56
Answer: c
Explanation: The function round is used to round off the given decimal number to the specified decimal places. In this case, the
number should be rounded off to two decimal places. Hence the output will be 4.57.
6. What will be the output of the following Python function?
any([2>8, 4>2, 1>2])
a) Error
b) True
c) False
d) 4>2
Answer: b
Explanation: The built-in function any() returns true if any or more of the elements of the iterable is true (non zero), If all the
elements are zero, it returns false.
7. What will be the output of the following Python function?
import math
abs(math.sqrt(25))
a) Error
b) -5
c) 5
d) 5.0
Answer: d
Explanation: The abs() function prints the absolute value of the argument passed. For example: abs(-5)=5. Hence, in this case
we get abs(5.0)=5.0.
8. What will be the output of the following Python function?
sum(2,4,6)
sum([1,2,3])
a) Error, 6
b) 12, Error
c) 12, 6
d) Error, Error
Answer: a
Explanation: The first function will result in an error because the function sum() is used to find the sum of iterable numbers. Hence
the outcomes will be Error and 6 respectively.
9. What will be the output of the following Python function?
all(3,0,4.2)
a) True
b) False
c) Error
d) 0
Answer: c
Explanation: The function all() returns ‘True’ if any one or more of the elements of the iterable are non zero. In the above case, the
values are not iterable, hence an error is thrown.
10. What will be the output of the following Python function?
min(max(False,-3,-4), 2,7)
a) 2
b) False
c) -3
d) -4
Answer: b
Explanation: The function max() is being used to find the maximum value from among -3, -4 and false. Since false amounts to the
value zero, hence we are left with min(0, 2, 7) Hence the output is 0 (false).
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Built-in Functions – 2”.
1. What will be the output of the following Python functions?
chr(‘97’)
chr(97)
a)
a
Error
b)
‘a’
a
c)
Error
a
d)
Error
Error
Answer: c
Explanation: The built-in function chr() returns the alphabet corresponding to the value given as an argument. This function
accepts only integer type values. In the first function, we have passed a string. Hence the first function throws an error.

2. What will be the output of the following Python function?


complex(1+2j)
a) Error
b) 1
c) 2j
d) 1+2j
Answer: d
Explanation: The built-in function complex() returns the argument in a complex form. Hence the output of the function shown
above will be 1+2j.
3. What is the output of the function complex()?
a) 0j
b) 0+0j
c) 0
d) Error
Answer: a
Explanation: The complex function returns 0j if both of the arguments are omitted, that is, if the function is in the form of complex()
or complex(0), then the output will be 0j.
4. The function divmod(a,b), where both ‘a’ and ‘b’ are integers is evaluated as:
a) (a%b, a//b)
b) (a//b, a%b)
c) (a//b, a*b)
d) (a/b, a%b)
Answer: b
Explanation: The function divmod(a,b) is evaluated as a//b, a%b, if both ‘a’ and ‘b’ are integers.
5. What will be the output of the following Python function?
divmod(10.5,5)
divmod(2.4,1.2)
a)
(2.00, 0.50)
(2.00, 0.00)
b)
(2, 0.5)
(2, 0)
c)
(2.0, 0.5)
(2.0, 0.0)
d)
(2, 0.5)
(2)
Answer: c
Explanation: See python documentation for the function divmod.

6. The function complex(‘2-3j’) is valid but the function complex(‘2 – 3j’) is invalid.
a) True
b) False
Answer: a
Explanation: When converting from a string, the string must not contain any blank spaces around the + or – operator. Hence the
function complex(‘2 – 3j’) will result in an error.
7. What will be the output of the following Python function?
list(enumerate([2, 3]))
a) Error
b) [(1, 2), (2, 3)]
c) [(0, 2), (1, 3)]
d) [(2, 3)]
Answer: c
Explanation: The built-in function enumerate() accepts an iterable as an argument. The function shown in the above case returns
containing pairs of the numbers given, starting from 0. Hence the output will be: [(0, 2), (1,3)].
8. What will be the output of the following Python functions?
x=3
eval('x^2')
a) Error
b) 1
c) 9
d) 6
Answer: b
Explanation: The function eval is use to evaluate the expression that it takes as an argument. In the above case, the eval()
function is used to perform XOR operation between 3 and 2. Hence the output is 1.
9. What will be the output of the following Python functions?
float('1e-003')
float('2e+003')
a)
3.00
300
b)
0.001
2000.0
c)
0.001
200
d)
Error
2003
Answer: b
Explanation: The output of the first function will be 0.001 and that of the second function will be 2000.0. The first function created
a floating point number up to 3 decimal places and the second function adds 3 zeros after the given number.

10. Which of the following functions does not necessarily accept only iterables as arguments?
a) enumerate()
b) all()
c) chr()
d) max()
Answer: c
Explanation: The functions enumerate(), all() and max() accept iterables as arguments whereas the function chr() throws an error
on receiving an iterable as an argument. Also note that the function chr() accepts only integer values.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Built-in Functions – 3”.
1. Which of the following functions accepts only integers as arguments?
a) ord()
b) min()
c) chr()
d) any()
Answer: c
Explanation: The function chr() accepts only integers as arguments. The function ord() accepts only strings. The functions min()
and max() can accept floating point as well as integer arguments.
2. Suppose there is a list such that: l=[2,3,4]. If we want to print this list in reverse order, which of the following methods should be
used?
a) reverse(l)
b) list(reverse[(l)])
c) reversed(l)
d) list(reversed(l))
Answer: d
Explanation: The built-in function reversed() can be used to reverse the elements of a list. This function accepts only an iterable
as an argument. To print the output in the form of a list, we use: list(reversed(l)). The output will be: [4,3,2].
3. What will be the output of the following Python function?
float(' -12345\n')
(Note that the number of blank spaces before the number is 5)
a)   -12345.0 (5 blank spaces before the number)
b) -12345.0
c) Error
d) -12345.000000000…. (infinite decimal places)
Answer: b
Explanation: The function float() will remove all the blank spaces and convert the integer to a floating point number. Hence the
output will be: -12345.0.
4. What will be the output of the following Python function?
ord(65)
ord(‘A’)
a)
A
65
b)
Error
65
c)
A
Error
d)
Error
Error
Answer: b
Explanation: The built-in function ord() is used to return the ASCII value of the alphabet passed to it as an argument. Hence the
first function results in an error and the output of the second function is 65.

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


float(‘-infinity’)
float(‘inf’)
a)
–inf
inf
b)
–infinity
inf
c)
Error
Error
d)
Error
Junk value
Answer: a
Explanation: The output of the first function will be –inf and that of the second function will be inf.

6. Which of the following functions will not result in an error when no arguments are passed to it?
a) min()
b) divmod()
c) all()
d) float()
Answer: d
Explanation: The built-in functions min(), max(), divmod(), ord(), any(), all() etc throw an error when no arguments are passed to
them. However there are some built-in functions like float(), complex() etc which do not throw an error when no arguments are
passed to them. The output of float() is 0.0.
7. What will be the output of the following Python function?
hex(15)
a) f
b) 0xF
c) 0Xf
d) 0xf
Answer: d
Explanation: The function hex() is used to convert the given argument into its hexadecimal representation, in lower case. Hence
the output of the function hex(15) is 0xf.
8. Which of the following functions does not throw an error?
a) ord()
b) ord(‘ ‘)
c) ord(”)
d) ord(“”)
Answer: b
Explanation: The function ord() accepts a character. Hence ord(), ord(”) and ord(“”) throw errors. However the function ord(‘ ‘)
does not throw an error because in this case, we are actually passing a blank space as an argument. The output of ord(‘ ‘) is 32
(ASCII value corresponding to blank space).
9. What will be the output of the following Python function?
len(["hello",2, 4, 6])
a) 4
b) 3
c) Error
d) 6
Answer: a
Explanation: The function len() returns the length of the number of elements in the iterable. Therefore the output of the function
shown above is 4.
10. What will be the output of the following Python function?
oct(7)
oct(‘7’)
a)
Error
07
b)
0o7
Error
c)
0o7
Error
d)
07
0o7
Answer: c
Explanation: The function oct() is used to convert its argument into octal form. This function does not accept strings. Hence the
second function results in an error while the output of the first function is 0o7.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Classes and Objects – 1”.
1. _____ represents an entity in the real world with its identity and behaviour.
a) A method
b) An object
c) A class
d) An operator
Answer: b
Explanation: An object represents an entity in the real world that can be distinctly identified. A class may define an object.
2. _____ is used to create an object.
a) class
b) constructor
c) User-defined functions
d) In-built functions
Answer: b
Explanation: The values assigned by the constructor to the class members is used to create the object.
3. What will be the output of the following Python code?
class test:
def __init__(self,a="Hello World"):
self.a=a

def display(self):
print(self.a)
obj=test()
obj.display()
a) The program has an error because constructor can’t have default arguments
b) Nothing is displayed
c) “Hello World” is displayed
d) The program has an error display function doesn’t have parameters
Answer: c
Explanation: The program has no error. “Hello World” is displayed. Execute in python shell to verify.
4. What is setattr() used for?
a) To access the attribute of the object
b) To set an attribute
c) To check if an attribute exists or not
d) To delete an attribute
Answer: b
Explanation: setattr(obj,name,value) is used to set an attribute. If attribute doesn’t exist, then it would be created.
5. What is getattr() used for?
a) To access the attribute of the object
b) To delete an attribute
c) To check if an attribute exists or not
d) To set an attribute
Answer: a
Explanation: getattr(obj,name) is used to get the attribute of an object.
6. What will be the output of the following Python code?
class change:
def __init__(self, x, y, z):
self.a = x + y + z

x = change(1,2,3)
y = getattr(x, 'a')
setattr(x, 'a', y+1)
print(x.a)
a) 6
b) 7
c) Error
d) 0
Answer: b
Explanation: First, a=1+2+3=6. Then, after setattr() is invoked, x.a=6+1=7.
7. What will be the output of the following Python code?
class test:
def __init__(self,a):
self.a=a

def display(self):
print(self.a)
obj=test()
obj.display()
a) Runs normally, doesn’t display anything
b) Displays 0, which is the automatic default value
c) Error as one argument is required while creating the object
d) Error as display function requires additional argument
Answer: c
Explanation: Since, the __init__ special method has another argument a other than self, during object creation, one argument is
required. For example: obj=test(“Hello”)
8. Is the following Python code correct?
>>> class A:
def __init__(self,b):
self.b=b
def display(self):
print(self.b)
>>> obj=A("Hello")
>>> del obj
a) True
b) False
Answer: a
Explanation: It is possible to delete an object of the class. On further typing obj in the python shell, it throws an error because the
defined object has now been deleted.
9. What will be the output of the following Python code?
class test:
def __init__(self):
self.variable = 'Old'
self.Change(self.variable)
def Change(self, var):
var = 'New'
obj=test()
print(obj.variable)
a) Error because function change can’t be called in the __init__ function
b) ‘New’ is printed
c) ‘Old’ is printed
d) Nothing is printed
Answer: c
Explanation: This is because strings are immutable. Hence any change made isn’t reflected in the original string.
10. What is Instantiation in terms of OOP terminology?
a) Deleting an instance of class
b) Modifying an instance of class
c) Copying an instance of class
d) Creating an instance of class
Answer: d
Explanation: Instantiation refers to creating an object/instance for a class.
11. What will be the output of the following Python code?
class fruits:
def __init__(self, price):
self.price = price
obj=fruits(50)

obj.quantity=10
obj.bags=2

print(obj.quantity+len(obj.__dict__))
a) 12
b) 52
c) 13
d) 60
Answer: c
Explanation: In the above code, obj.quantity has been initialised to 10. There are a total of three items in the dictionary, price,
quantity and bags. Hence, len(obj.__dict__) is 3.
12. What will be the output of the following Python code?
class Demo:
def __init__(self):
pass

def test(self):
print(__name__)

obj = Demo()
obj.test()
a) Exception is thrown
b) __main__
c) Demo
d) test
Answer: b
Explanation: Since the above code is being run not as a result of an import from another module, the variable will have value
“__main__”.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Classes and Objects – 2”.
1. The assignment of more than one function to a particular operator is _______
a) Operator over-assignment
b) Operator overriding
c) Operator overloading
d) Operator instance
Answer: c
Explanation: The assignment of more than one function to a particular operator is called as operator overloading.
2. Which of the following is not a class method?
a) Non-static
b) Static
c) Bounded
d) Unbounded
Answer: a
Explanation: The three different class methods in Python are static, bounded and unbounded methods.
3. What will be the output of the following Python code?
def add(c,k):
c.test=c.test+1
k=k+1
class A:
def __init__(self):
self.test = 0
def main():
Count=A()
k=0

for i in range(0,25):
add(Count,k)
print("Count.test=", Count.test)
print("k =", k)
main()
a) Exception is thrown
b)
Count.test=25
k=25
c)
Count.test=25
k=0
d)
Count.test=0
k=0
Answer: c
Explanation: The program has no error. Here, test is a member of the class while k isn’t. Hence test keeps getting incremented
25 time while k remains 0.

4. Which of the following Python code creates an empty class?


a)
class A:
return
b)
class A:
pass
c)
class A:
d) It is not possible to create an empty class
Answer: b
Explanation: Execute in python shell to verify.
5. Is the following Python code valid?
class B(object):
def first(self):
print("First method called")
def second():
print("Second method called")
ob = B()
B.first(ob)
a) It isn’t as the object declaration isn’t right
b) It isn’t as there isn’t any __init__ method for initializing class members
c) Yes, this method of calling is called unbounded method call
d) Yes, this method of calling is called bounded method call
Answer: c
Explanation: The method may be created in the method demonstrated in the code as well and this is called as the unbounded
method call. Calling the method using obj.one() is the bounded method call.
6. What are the methods which begin and end with two underscore characters called?
a) Special methods
b) In-built methods
c) User-defined methods
d) Additional methods
Answer: a
Explanation: Special methods like __init__ begin and end with two underscore characters.
7. Special methods need to be explicitly called during object creation.
a) True
b) False
Answer: b
Explanation: Special methods are automatically called during object creation.
8. What will be the output of the following Python code?
>>> class demo():
def __repr__(self):
return '__repr__ built-in function called'
def __str__(self):
return '__str__ built-in function called'
>>> s=demo()
>>> print(s)
a) Error
b) Nothing is printed
c) __str__ called
d) __repr__ called
Answer: c
Explanation: __str__ is used for producing a string representation of an object’s value that Python can evaluate. Execute in
python shell to verify.
9. What will be the output of the following Python code?
>>> class demo():
def __repr__(self):
return '__repr__ built-in function called'
def __str__(self):
return '__str__ built-in function called'
>>> s=demo()
>>> print(s)
a) __str__ called
b) __repr__ called
c) Error
d) Nothing is printed
Answer: a
Explanation: __str__ is used for producing a string representation of an object’s value that is most readable for humans. Execute
in python shell to verify.
10. What is hasattr(obj,name) used for?
a) To access the attribute of the object
b) To delete an attribute
c) To check if an attribute exists or not
d) To set an attribute
Answer: c
Explanation: hasattr(obj,name) checks if an attribute exists or not and returns True or False.
11. What will be the output of the following Python code?
class stud:
def __init__(self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print("Roll no : ", self.roll_no, ", Grade: ", self.grade)
stud1 = stud(34, 'S')
stud1.age=7
print(hasattr(stud1, 'age'))
a) Error as age isn’t defined
b) True
c) False
d) 7
Answer: b
Explanation: Execute in python shell to verify.
12. What is delattr(obj,name) used for?
a) To print deleted attribute
b) To delete an attribute
c) To check if an attribute is deleted or not
d) To set an attribute
Answer: b
Explanation: delattr(obj,name) deletes an attribute in a class.
13. __del__ method is used to destroy instances of a class.
a) True
b) False
Answer: a
Explanation: ___del__ method acts as a destructor and is used to destroy objects of classes.
14. What will be the output of the following Python code?
class stud:
‘Base class for all students’
def __init__(self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print("Roll no : ", self.roll_no, ", Grade: ", self.grade)
print(student.__doc__)
a) Exception is thrown
b) __main__
c) Nothing is displayed
d) Base class for all students
Answer: d
Explanation: ___doc__ built-in class attribute is used to print the class documentation string or none, if undefined.
15. What does print(Test.__name__) display (assuming Test is the name of the class)?
a) ()
b) Exception is thrown
c) Test
d) __main__
Answer: c
Explanation: __name__ built-in class attribute is used to display the class name.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Datetime Module – 1”.
1. What will be the output of the following Python code?
import datetime
d=datetime.date(2016,7,24)
print(d)
a) Error
b) 2017-07-24
c) 2017-7-24
d) 24-7-2017
Answer: b
Explanation: In the snippet of code shown above, we are simply printing the date entered by us. We enter the date in the format:
yyyy,m,dd. The date is then printed in the format: yyyy-mm-dd. Hence the output is: 2017-07-24.
2. What will be the output of the following Python code?
import datetime
d=datetime.date(2017,06,18)
print(d)
a) Error
b) 2017-06-18
c) 18-06-2017
d) 06-18-2017
Answer: a
Explanation: The code shown above will result in an error because of the format of the date entered. Had the date been entered
as: d=datetime.date(2017,6,18), no error would have been thrown.
3. What will be the output of the following Python code if the system date is 18th August, 2016?
tday=datetime.date.today()
print(tday.month())
a) August
b) Aug
c) 08
d) 8
Answer: d
Explanation: The code shown above prints the month number from the system date. Therefor the output will be 8 if the system
date is 18th August, 2016.
4. What will be the output of the following Python code if the system date is 18th June, 2017 (Sunday)?
import datetime
tday=datetime.date.today()
print(tday)
a) 18-06-2017
b) 06-18-2017
c) 2017-06-18
d) Error
Answer: c
Explanation: The code shown above prints the system date in the format yyyy-mm-dd. Hence the output of this code is: 2017-06-
18.
5. What will be the output of the following Python code if the system date is 18th June, 2017 (Sunday)?
tday=datetime.date.today()
print(tday.weekday())
a) 6
b) 1
c) 0
d) 7
Answer: a
Explanation: The code shown above prints an integer depending on which day of the week it is. Monday-0, Tuesday-1,
Wednesday-2, Thursday-3, Friday-4, Saturday-5, Sunday-6. Hence the output is 6 in the case shown above.
6. What will be the output of the following Python code if the system date is 21st June, 2017 (Wednesday)?
tday=datetime.date.today()
print(tday.isoweekday())
a) Wed
b) Wednesday
c) 2
d) 3
Answer: d
Explanation: This code prints an integer depending on which day of the week it is. Monday-1, Tuesday-2, Wednesday-3,
Thursday-4, Friday-5, Saturday-6, Sunday-7. Hence the output of the code shown above is 3.
7. Point out the error (if any) in the code shown below if the system date is 18th June, 2017?
tday=datetime.date.today()
bday=datetime.date(2017,9,18)
till_bday=bday-tday
print(till_bday)
a) 3 months, 0:00:00
b) 90 days, 0:00:00
c) 3 months 2 days, 0:00:00
d) 92 days, 0:00:00
Answer: d
Explanation: The code shown above can be used to find the number of days between two given dates. The output of the code
shown above will thus be 92.
8. The value returned when we use the function isoweekday() is ______ and that for the function weekday() is ________ if the
system date is 19th June, 2017 (Monday).
a) 0,0
b) 0,1
c) 1,0
d) 1,1
Answer: c
Explanation: The value returned when we use the function isoweekday() is 1 and that for the function weekday() is 0 if the system
date is 19th June, 2017 (Monday).
9. Which of the following will throw an error if used after the following Python code?
tday=datetime.date.today()
bday=datetime.date(2017,9,18)
t_day=bday-tday
a) print(t_day.seconds)
b) print(t_day.months)
c) print(t_day.max)
d) print(t_day.resolution)
Answer: b
Explanation: The statement: print(t_day.months) will throw an error because there is no function such as t_day.months, whereas
t_day.seconds, t_day.max and t_day.resolution are valid, provided that t_day is defined.
10. What will be the output of the following Python code if the system date is: 6/19/2017
tday=datetime.date.today()
tdelta=datetime.timedelta(days=10)
print(tday+tdelta)
a) 2017-16-19
b) 2017-06-9
c) 2017-06-29
d) Error
Answer: c
Explanation: The code shown above will add the specified number of days to the current date and print the new date. On adding
ten days to 6/19/2017, we get 6/29/2017. Hence the output is: 2017-06-29.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Datetime Module – 2”.
1. The output of both of the print statements is the same.
import datetime
dt_1 = datetime.datetime.today()
dt_2 = datetime.datetime.now()
print(dt_1)
print(dt_2)
a) True
b) False
Answer: b
Explanation: The output of the two print statements is not the same because of the difference in time between the execution of
the two print statements. There is a difference in the order of milliseconds between the two statements and this is reflected in the
output.
2. Which of the following functions can be used to find the coordinated universal time, assuming that the datetime module has
already been imported?
a) datetime.utc()
b) datetime.datetime.utc()
c) datetime.utcnow()
d) datetime.datetime.utcnow()
Answer: d
Explanation: The function datetime.datetime.utcnow() can be used to find the UTC (Coordinated Universal Time), assuming that
the datetime module has already been imported. The other function s shown above are invalid.
3. What will be the output of the following Python code?
import time
time.time()
a) The number of hours passed since 1st January, 1970
b) The number of days passed since 1st January, 1970
c) The number of seconds passed since 1st January, 1970
d) The number of minutes passed since 1st January, 1970
Answer: c
Explanation: The code shown above will return the number of seconds passed since 1st January, 1970.
4. What will be the output of the following Python code, if the time module has already been imported?
def num(m):
t1 = time.time()
for i in range(0,m):
print(i)
t2 = time.time()
print(str(t2-t1))

num(3)
a)
1
2
3
The time taken for the execution of the code
b)
3
The time taken for the execution of the code
c)
1
2
3
UTC time
d)
3
UTC time
Answer: a
Explanation: The code shown above will return the numbers 1, 2, 3, followed by the time taken in the execution of the code.
Output:
1
2
3
The time taken for the execution of the code

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


import time
time.asctime()
a) Current date only
b) UTC time
c) Current date and time
d) Current time only
Answer: c
Explanation: The function time.asctime(), present if the time module can be used to return the current date and time. It can also
accept a parameter and return the date and time in a particular format. However in the above code, since we have not passed
any parameters in the above code, the current date and time is returned.
6. What will be the output of the following Python code?
import time
t=(2010, 9, 20, 8, 15, 12, 6)
time.asctime(t)
a) ‘20 Sep 2010 8:15:12 Sun’
b) ‘2010 20 Sept 08:15:12 Sun’
c) ‘Sun Sept 20 8:15:12 2010’
d) Error
Answer: d
Explanation: The code shown above results in an error because this function accepts exactly 9 arguments (including day of the
year and DST), but only 7 are given. Hence an error is thrown.
7. What will be the output of the following Python code?
import time
t=(2010, 9, 20, 8, 45, 12, 6, 0, 0)
time.asctime(t)
a) ‘Sep 20 2010 08:45:12 Sun’
b) ‘Sun Sep 20 08:45:12 2010’
c) ’20 Sep 08:45:12 Sun 2010’
d) ‘2010 20 Sep 08:45:12 Sun’
Answer: b
Explanation: The code shown above returns the given date and time in a particular format. Hence the output of the code shown
above will be: ‘Sun Sep 20 08:45:12 2010’.
8. The sleep function (under the time module) is used to ___________
a) Pause the code for the specified number of seconds
b) Return the specified number of seconds, in terms of milliseconds
c) Stop the execution of the code
d) Return the output of the code had it been executed earlier by the specified number of seconds
Answer: a
Explanation: The sleep function (under the time module) is used to pause the code for the specified number of seconds. The
number of seconds is taken as an argument by this function.
9. What will be the output of the following Python code?
import time
for i in range(0,5):
print(i)
time.sleep(2)
a) After an interval of 2 seconds, the numbers 1, 2, 3, 4, 5 are printed all together
b) After an interval of 2 seconds, the numbers 0, 1, 2, 3, 4 are printed all together
c) Prints the numbers 1, 2, 3, 4, 5 at an interval of 2 seconds between each number
d) Prints the numbers 0, 1, 2, 3, 4 at an interval of 2 seconds between each number
Answer: d
Explanation: The output of the code shown above will be the numbers 0, 1, 2, 3, 4 at an interval of 2 seconds each.
10. What will be the output if we try to extract only the year from the following Python code? (time.struct_time(tm_year=2017,
tm_mon=6, tm_mday=25, tm_hour=18, tm_min=26, tm_sec=6, tm_wday=6, tm_yday=176, tm_isdst=0))
import time
t=time.localtime()
print(t)
a) t[1]
b) tm_year
c) t[0]
d) t_year
Answer: c
Explanation: To extract the year from the code shown above, we use the command t[0]. The command t[1] will return the month
number (6 in the above case). The commands tm_year and t_year will result in errors.
11. State whether true or false.
s = time.time()
t= time.time()
s == t
a) True
b) False
Answer: b
Explanation: The variables ‘s’ and ‘t’ will not be equal due to the slight difference in the time of their execution. Hence the output
of this code will be: False.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Decorators”.
1. What will be the output of the following Python code?
def mk(x):
def mk1():
print("Decorated")
x()
return mk1
def mk2():
print("Ordinary")
p = mk(mk2)
p()
a)
Decorated
Decorated
b)
Ordinary
Ordinary
c)
Ordinary
Decorated
d)
Decorated
Ordinary
Answer: d
Explanation: The code shown above first prints the word “Decorated” and then “ordinary”. Hence the output of this code is:
Decorated
Ordinary.

2. In the following Python code, which function is the decorator?


def mk(x):
def mk1():
print("Decorated")
x()
return mk1
def mk2():
print("Ordinary")
p = mk(mk2)
p()
a) p()
b) mk()
c) mk1()
d) mk2()
Answer: b
Explanation: In the code shown above, the function mk() is the decorator. The function which is getting decorated is mk2(). The
return function is given the name p().
3. The ______ symbol along with the name of the decorator function can be placed above the definition of the function to be
decorated works as an alternate way for decorating a function.
a) #
b) $
c) @
d) &
Answer: c
Explanation: The @ symbol along with the name of the decorator function can be placed above the definition of the function to be
decorated works as an alternate way for decorating a function.
4. What will be the output of the following Python code?
def ordi():
print("Ordinary")
ordi
ordi()
a)
Address
Ordinary
b)
Error
Address
c)
Ordinary
Ordinary
d)
Ordinary
Address
Answer: a
Explanation: The code shown above returns the address on the function ordi first, after which the word “Ordinary” is printed.
Hence the output of this code is:
Address
Ordinary.

5. The two snippets of the following Python codes are equivalent.


CODE 1
@f
def f1():
print(“Hello”)
CODE 2
def f1():
print(“Hello”)
f1 = f(f1)
a) True
b) False
Answer: a
Explanation: The @ symbol can be used as an alternate way to specify a function that needs to be decorated. The output of the
codes shown above is the same. Hence they are equivalent. Therefore this statement is true.
6. What will be the output of the following Python function?
def f(p, q):
return p%q
f(0, 2)
f(2, 0)
a)
0
0
b)
Zero Division Error
Zero Division Error
c)
0
Zero Division Error
d)
Zero Division Error
0
Answer: c
Explanation: The output of f(0, 2) is 0, since o%2 is equal to 0. The output of the f(2, 0) is a Zero Division Error. We can make
use of decorators in order to avoid this error.

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


def f(x):
def f1(a, b):
print("hello")
if b==0:
print("NO")
return
return f(a, b)
return f1
@f
def f(a, b):
return a%b
f(4,0)
a)
hello
NO
b)
hello
Zero Division Error
c) NO
d) hello
Answer: a
Explanation: In the code shown above, we have used a decorator in order to avoid the Zero Division Error. Hence the output of
this code is:
hello
NO
8. What will be the output of the following Python code?
def f(x):
def f1(*args, **kwargs):
print("*"* 5)
x(*args, **kwargs)
print("*"* 5)
return f1
def a(x):
def f1(*args, **kwargs):
print("%"* 5)
x(*args, **kwargs)
print("%"* 5)
return f1
@f
@a
def p(m):
print(m)
p("hello")
a)
*****
%%%%%
hello
%%%%%
*****
b) Error
c) *****%%%%%hello%%%%%*****
d) hello
Answer: a
Explanation: The code shown above uses multiple decorators. The output of this code is:
*****
%%%%%
hello
%%%%%
*****
9. The following python code can work with ____ parameters.
def f(x):
def f1(*args, **kwargs):
print("Sanfoundry")
return x(*args, **kwargs)
return f1
a) 2
b) 1
c) any number of
d) 0
Answer: c
Explanation: The code shown above shows a general decorator which can work with any number of arguments.
10. What will be the output of the following Python code?
def f(x):
def f1(*args, **kwargs):
print("*", 5)
x(*args, **kwargs)
print("*", 5)
return f1
@f
def p(m):
p(m)
print("hello")
a)
*****
hello
b)
*****
*****
hello
c) *****
d) hello
Answer: d
Explanation: In the code shown above, we have not passed any parameter to the function p. Hence the output of this code is:
hello.
11. A function with parameters cannot be decorated.
a) True
b) False
Answer: b
Explanation: Any function, irrespective of whether or not it has parameters can be decorated. Hence the statement is false.
12. Identify the decorator in the snippet of code shown below.
def sf():
pass
sf = mk(sf)
@f
def sf():
return
a) @f
b) f
c) sf()
d) mk
Answer: d
Explanation: In the code shown above, @sf is not a decorator but only a decorator line. The ‘@’ symbol represents the
application of a decorator. The decorator here is the function mk.
13. What will be the output of the following Python code?
class A:
@staticmethod
def a(x):
print(x)
A.a(100)
a) Error
b) Warning
c) 100
d) No output
Answer: c
Explanation: The code shown above demonstrates rebinding using a static method. This can be done with or without a
decorator. The output of this code will be 100.
14. What will be the output of the following Python code?
def d(f):
def n(*args):
return '$' + str(f(*args))
return n
@d
def p(a, t):
return a + a*t
print(p(100,0))
a) 100
b) $100
c) $0
d) 0
Answer: b
Explanation: In the code shown above, the decorator helps us to prefix the dollar sign along with the value. Since the second
argument is zero, the output of the code is: $100.
15. What will be the output of the following Python code?
def c(f):
def inner(*args, **kargs):
inner.co += 1
return f(*args, **kargs)
inner.co = 0
return inner
@c
def fnc():
pass
if __name__ == '__main__':
fnc()
fnc()
fnc()
print(fnc.co)
a) 4
b) 3
c) 0
d) 1
Answer: b
Explanation: The code shown above returns the number of times a given function has been called. Hence the output of this code
is: 3
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Dictionary – 2”.
1. Which of these about a dictionary is false?
a) The values of a dictionary can be accessed using keys
b) The keys of a dictionary can be accessed using values
c) Dictionaries aren’t ordered
d) Dictionaries are mutable
Answer: b
Explanation: The values of a dictionary can be accessed using keys but the keys of a dictionary can’t be accessed using values.
2. Which of the following is not a declaration of the dictionary?
a) {1: ‘A’, 2: ‘B’}
b) dict([[1,”A”],[2,”B”]])
c) {1,”A”,2”B”}
d) { }
Answer: c
Explanation: Option c is a set, not a dictionary.
3. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
for i,j in a.items():
print(i,j,end=" ")
a) 1 A 2 B 3 C
b) 1 2 3
c) A B C
d) 1:”A” 2:”B” 3:”C”
Answer: a
Explanation: In the above code, variables i and j iterate over the keys and values of the dictionary respectively.
4. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
print(a.get(1,4))
a) 1
b) A
c) 4
d) Invalid syntax for get method
Answer: b
Explanation: The get() method returns the value of the key if the key is present in the dictionary and the default value(second
parameter) if the key isn’t present in the dictionary.
5. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
print(a.get(5,4))
a) Error, invalid syntax
b) A
c) 5
d) 4
Answer: d
Explanation: The get() method returns the default value(second parameter) if the key isn’t present in the dictionary.
6. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
print(a.setdefault(3))
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
b) C
c) {1: 3, 2: 3, 3: 3}
d) No method called setdefault() exists for dictionary
Answer: b
Explanation: setdefault() is similar to get() but will set dict[key]=default if key is not already in the dictionary.
7. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
a.setdefault(4,"D")
print(a)
a) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’}
b) None
c) Error
d) [1,3,6,10]
Answer: a
Explanation: setdefault() will set dict[key]=default if key is not already in the dictionary.
8. What will be the output of the following Python code?
a={1:"A",2:"B",3:"C"}
b={4:"D",5:"E"}
a.update(b)
print(a)
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
b) Method update() doesn’t exist for dictionaries
c) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’, 5: ‘E’}
d) {4: ‘D’, 5: ‘E’}
Answer: c
Explanation: update() method adds dictionary b’s key-value pairs to dictionary a. Execute in python shell to verify.
9. What will be the output of the following Python code?
a={1:"A",2:"B",3:"C"}
b=a.copy()
b[2]="D"
print(a)
a) Error, copy() method doesn’t exist for dictionaries
b) {1: ‘A’, 2: ‘B’, 3: ‘C’}
c) {1: ‘A’, 2: ‘D’, 3: ‘C’}
d) “None” is printed
Answer: b
Explanation: Changes made in the copy of the dictionary isn’t reflected in the original one.
10. What will be the output of the following Python code?
a={1:"A",2:"B",3:"C"}
a.clear()
print(a)
a) None
b) { None:None, None:None, None:None}
c) {1:None, 2:None, 3:None}
d) { }
Answer: d
Explanation: The clear() method clears all the key-value pairs in the dictionary.
11. Which of the following isn’t true about dictionary keys?
a) More than one key isn’t allowed
b) Keys must be immutable
c) Keys must be integers
d) When duplicate keys encountered, the last assignment wins
Answer: c
Explanation: Keys of a dictionary may be any data type that is immutable.
12. What will be the output of the following Python code?
a={1:5,2:3,3:4}
a.pop(3)
print(a)
a) {1: 5}
b) {1: 5, 2: 3}
c) Error, syntax error for pop() method
d) {1: 5, 3: 4}
Answer: b
Explanation: pop() method removes the key-value pair for the key mentioned in the pop() method.
13. What will be the output of the following Python code?
a={1:5,2:3,3:4}
print(a.pop(4,9))
a) 9
b) 3
c) Too many arguments for pop() method
d) 4
Answer: a
Explanation: pop() method returns the value when the key is passed as an argument and otherwise returns the default
value(second argument) if the key isn’t present in the dictionary.
14. What will be the output of the following Python code?
a={1:"A",2:"B",3:"C"}
for i in a:
print(i,end=" ")
a) 1 2 3
b) ‘A’ ‘B’ ‘C’
c) 1 ‘A’ 2 ‘B’ 3 ‘C’
d) Error, it should be: for i in a.items():
Answer: a
Explanation: The variable i iterates over the keys of the dictionary and hence the keys are printed.
15. What will be the output of the following Python code?
>>> a={1:"A",2:"B",3:"C"}
>>> a.items()
a) Syntax error
b) dict_items([(‘A’), (‘B’), (‘C’)])
c) dict_items([(1,2,3)])
d) dict_items([(1, ‘A’), (2, ‘B’), (3, ‘C’)])
Answer: d
Explanation: The method items() returns list of tuples with each tuple having a key-value pair.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Dictionary – 3”.
1. Which of the statements about dictionary values if false?
a) More than one key can have the same value
b) The values of the dictionary can be accessed as dict[key]
c) Values of a dictionary must be unique
d) Values of a dictionary can be a mixture of letters and numbers
Answer: c
Explanation: More than one key can have the same value.
2. What will be the output of the following Python code snippet?
>>> a={1:"A",2:"B",3:"C"}
>>> del a
a) method del doesn’t exist for the dictionary
b) del deletes the values in the dictionary
c) del deletes the entire dictionary
d) del deletes the keys in the dictionary
Answer: c
Explanation: del deletes the entire dictionary and any further attempt to access it will throw an error.
3. If a is a dictionary with some key-value pairs, what does a.popitem() do?
a) Removes an arbitrary element
b) Removes all the key-value pairs
c) Removes the key-value pair for the key given as an argument
d) Invalid method for dictionary
Answer: a
Explanation: The method popitem() removes a random key-value pair.
4. What will be the output of the following Python code snippet?
total={}
def insert(items):
if items in total:
total[items] += 1
else:
total[items] = 1
insert('Apple')
insert('Ball')
insert('Apple')
print (len(total))
a) 3
b) 1
c) 2
d) 0
Answer: c
Explanation: The insert() function counts the number of occurrences of the item being inserted into the dictionary. There are only
2 keys present since the key ‘Apple’ is repeated. Thus, the length of the dictionary is 2.
5. What will be the output of the following Python code snippet?
a = {}
a[1] = 1
a['1'] = 2
a[1]=a[1]+1
count = 0
for i in a:
count += a[i]
print(count)
a) 1
b) 2
c) 4
d) Error, the keys can’t be a mixture of letters and numbers
Answer: c
Explanation: The above piece of code basically finds the sum of the values of keys.
6. What will be the output of the following Python code snippet?
numbers = {}
letters = {}
comb = {}
numbers[1] = 56
numbers[3] = 7
letters[4] = 'B'
comb['Numbers'] = numbers
comb['Letters'] = letters
print(comb)
a) Error, dictionary in a dictionary can’t exist
b) ‘Numbers’: {1: 56, 3: 7}
c) {‘Numbers’: {1: 56}, ‘Letters’: {4: ‘B’}}
d) {‘Numbers’: {1: 56, 3: 7}, ‘Letters’: {4: ‘B’}}
Answer: d
Explanation: Dictionary in a dictionary can exist.
7. What will be the output of the following Python code snippet?
test = {1:'A', 2:'B', 3:'C'}
test = {}
print(len(test))
a) 0
b) None
c) 3
d) An exception is thrown
Answer: a
Explanation: In the second line of code, the dictionary becomes an empty dictionary. Thus, length=0.
8. What will be the output of the following Python code snippet?
test = {1:'A', 2:'B', 3:'C'}
del test[1]
test[1] = 'D'
del test[2]
print(len(test))
a) 0
b) 2
c) Error as the key-value pair of 1:’A’ is already deleted
d) 1
Answer: b
Explanation: After the key-value pair of 1:’A’ is deleted, the key-value pair of 1:’D’ is added.
9. What will be the output of the following Python code snippet?
a = {}
a[1] = 1
a['1'] = 2
a[1.0]=4
count = 0
for i in a:
count += a[i]
print(count)
a) An exception is thrown
b) 3
c) 6
d) 2
Answer: c
Explanation: The value of key 1 is 4 since 1 and 1.0 are the same. Then, the function count() gives the sum of all the values of the
keys (2+4).
10. What will be the output of the following Python code snippet?
a={}
a['a']=1
a['b']=[2,3,4]
print(a)
a) Exception is thrown
b) {‘b’: [2], ‘a’: 1}
c) {‘b’: [2], ‘a’: [3]}
d) {‘b’: [2, 3, 4], ‘a’: 1}
Answer: d
Explanation: Mutable members can be used as the values of the dictionary but they cannot be used as the keys of the dictionary.
11. What will be the output of the following Python code snippet?
>>>import collections
>>> a=collections.Counter([1,1,2,3,3,4,4,4])
>>> a
a) {1,2,3,4}
b) Counter({4, 1, 3, 2})
c) Counter({4: 3, 1: 2, 3: 2, 2: 1})
d) {4: 3, 1: 2, 3: 2, 2: 1}
Answer: c
Explanation: The statement a=collections.OrderedDict() generates a dictionary with the number as the key and the count of
times the number appears as the value.
12. What will be the output of the following Python code snippet?
>>>import collections
>>> b=collections.Counter([2,2,3,4,4,4])
>>> b.most_common(1)
a) Counter({4: 3, 2: 2, 3: 1})
b) {3:1}
c) {4:3}
d) [(4, 3)]
Answer: d
Explanation: The most_common() method returns the n number key-value pairs where the value is the most recurring.
13. What will be the output of the following Python code snippet?
>>>import collections
>>> b=collections.Counter([2,2,3,4,4,4])
>>> b.most_common(1)
a) Counter({4: 3, 2: 2, 3: 1})
b) {3:1}
c) {4:3}
d) [(4, 3)]
Answer: d
Explanation: The most_common() method returns the n number key-value pairs where the value is the most recurring.
14. What will be the output of the following Python code snippet?
>>> import collections
>>> a=collections.Counter([2,2,3,3,3,4])
>>> b=collections.Counter([2,2,3,4,4])
>>> a|b
a) Counter({3: 3, 2: 2, 4: 2})
b) Counter({2: 2, 3: 1, 4: 1})
c) Counter({3: 2})
d) Counter({4: 1})
Answer: a
Explanation: a|b returns the pair of keys and the highest recurring value.
15. What will be the output of the following Python code snippet?
>>> import collections
>>> a=collections.Counter([3,3,4,5])
>>> b=collections.Counter([3,4,4,5,5,5])
>>> a&b
a) Counter({3: 12, 4: 1, 5: 1})
b) Counter({3: 1, 4: 1, 5: 1})
c) Counter({4: 2})
d) Counter({5: 1})
Answer: b
Explanation: a&b returns the pair of keys and the lowest recurring value.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Dictionary – 4”.
1. The following Python code is invalid.
class demo(dict):
def __test__(self,key):
return []
a = demo()
a['test'] = 7
print(a)
a) True
b) False
Answer: b
Explanation: The output of the code is: {‘test’:7}.
2. What will be the output of the following Python code?
count={}
count[(1,2,4)] = 5
count[(4,2,1)] = 7
count[(1,2)] = 6
count[(4,2,1)] = 2
tot = 0
for i in count:
tot=tot+count[i]
print(len(count)+tot)
a) 25
b) 17
c) 16
d) Tuples can’t be made keys of a dictionary
Answer: c
Explanation: Tuples can be made keys of a dictionary. Length of the dictionary is 3 as the value of the key (4,2,1) is modified to
2. The value of the variable tot is 5+6+2=13.
3. What will be the output of the following Python code?
a={}
a[2]=1
a[1]=[2,3,4]
print(a[1][1])
a) [2,3,4]
b) 3
c) 2
d) An exception is thrown
Answer: b
Explanation: Now, a={1:[2,3,4],2:1} . a[1][1] refers to second element having key 1.
4. What will be the output of the following Python code?
>>> a={'B':5,'A':9,'C':7}
>>> sorted(a)
a) [‘A’,’B’,’C’]
b) [‘B’,’C’,’A’]
c) [5,7,9]
d) [9,5,7]
Answer: a
Explanation: Return a new sorted list of keys in the dictionary.
5. What will be the output of the following Python code?
>>> a={i: i*i for i in range(6)}
>>> a
a) Dictionary comprehension doesn’t exist
b) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36}
c) {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25}
d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Answer: d
Explanation: Dictionary comprehension is implemented in the above piece of code.
6. What will be the output of the following Python code?
>>> a={}
>>> a.fromkeys([1,2,3],"check")
a) Syntax error
b) {1:”check”,2:”check”,3:”check”}
c) “check”
d) {1:None,2:None,3:None}
Answer: b
Explanation: The dictionary takes values of keys from the list and initializes it to the default value (value given in the second
parameter). Execute in Python shell to verify.
7. What will be the output of the following Python code?
>>> b={}
>>> all(b)
a) { }
b) False
c) True
d) An exception is thrown
Answer: c
Explanation: Function all() returns True if all keys of the dictionary are true or if the dictionary is empty.
8. If b is a dictionary, what does any(b) do?
a) Returns True if any key of the dictionary is true
b) Returns False if dictionary is empty
c) Returns True if all keys of the dictionary are true
d) Method any() doesn’t exist for dictionary
Answer: a
Explanation: Method any() returns True if any key of the dictionary is true and False if the dictionary is empty.
9. What will be the output of the following Python code?
>>> a={"a":1,"b":2,"c":3}
>>> b=dict(zip(a.values(),a.keys()))
>>> b
a) {‘a’: 1, ‘b’: 2, ‘c’: 3}
b) An exception is thrown
c) {‘a’: ‘b’: ‘c’: }
d) {1: ‘a’, 2: ‘b’, 3: ‘c’}
Answer: d
Explanation: The above piece of code inverts the key-value pairs in the dictionary.
10. What will be the output of the following Python code?
>>> a={i: 'A' + str(i) for i in range(5)}
>>> a
a) An exception is thrown
b) {0: ‘A0’, 1: ‘A1’, 2: ‘A2’, 3: ‘A3’, 4: ‘A4’}
c) {0: ‘A’, 1: ‘A’, 2: ‘A’, 3: ‘A’, 4: ‘A’}
d) {0: ‘0’, 1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’}
Answer: b
Explanation: Dictionary comprehension and string concatenation is implemented in the above piece of code.
11. What will be the output of the following Python code?
>>> a=dict()
>>> a[1]
a) An exception is thrown since the dictionary is empty
b) ‘ ‘
c) 1
d) 0
Answer: a
Explanation: The values of a dictionary can be accessed through the keys only if the keys exist in the dictionary.
12. What will be the output of the following Python code?
>>> import collections
>>> a=dict()
>>> a=collections.defaultdict(int)
>>> a[1]
a) 1
b) 0
c) An exception is thrown
d) ‘ ‘
Answer: b
Explanation: The statement a=collections.defaultdict(int) gives the default value of 0
(since int data type is given within the parenthesis) even if the keys don’t exist in the dictionary.
13. What will be the output of the following Python code?
>>> import collections
>>> a=dict()
>>> a=collections.defaultdict(str)
>>> a['A']
a) An exception is thrown since the dictionary is empty
b) ‘ ‘
c) ‘A’
d) 0
Answer: b
Explanation: The statement a=collections.defaultdict(str) gives the default value of ‘ ‘ even if the keys don’t exist in the dictionary.
14. What will be the output of the following Python code?
>>> import collections
>>> b=dict()
>>> b=collections.defaultdict(lambda: 7)
>>> b[4]
a) 4
b) 0
c) An exception is thrown
d) 7
Answer: d
Explanation: The statement a=collections.defaultdict(lambda: x) gives the default value of x even if the keys don’t exist in the
dictionary.
15. What will be the output of the following Python code?
>>> import collections
>>> a=collections.OrderedDict((str(x),x) for x in range(3))
>>> a
a) {‘2’:2, ‘0’:0, ‘1’:1}
b) OrderedDict([(‘0’, 0), (‘1’, 1), (‘2’, 2)])
c) An exception is thrown
d) ‘ ‘
Answer: b
Explanation: The line of code a=collections.OrderedDict() generates a dictionary satisfying the conditions given within the
parenthesis and in an ascending order of the keys.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Encapsulation”.
1. Which of these is not a fundamental features of OOP?
a) Encapsulation
b) Inheritance
c) Instantiation
d) Polymorphism
Answer: c
Explanation: Instantiation simply refers to creation of an instance of class. It is not a fundamental feature of OOP.
2. Which of the following is the most suitable definition for encapsulation?
a) Ability of a class to derive members of another class as a part of its own definition
b) Means of bundling instance variables and methods in order to restrict access to certain class members
c) Focuses on variables and passing of variables to functions
d) Allows for implementation of elegant software that is well designed and easily modified
Answer: b
Explanation: The values assigned by the constructor to the class members is used to create the object.
3. What will be the output of the following Python code?
class Demo:
def __init__(self):
self.a = 1
self.__b = 1

def display(self):
return self.__b
obj = Demo()
print(obj.a)
a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a private member
c) The program runs fine and 1 is printed
d) The program has an error as you can’t name a class member using __b
Answer: c
Explanation: The program has no error because the class member which is public is printed. 1 is displayed. Execute in python
shell to verify.
4. What will be the output of the following Python code?
class Demo:
def __init__(self):
self.a = 1
self.__b = 1

def display(self):
return self.__b

obj = Demo()
print(obj.__b)
a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a private member
c) The program has an error because b is private and hence can’t be printed
d) The program runs fine and 1 is printed
Answer: c
Explanation: Variables beginning with two underscores are said to be private members of the class and they can’t be accessed
directly.
5. Methods of a class that provide access to private members of the class are called as ______ and ______
a) getters/setters
b) __repr__/__str__
c) user-defined functions/in-built functions
d) __init__/__del__
Answer: a
Explanation: The purpose of getters and setters is to get(return) and set(assign) private instance variables of a class.
6. Which of these is a private data field?
def Demo:
def __init__(self):
__a = 1
self.__b = 1
self.__c__ = 1
__d__= 1
a) __a
b) __b
c) __c__
d) __d__
Answer: b
Explanation: Variables such as self.__b are private members of the class.
7. What will be the output of the following Python code?
class Demo:
def __init__(self):
self.a = 1
self.__b = 1

def get(self):
return self.__b

obj = Demo()
print(obj.get())
a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a private member
c) The program has an error because b is private and hence can’t be printed
d) The program runs fine and 1 is printed
Answer: d
Explanation: Here, get(self) is a member of the class. Hence, it can even return a private member of the class. Because of this
reason, the program runs fine and 1 is printed.
8. What will be the output of the following Python code?
class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def get(self):
return self.__b
obj = Demo()
obj.a=45
print(obj.a)
a) The program runs properly and prints 45
b) The program has an error because the value of members of a class can’t be changed from outside the class
c) The program runs properly and prints 1
d) The program has an error because the value of members outside a class can only be changed as self.a=45
Answer: a
Explanation: It is possible to change the values of public class members using the object of the class.
9. Private members of a class cannot be accessed.
a) True
b) False
Answer: b
Explanation: Private members of a class are accessible if written as follows: obj._Classname__privatemember. Such renaming
of identifiers is called as name mangling.
10. The purpose of name mangling is to avoid unintentional access of private class members.
a) True
b) False
Answer: a
Explanation: Name mangling prevents unintentional access of private members of a class, while still allowing access when
needed. Unless the variable is accessed with its mangled name, it will not be found.
11. What will be the output of the following Python code?
class fruits:
def __init__(self):
self.price = 100
self.__bags = 5
def display(self):
print(self.__bags)
obj=fruits()
obj.display()
a) The program has an error because display() is trying to print a private class member
b) The program runs fine but nothing is printed
c) The program runs fine and 5 is printed
d) The program has an error because display() can’t be accessed
Answer: c
Explanation: Private class members can be printed by methods which are members of the class.
12. What will be the output of the following Python code?
class student:
def __init__(self):
self.marks = 97
self.__cgpa = 8.7
def display(self):
print(self.marks)
obj=student()
print(obj._student__cgpa)
a) The program runs fine and 8.7 is printed
b) Error because private class members can’t be accessed
c) Error because the proper syntax for name mangling hasn’t been implemented
d) The program runs fine but nothing is printed
Answer: a
Explanation: Name mangling has been properly implemented in the code given above and hence the program runs properly.
13. Which of the following is false about protected class members?
a) They begin with one underscore
b) They can be accessed by subclasses
c) They can be accessed by name mangling method
d) They can be accessed within a class
Answer: c
Explanation: Protected class members can’t be accessed by name mangling.
14. What will be the output of the following Python code?
class objects:
def __init__(self):
self.colour = None
self._shape = "Circle"

def display(self, s):


self._shape = s
obj=objects()
print(obj._objects_shape)
a) The program runs fine because name mangling has been properly implemented
b) Error because the member shape is a protected member
c) Error because the proper syntax for name mangling hasn’t been implemented
d) Error because the member shape is a private member
Answer: b
Explanation: Protected members begin with one underscore and they can only be accessed within a class or by subclasses.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Exception Handling – 2”.
1. The following Python code will result in an error if the input value is entered as -5.
assert False, 'Spanish'
a) True
b) False
Answer: a
Explanation: The code shown above results in an assertion error. The output of the code is:
Traceback (most recent call last):
File “<pyshell#0>”, line 1, in <module>
assert False, ‘Spanish’
AssertionError: Spanish
Hence, this statement is true.
2. What will be the output of the following Python code?
x=10
y=8
assert x>y, 'X too small'
a) Assertion Error
b) 10 8
c) No output
d) 108
Answer: c
Explanation: The code shown above results in an error if and only if x<y. However, in the above case, since x>y, there is no error.
Since there is no print statement, hence there is no output.
3. What will be the output of the following Python code?
#generator
def f(x):
yield x+1
g=f(8)
print(next(g))
a) 8
b) 9
c) 7
d) Error
Answer: b
Explanation: The code shown above returns the value of the expression x+1, since we have used to keyword yield. The value of x
is 8. Hence the output of the code is 9.
4. What will be the output of the following Python code?
def f(x):
yield x+1
print("test")
yield x+2
g=f(9)
a) Error
b) test
c)
test
10
12
d) No output
Answer: d
Explanation: The code shown above will not yield any output. This is because when we try to yield 9, and there is no next(g), the
iteration stops. Hence there is no output.
5. What will be the output of the following Python code?
def f(x):
yield x+1
print("test")
yield x+2
g=f(10)
print(next(g))
print(next(g))
a) No output
b)
11
test
12
c)
11
test
d) 11
Answer: b
Explanation: The code shown above results in the output:
11
test
12
This is because we have used next(g) twice. Had we not used next, there would be no output.
6. What will be the output of the following Python code?
def a():
try:
f(x, 4)
finally:
print('after f')
print('after f?')
a()
a) No output
b) after f?
c) error
d) after f
Answer: c
Explanation: This code shown above will result in an error simply because ‘f’ is not defined. ‘try’ and ‘finally’ are keywords used in
exception handling.
7. What will be the output of the following Python code?
def f(x):
for i in range(5):
yield i
g=f(8)
print(list(g))
a) [0, 1, 2, 3, 4]
b) [1, 2, 3, 4, 5, 6, 7, 8]
c) [1, 2, 3, 4, 5]
d) [0, 1, 2, 3, 4, 5, 6, 7]
Answer: a
Explanation: The output of the code shown above is a list containing whole numbers in the range (5). Hence the output of this
code is: [0, 1, 2, 3, 4].
8. The error displayed in the following Python code is?
import itertools
l1=(1, 2, 3)
l2=[4, 5, 6]
l=itertools.chain(l1, l2)
print(next(l1))
a) ‘list’ object is not iterator
b) ‘tuple’ object is not iterator
c) ‘list’ object is iterator
d) ‘tuple’ object is iterator
Answer: b
Explanation: The error raised in the code shown above is that: ‘tuple’ object is not iterator. Had we given l2 as argument to next,
the error would have been: ‘list’ object is not iterator.
9. Which of the following is not an exception handling keyword in Python?
a) try
b) except
c) accept
d) finally
Answer: c
Explanation: The keywords ‘try’, ‘except’ and ‘finally’ are exception handling keywords in python whereas the word ‘accept’ is not
a keyword at all.
10. What will be the output of the following Python code?
g = (i for i in range(5))
type(g)
a) class <’loop’>
b) class <‘iteration’>
c) class <’range’>
d) class <’generator’>
Answer: d
Explanation: Another way of creating a generator is to use parenthesis. Hence the output of the code shown above is:
class<’generator’>.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Exception Handling – 3”.
1. 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
Answer: a
Explanation: In the code shown above, if the input file in not found, then the statement: “Input file not found” is printed on the
screen. The user is then prompted to reenter the file name. Error is not thrown.
2. What will be the output of the following Python code?
lst = [1, 2, 3]
lst[3]
a) NameError
b) ValueError
c) IndexError
d) TypeError
Answer: c
Explanation: The snippet of code shown above throws an index error. This is because the index of the list given in the code, that
is, 3 is out of range. The maximum index of this list is 2.
3. What will be the output of the following Python code?
t[5]
a) IndexError
b) NameError
c) TypeError
d) ValeError
Answer: b
Explanation: The expression shown above results in a name error. This is because the name ‘t’ is not defined.
4. 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
Answer: d
Explanation: The line of code shown above will result in a type error. This is because the operand ‘+’ is not supported when we
combine the data types ‘int’ and ‘str’. Sine this is exactly what we have done in the code shown above, a type error is thrown.
5. What will be the output of the following Python code?
int('65.43')
a) ImportError
b) ValueError
c) TypeError
d) NameError
Answer: b
Explanation: The snippet of code shown above results in a value error. This is because there is an invalid literal for int() with base
10: ’65.43’.
6. 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(math.factorial(num))

CODE 2
num=int(input("Enter a number of whose factorial you want to find"))
print(math.factorial(num))
a) ValueError, NameError
b) AttributeError, ValueError
c) NameError, TypeError
d) TypeError, ValueError
Answer: a
Explanation: The first code results in a ValueError. This is because when we enter the input as -6, we are trying to find the
factorial of a negative number, which is not possible. The second code results in a NameError. This is because we have not
imported the math module. Hence the name ‘math’ is undefined.
7. 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”)
Answer: c
Explanation: In the code shown above, since the value passed as an argument to the function is between 1 and 12 (both
included), hence the output is the value itself, that is 6. If the value had been above 12 and less than 1, a ValueError would have
been thrown.
8. What will be the output of the following Python code if the input entered is 6?
valid = False
while not valid:
try:
n=int(input("Enter a number"))
while n%2==0:
print("Bye")
valid = True
except ValueError:
print("Invalid")
a) Bye (printed once)
b) No output
c) Invalid (printed once)
d) Bye (printed infinite number of times)
Answer: d
Explanation: The code shown above results in the word “Bye” being printed infinite number of times. This is because an even
number has been given as input. If an odd number had been given as input, then there would have been no output.
9. 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
Answer: b
Explanation: The first code shows an error detected during execution. This might occur occasionally. The second line of code
represents a syntax error. When there is deviation from the rules of a language, a syntax error is thrown.
10. Which of the following statements is true?
a) The standard exceptions are automatically imported into Python programs
b) All raised standard exceptions must be handled in Python
c) When there is a deviation from the rules of a programming language, a semantic error is thrown
d) If any exception is thrown in try block, else block is executed
Answer: a
Explanation: When any exception is thrown in try block, except block is executed. If exception in not thrown in try block, else block
is executed. When there is a deviation from the rules of a programming language, a syntax error is thrown. The only true
statement above is: The standard exceptions are automatically imported into Python programs.
11. Which of the following is not a standard exception in Python?
a) NameError
b) IOError
c) AssignmentError
d) ValueError
Answer: c
Explanation: NameError, IOError and ValueError are standard exceptions in Python whereas Assignment error is not a standard
exception in Python.
12. Syntax errors are also known as parsing errors.
a) True
b) False
Answer: a
Explanation: Syntax errors are known as parsing errors. Syntax errors are raised when there is a deviation from the rules of a
language. Hence the statement is true.
13. An exception is ____________
a) an object
b) a special function
c) a standard module
d) a module
Answer: a
Explanation: An exception is an object that is raised by a function signaling that an unexpected situation has occurred, that the
function itself cannot handle.
14. _______________________ exceptions are raised as a result of an error in opening a particular file.
a) ValueError
b) TypeError
c) ImportError
d) IOError
Answer: d
Explanation: IOError exceptions are raised as a result of an error in opening or closing a particular file.
15. Which of the following blocks will be executed whether an exception is thrown or not?
a) except
b) else
c) finally
d) assert
Answer: c
Explanation: The statements in the finally block will always be executed, whether an exception is thrown or not. This clause is
used to close the resources used in a code.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Exception Handling – 1”.
1. How many except statements can a try-except block have?
a) zero
b) one
c) more than one
d) more than zero
Answer: d
Explanation: There has to be at least one except statement.
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
Answer: c
Explanation: The else part is executed when no exception occurs.
3. Is the following Python code valid?
try:
# Do something
except:
# Do something
finally:
# Do something
a) no, there is no such thing as finally
b) no, finally cannot be used with except
c) no, finally must come before except
d) yes
Answer: b
Explanation: Refer documentation.
4. Is the following Python code valid?
try:
# Do something
except:
# Do something
else:
# Do something
a) no, there is no such thing as else
b) no, else cannot be used with except
c) no, else must come before except
d) yes
Answer: d
Explanation: Refer documentation.
5. Can one block of except statements handle multiple exception?
a) yes, like except TypeError, SyntaxError [,…]
b) yes, like except [TypeError, SyntaxError]
c) no
d) none of the mentioned
Answer: a
Explanation: Each type of exception can be specified directly. There is no need to put it in a list.
6. 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
Answer: d
Explanation: The finally block is always executed.
7. What will be the output of the following Python code?
def foo():
try:
return 1
finally:
return 2
k = foo()
print(k)
a) 1
b) 2
c) 3
d) error, there is more than one return statement in a single try-finally block
Answer: b
Explanation: The finally block is executed even there is a return statement in the try block.
8. What will be the output of the following Python code?
def foo():
try:
print(1)
finally:
print(2)
foo()
a) 1 2
b) 1
c) 2
d) none of the mentioned
Answer: a
Explanation: No error occurs in the try block so 1 is printed. Then the finally block is executed and 2 is printed.
9. 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
Answer: c
Explanation: A new exception class must inherit from a BaseException. There is no such inheritance here.
10. What happens when ‘1’ == 1 is executed?
a) we get a True
b) we get a False
c) an TypeError occurs
d) a ValueError occurs
Answer: b
Explanation: It simply evaluates to False and does not raise any exception.
This set of Python Questions and Answers for Experienced people focuses on “While and For Loops”.
1. What will be the output of the following Python code?
for i in range(2.0):
print(i)
a) 0.0 1.0
b) 0 1
c) error
d) none of the mentioned
Answer: c
Explanation: Object of type float cannot be interpreted as an integer.
2. What will be the output of the following Python code?
for i in range(int(2.0)):
print(i)
a) 0.0 1.0
b) 0 1
c) error
d) none of the mentioned
Answer: b
Explanation: range(int(2.0)) is the same as range(2).
3. What will be the output of the following Python code?
for i in range(float('inf')):
print (i)
a) 0.0 0.1 0.2 0.3 …
b) 0 1 2 3 …
c) 0.0 1.0 2.0 3.0 …
d) none of the mentioned
Answer: d
Explanation: Error, objects of type float cannot be interpreted as an integer.
4. What will be the output of the following Python code?
for i in range(int(float('inf'))):
print (i)
a) 0.0 0.1 0.2 0.3 …
b) 0 1 2 3 …
c) 0.0 1.0 2.0 3.0 …
d) none of the mentioned
Answer: d
Explanation: OverflowError, cannot convert float infinity to integer.
5. What will be the output of the following Python code snippet?
for i in [1, 2, 3, 4][::-1]:
print (i)
a) 1 2 3 4
b) 4 3 2 1
c) error
d) none of the mentioned
Answer: b
Explanation: [::-1] reverses the list.
6. What will be the output of the following Python code snippet?
for i in ''.join(reversed(list('abcd'))):
print (i)
a) a b c d
b) d c b a
c) error
d) none of the mentioned
Answer: b
Explanation: ‘ ‘.join(reversed(list(‘abcd’))) reverses a string.
7. What will be the output of the following Python code snippet?
for i in 'abcd'[::-1]:
print (i)
a) a b c d
b) d c b a
c) error
d) none of the mentioned
Answer: b
Explanation: [::-1] reverses the string.
8. What will be the output of the following Python code snippet?
for i in '':
print (i)
a) None
b) (nothing is printed)
c) error
d) none of the mentioned
Answer: b
Explanation: The string does not have any character to loop over.
9. What will be the output of the following Python code snippet?
x=2
for i in range(x):
x += 1
print (x)
a) 0 1 2 3 4 …
b) 0 1
c) 3 4
d) 0 1 2 3
Answer: c
Explanation: Variable x is incremented and printed twice.
10. What will be the output of the following Python code snippet?
x=2
for i in range(x):
x -= 2
print (x)
a) 0 1 2 3 4 …
b) 0 -2
c) 0
d) error
Answer: b
Explanation: The loop is entered twice.
To practice all questions on Python for experienced people, .
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Formatting – 1”.
1. What will be the output of the following Python code snippet?
X=”hi”
print(“05d”%X)
a) 00000hi
b) 000hi
c) hi000
d) error
Answer: d
Explanation: The code snippet shown above results in an error because the above formatting option works only if ‘X’ is a
number. Since in the above case ‘X’ is a string, an error is thrown.
2. What will be the output of the following Python code snippet?
X=”san-foundry”
print(“%56s”,X)
a) 56 blank spaces before san-foundry
b) 56 blank spaces before san and foundry
c) 56 blank spaces after san-foundry
d) no change
Answer: a
Explanation: The formatting option print(“%Ns”,X) helps us add ‘N’ number of spaces before a given string ‘X’. Hence the output
for the code snippet shown above will be 56 blank spaces before the string “san-foundry”.
3. What will be the output of the following Python expression if x=456?
print("%-06d"%x)
a) 000456
b) 456000
c) 456
d) error
Answer: c
Explanation: The expression shown above results in the output 456.
4. What will be the output of the following Python expression if X=345?
print(“%06d”%X)
a) 345000
b) 000345
c) 000000345
d) 345000000
Answer: b
Explanation: The above expression returns the output 000345. It adds the required number of zeroes before the given number in
order to make the number of digits 6 (as specified in this case).
5. Which of the following formatting options can be used in order to add ‘n’ blank spaces after a given string ‘S’?
a) print(“-ns”%S)
b) print(“-ns”%S)
c) print(“%ns”%S)
d) print(“%-ns”%S)
Answer: d
Explanation: In order to add ‘n’ blank spaces after a given string ‘S’, we use the formatting option:(“%-ns”%S).
6. What will be the output of the following Python expression if X = -122?
print("-%06d"%x)
a) -000122
b) 000122
c) –00122
d) -00122
Answer: c
Explanation: The given number is -122. Here the total number of digits (including the negative sign) should be 6 according to the
expression. In addition to this, there is a negative sign in the given expression. Hence the output will be – -00122.
7. What will be the output of the following Python expression if the value of x is 34?
print(“%f”%x)
a) 34.00
b) 34.0000
c) 34.000000
d) 34.00000000
Answer: c
Explanation: The expression shown above normally returns the value with 6 decimal points if it is not specified with any number.
Hence the output of this expression will be: 34.000000 (6 decimal points).
8. What will be the output of the following Python expression if x=56.236?
print("%.2f"%x)
a) 56.00
b) 56.24
c) 56.23
d) 0056.236
Answer: b
Explanation: The expression shown above rounds off the given number to the number of decimal places specified. Since the
expression given specifies rounding off to two decimal places, the output of this expression will be 56.24. Had the value been
x=56.234 (last digit being any number less than 5), the output would have been 56.23.
9. What will be the output of the following Python expression if x=22.19?
print("%5.2f"%x)
a) 22.1900
b) 22.00000
c) 22.19
d) 22.20
Answer: c
Explanation: The output of the expression above will be 22.19. This expression specifies that the total number of digits (including
the decimal point) should be 5, rounded off to two decimal places.
10. The expression shown below results in an error.
print("-%5d0",989)
a) True
b) False
Answer: b
Explanation: The expression shown above does not result in an error. The output of this expression is -%5d0 989. Hence this
statement is incorrect.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Formatting – 2”.
1. What will be the output of the following Python code snippet?
'%d %s %g you' %(1, 'hello', 4.0)
a) Error
b) 1 hello you 4.0
c) 1 hello 4 you
d) 1 4 hello you
Answer: c
Explanation: In the snippet of code shown above, three values are inserted into the target string. When we insert more than one
value, we should group the values on the right in a tuple. The % formatting expression operator expects either a single item or a
tuple of one or more items on its right side.
2. The output of which of the codes shown below will be: “There are 4 blue birds.”?
a) ‘There are %g %d birds.’ %4 %blue
b) ‘There are %d %s birds.’ %(4, blue)
c) ‘There are %s %d birds.’ %[4, blue]
d) ‘There are %d %s birds.’ 4, blue
Answer: b
Explanation: The code ‘There are %d %s birds.’ %(4, blue) results in the output: There are 4 blue birds. When we insert more
than one value, we should group the values on the right in a tuple.
3. What will be the output of the python code shown below for various styles of format specifiers?
x=1234
res='integers:...%d...%-6d...%06d' %(x, x, x)
res
a) ‘integers:…1234…1234 …001234’
b) ‘integers…1234…1234…123400’
c) ‘integers:… 1234…1234…001234’
d) ‘integers:…1234…1234…001234’
Answer: a
Explanation: The code shown above prints 1234 for the format specified %d, ‘1234 ’ for the format specifier %-6d (minus ‘-‘
sign signifies left justification), and 001234 for the format specifier %06d. Hence the output of this code is: ‘integers:…1234…
1234 …001234’
4. What will be the output of the following Python code snippet?
x=3.3456789
'%f | %e | %g' %(x, x, x)
a) Error
b) ‘3.3456789 | 3.3456789+00 | 3.345678’
c) ‘3.345678 | 3.345678e+0 | 3.345678’
d) ‘3.345679 | 3.345679e+00 | 3.34568’
Answer: d
Explanation: The %f %e and %g format specifiers represent floating point numbers in different ways. %e and %E are the same,
except that the exponent is in lowercase. %g chooses the format by number content. Hence the output of this code is: ‘3.345679
| 3.345679e+00 | 3.34568’.
5. What will be the output of the following Python code snippet?
x=3.3456789
'%-6.2f | %05.2f | %+06.1f' %(x, x, x)
a) ‘3.35 | 03.35 | +003.3’
b) ‘3.3456789 | 03.3456789 | +03.3456789’
c) Error
d) ‘3.34 | 03.34 | 03.34+’
Answer: a
Explanation: The code shown above rounds the floating point value to two decimal places. In this code, a variety of addition
formatting features such as zero padding, total field width etc. Hence the output of this code is: ‘3.35 | 03.35 | +003.3’.
6. What will be the output of the following Python code snippet?
x=3.3456789
'%s' %x, str(x)
a) Error
b) (‘3.3456789’, ‘3.3456789’)
c) (3.3456789, 3.3456789)
d) (‘3.3456789’, 3.3456789)
Answer: b
Explanation: We can simply convert strings with a %s format expression or the str built-in function. Both of these methods have
been shown in this code. Hence the output is: ) (‘3.3456789’, ‘3.3456789’)
7. What will be the output of the following Python code snippet?
'%(qty)d more %(food)s' %{'qty':1, 'food': 'spam'}
a) Error
b) No output
c) ‘1 more foods’
d) ‘1 more spam’
Answer: d
Explanation: String formatting also allows conversion targets on the left to refer to the keys in a dictionary coded on the right and
fetch the corresponding values. In the code shown above, (qty) and (food) in the format string on the left refers to keys in the
dictionary literal on the right and fetch their assorted values. Hence the output of the code shown above is: 1 more spam.
8. What will be the output of the following Python code snippet?
a='hello'
q=10
vars()
a) {‘a’ : ‘hello’, ‘q’ : 10, ……..plus built-in names set by Python….}
b) {……Built in names set by Python……}
c) {‘a’ : ‘hello’, ‘q’ : 10}
d) Error
Answer: a
Explanation: The built in function vars() returns a dictionary containing all the variables that exist in the place. Hence the output of
the code shown above is: {‘a’ : ‘hello’, ‘q’ : 10, ……..plus built-in names set by Python….}
9. What will be the output of the following Python code?
s='{0}, {1}, and {2}'
s.format('hello', 'good', 'morning')
a) ‘hello good and morning’
b) ‘hello, good, morning’
c) ‘hello, good, and morning’
d) Error
Answer: c
Explanation: Within the subject string, curly braces designate substitution targets and arguments to be inserted either by position
or keyword. Hence the output of the code shown above:’hello, good,and morning’.
10. What will be the output of the following Python code?
s='%s, %s & %s'
s%('mumbai', 'kolkata', 'delhi')
a) mumbai kolkata & delhi
b) Error
c) No output
d) ‘mumbai, kolkata & delhi’
Answer: d
Explanation: In the code shown above, the format specifier %s is replaced by the designated substitution. Hence the output of
the code shown above is: ‘mumbai, kolkata & delhi’.
11. What will be the output of the following Python code?
t = '%(a)s, %(b)s, %(c)s'
t % dict(a='hello', b='world', c='universe')
a) ‘hello, world, universe’
b) ‘hellos, worlds, universes’
c) Error
d) hellos, world, universe
Answer: a
Explanation: Within the subject string, curly braces represent substitution targets and arguments to be inserted. Hence the output
of the code shown above:
‘hello, world, universe’.
12. What will be the output of the following Python code?
'{a}, {0}, {abc}'.format(10, a=2.5, abc=[1, 2])
a) Error
b) ‘2.5, 10, [1, 2]’
c) 2.5, 10, 1, 2
d) ’10, 2.5, [1, 2]’
Answer: b
Explanation: Since we have specified that the order of the output be: {a}, {0}, {abc}, hence the value of associated with {a} is
printed first followed by that of {0} and {abc}. Hence the output of the code shown above is: ‘2.5, 10, [1, 2]’.
13. What will be the output of the following Python code?
'{0:.2f}'.format(1.234)
a) ‘1’
b) ‘1.234’
c) ‘1.23’
d) ‘1.2’
Answer: c
Explanation: The code shown above displays the string method to round off a given decimal number to two decimal places.
Hence the output of the code is: ‘1.23’.
14. What will be the output of the following Python code?
'%x %d' %(255, 255)
a) ‘ff, 255’
b) ‘255, 255’
c) ‘15f, 15f’
d) Error
Answer: a
Explanation: The code shown above converts the given arguments to hexadecimal and decimal values and prints the result. This
is done using the format specifiers %x and %d respectively. Hence the output of the code shown above is: ‘ff, 255’.
15. The output of the two codes shown below is the same.
i. '{0:.2f}'.format(1/3.0)
ii. '%.2f'%(1/3.0)
a) True
b) False
Answer: a
Explanation: The two codes shown above represent the same operation but in different formats. The output of both of these
functions is: ‘0.33’. Hence the statement is true.
This set of Python Questions and Answers for Freshers focuses on “While and For Loops”.
1. What will be the output of the following Python code?
x = 123
for i in x:
print(i)
a) 1 2 3
b) 123
c) error
d) none of the mentioned
Answer: c
Explanation: Objects of type int are not iterable.
2. What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'}
for i in d:
print(i)
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
Answer: a
Explanation: Loops over the keys of the dictionary.
3. What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'}
for x, y in d:
print(x, y)
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
Answer: d
Explanation: Error, objects of type int aren’t iterable.
4. What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'}
for x, y in d.items():
print(x, y)
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
Answer: c
Explanation: Loops over key, value pairs.
5. What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'}
for x in d.keys():
print(d[x])
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
Answer: b
Explanation: Loops over the keys and prints the values.
6. What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'}
for x in d.values():
print(x)
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
Answer: b
Explanation: Loops over the values.
7. What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'}
for x in d.values():
print(d[x])
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
Answer: d
Explanation: Causes a KeyError.
8. What will be the output of the following Python code?
d = {0, 1, 2}
for x in d.values():
print(x)
a) 0 1 2
b) None None None
c) error
d) none of the mentioned
Answer: c
Explanation: Objects of type set have no attribute values.
9. What will be the output of the following Python code?
d = {0, 1, 2}
for x in d:
print(x)
a) 0 1 2
b) {0, 1, 2} {0, 1, 2} {0, 1, 2}
c) error
d) none of the mentioned
Answer: a
Explanation: Loops over the elements of the set and prints them.
10. What will be the output of the following Python code?
d = {0, 1, 2}
for x in d:
print(d.add(x))
a) 0 1 2
b) 0 1 2 0 1 2 0 1 2 …
c) None None None
d) None of the mentioned
Answer: c
Explanation: Variable x takes the values 0, 1 and 2. set.add() returns None which is printed.
11. What will be the output of the following Python code?
for i in range(0):
print(i)
a) 0
b) no output
c) error
d) none of the mentioned
Answer: b
Explanation: range(0) is empty.
To practice all questions on Python for freshers, .
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Function – 4”.
1. What is a variable defined outside a function referred to as?
a) A static variable
b) A global variable
c) A local variable
d) An automatic variable
Answer: b
Explanation: The value of a variable defined outside all function definitions is referred to as a global variable and can be used by
multiple functions of the program.
2. What is a variable defined inside a function referred to as?
a) A global variable
b) A volatile variable
c) A local variable
d) An automatic variable
Answer: c
Explanation: The variable inside a function is called as local variable and the variable definition is confined only to that function.
3. What will be the output of the following Python code?
i=0
def change(i):
i=i+1
return i
change(1)
print(i)
a) 1
b) Nothing is displayed
c) 0
d) An exception is thrown
Answer: c
Explanation: Any change made in to an immutable data type in a function isn’t reflected outside the function.
4. What will be the output of the following Python code?
def a(b):
b = b + [5]

c = [1, 2, 3, 4]
a(c)
print(len(c))
a) 4
b) 5
c) 1
d) An exception is thrown
Answer: b
Explanation: Since a list is mutable, any change made in the list in the function is reflected outside the function.
5. What will be the output of the following Python code?
a=10
b=20
def change():
global b
a=45
b=56
change()
print(a)
print(b)
a)
10
56
b)
45
56
c)
10
20
d) Syntax Error
Answer: a
Explanation: The statement “global b” allows the global value of b to be accessed and changed. Whereas the variable a is local
and hence the change isn’t reflected outside the function.
6. What will be the output of the following Python code?
def change(i = 1, j = 2):
i=i+j
j=j+1
print(i, j)
change(j = 1, i = 2)
a) An exception is thrown because of conflicting values
b) 1 2
c) 3 3
d) 3 2
Answer: d
Explanation: The values given during function call is taken into consideration, that is, i=2 and j=1.
7. What will be the output of the following Python code?
def change(one, *two):
print(type(two))
change(1,2,3,4)
a) Integer
b) Tuple
c) Dictionary
d) An exception is thrown
Answer: b
Explanation: The parameter two is a variable parameter and consists of (2,3,4). Hence the data type is tuple.
8. If a function doesn’t have a return statement, which of the following does the function return?
a) int
b) null
c) None
d) An exception is thrown without the return statement
Answer: c
Explanation: A function can exist without a return statement and returns None if the function doesn’t have a return statement.
9. What will be the output of the following Python code?
def display(b, n):
while n > 0:
print(b,end="")
n=n-1
display('z',3)
a) zzz
b) zz
c) An exception is executed
d) Infinite loop
Answer: a
Explanation: The loop runs three times and ‘z’ is printed each time.
10. What will be the output of the following Python code?
def find(a, **b):
print(type(b))
find('letters',A='1',B='2')
a) String
b) Tuple
c) Dictionary
d) An exception is thrown
Answer: c
Explanation: b combines the remaining parameters into a dictionary.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Functional Programming Tools”.
1. What will be the output of the following Python code?
odd=lambda x: bool(x%2)
numbers=[n for n in range(10)]
print(numbers)
n=list()
for i in numbers:
if odd(i):
continue
else:
break
a) [0, 2, 4, 6, 8, 10]
b) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
c) [1, 3, 5, 7, 9]
d) Error
Answer: b
Explanation: The code shown above returns a new list containing whole numbers up to 10 (excluding 10). Hence the output of the
code is: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].
2. What will be the output of the following Python code?
f=lambda x:bool(x%2)
print(f(20), f(21))
a) False True
b) False False
c) True True
d) True False
Answer: a
Explanation: The code shown above will return true if the given argument is an odd number, and false if the given argument is an
even number. Since the arguments are 20 and 21 respectively, the output of this code is: False True.
3. What will be the output of the following Python code?
import functools
l=[1,2,3,4]
print(functools.reduce(lambda x,y:x*y,l))
a) Error
b) 10
c) 24
d) No output
Answer: c
Explanation: The code shown above returns the product of all the elements of the list. Hence the output is 1*2*3*4 = 24.
4. What will be the output of the following Python code?
l=[1, -2, -3, 4, 5]
def f1(x):
return x<2
m1=filter(f1, l)
print(list(m1))
a) [1, 4, 5 ]
b) Error
c) [-2, -3]
d) [1, -2, -3]
Answer: d
Explanation: The code shown above returns only those elements from the list, which are less than 2. The functional programming
tool used to achieve this operation is filter. Hence the output of the code is:[1, -2, -3].
5. What will be the output of the following Python code?
l=[-2, 4]
m=map(lambda x:x*2, l)
print(m)
a) [-4, 16]
b) Address of m
c) Error
d)
-4
16
Answer: b
Explanation: The code shown above returns the address of m. Had we used the statement: print(list(m)), the output would have
been: [-4, 16].

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


l=[1, -2, -3, 4, 5]
def f1(x):
return x<-1
m1=map(f1, l)
print(list(m1))
a) [False, False, False, False, False]
b) [False, True, True, False, False]
c) [True, False, False, True, True]
d) [True, True, True, True, True]
Answer: b
Explanation: This code shown returns a list which contains True if the corresponding element of the list is less than -1, and false if
the corresponding element is greater than -1. Hence the output of the code shown above: [False, True, True, False, False].
7. What will be the output of the following Python code?
l=[1, 2, 3, 4, 5]
m=map(lambda x:2**x, l)
print(list(m))
a) [1, 4, 9, 16, 25 ]
b) [2, 4, 8, 16, 32 ]
c) [1, 0, 1, 0, 1]
d) Error
Answer: b
Explanation: The code shown above prints a list containing each element of the list as the power of two. That is, the output is: [2,
4, 8, 16, 32].
8. What will be the output of the following Python code?
import functools
l=[1, 2, 3, 4, 5]
m=functools.reduce(lambda x, y:x if x>y else y, l)
print(m)
a) Error
b) Address of m
c) 1
d) 5
Answer: d
Explanation: The code shown above can be used to find the maximum of the elements from the given list. In the above code, this
operation is achieved by using the programming tool reduce. Hence the output of the code shown above is 5.
9. What will be the output of the following Python code?
l=[n for n in range(5)]
f=lambda x:bool(x%2)
print(f(3), f(1))
for i in range(len(l)):
if f(l[i]):
del l[i]
print(i)
a)
True True
1
2
Error
b)
False False
1
2
c)
True False
1
2
Error
d)
False True
1
2
Answer: a
Explanation: The code shown above prints true if the value entered as an argument is odd, else false is printed. Hence the
output: True True. The error is due to the list index being out of range.

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


m=reduce(lambda x: x-3 in range(4, 10))
print(list(m))
a) [1, 2, 3, 4, 5, 6, 7]
b) No output
c) [1, 2, 3, 4, 5, 6]
d) Error
Answer: b
Explanation: The code shown above will result in an error. This is because e have not imported functools. Further, ‘reduce’, as
such is not defined. We should use functools.reduce to remove the error.
11. Which of the following numbers will not be a part of the output list of the following Python code?
def sf(a):
return a%3!=0 and a%5!=0
m=filter(sf, range(1, 31))
print(list(m))
a) 1
b) 29
c) 6
d) 10
Answer: d
Explanation: The output list of the code shown above will not contain any element that is divisible by 3 or 5. Hence the number
which is not present in the output list is 10. The output list: [1, 2, 4, 7, 8, 11, 13, 14, 16, 17, 19, 22, 23, 26, 28, 29]
12. The single line equivalent of the following Python code?
l=[1, 2, 3, 4, 5]
def f1(x):
return x<0
m1=filter(f1, l)
print(list(m1))
a) filter(lambda x:x<0, l)
b) filter(lambda x, y: x<0, l)
c) filter(reduce x<0, l)
d) reduce(x: x<0, l)
Answer: a
Explanation: The code shown above returns a new list containing only those elements from list l, which are less than 0. Since
there are no such elements in the list l, the output of this code is: []. The single line equivalent of this code is filter(lambda x:x<0, l).
13. What will be the output of the following Python code?
list(map((lambda x:x^2), range(10)))
a) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
b) Error
c) [2, 3, 0, 1, 6, 7, 4, 5, 10, 11]
d) No output
Answer: c
Explanation: The line of code shown above returns a list of each number from 1 to 10, after an XOR operation is performed on
each of these numbers with 2. Hence the output of this code is: [2, 3, 0, 1, 6, 7, 4, 5, 10, 11]
14. What will be the output of the following Python code?
list(map((lambda x:x**2), filter((lambda x:x%2==0), range(10))))
a) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b) [0, 4, 16, 36, 64]
c) Error
d) No output
Answer: b
Explanation: The output list will contain each number up to 10 raised to 2, except odd numbers, that is, 1, 3, 5, 9. Hence the
output of the code is: [0, 4, 16, 36, 64].
15. The output of the following codes are the same.
[x**2 for x in range(10)]
list(map((lambda x:x**2), range(10)))
a) True
b) False
Answer: a
Explanation: Both of the codes shown above print each whole number up to 10, raised to the power 2. Hence the output of both
of these codes is: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]. Therefore, the statement is true.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Global vs Local Variables – 1”.
1. What will be the output of the following Python code?
def f1():
x=15
print(x)
x=12
f1()
a) Error
b) 12
c) 15
d) 1512
Answer: c
Explanation: In the code shown above, x=15 is a local variable whereas x=12 is a global variable. Preference is given to local
variable over global variable. Hence the output of the code shown above is 15.
2. What will be the output of the following Python code?
def f1():
x=100
print(x)
x=+1
f1()
a) Error
b) 100
c) 101
d) 99
Answer: b
Explanation: The variable x is a local variable. It is first printed and then modified. Hence the output of this code is 100.
3. What will be the output of the following Python code?
def san(x):
print(x+1)
x=-2
x=4
san(12)
a) 13
b) 10
c) 2
d) 5
Answer: a
Explanation: The value passed to the function san() is 12. This value is incremented by one and printed. Hence the output of the
code shown above is 13.
4. What will be the output of the following Python code?
def f1():
global x
x+=1
print(x)
x=12
print("x")
a) Error
b) 13
c)
13
x
d) x
Answer: d
Explanation: In the code shown above, the variable ‘x’ is declared as global within the function. Hence the output is ‘x’. Had the
variable ‘x’ been a local variable, the output would have been:
13
x
5. What will be the output of the following Python code?
def f1(x):
global x
x+=1
print(x)
f1(15)
print("hello")
a) error
b) hello
c) 16
d)
16
hello
Answer: a
Explanation: The code shown above will result in an error because ‘x’ is a global variable. Had it been a local variable, the output
would be: 16
hello

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


x=12
def f1(a,b=x):
print(a,b)
x=15
f1(4)
a) Error
b) 12 4
c) 4 12
d) 4 15
Answer: c
Explanation: At the time of leader processing, the value of ‘x’ is 12. It is not modified later. The value passed to the function f1 is
4. Hence the output of the code shown above is 4 12.
7. What will be the output of the following Python code?
def f():
global a
print(a)
a = "hello"
print(a)
a = "world"
f()
print(a)
a)
hello
hello
world
b)
world
hello
hello
c)
hello
world
world
d)
world
hello
world
Answer: b
Explanation: Since the variable ‘a’ has been explicitly specified as a global variable, the value of a passed to the function is
‘world’. Hence the output of this code is:
world
hello
hello

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


def f1(a,b=[]):
b.append(a)
return b
print(f1(2,[3,4]))
a) [3,2,4]
b) [2,3,4]
c) Error
d) [3,4,2]
Answer: d
Explanation: In the code shown above, the integer 2 is appended to the list [3,4]. Hence the output of the code is [3,4,2]. Both the
variables a and b are local variables.
9. What will be the output of the following Python code?
def f(p, q, r):
global s
p = 10
q = 20
r = 30
s = 40
print(p,q,r,s)
p,q,r,s = 1,2,3,4
f(5,10,15)
a) 1 2 3 4
b) 5 10 15 4
c) 10 20 30 40
d) 5 10 15 40
Answer: c
Explanation: The above code shows a combination of local and global variables. The output of this code is: 10 20 30 40
10. What will be the output of the following Python code?
def f(x):
print("outer")
def f1(a):
print("inner")
print(a,x)
f(3)
f1(1)
a)
outer
error
b)
inner
error
c)
outer
inner
d) error
Answer: a
Explanation: The error will be caused due to the statement f1(1) because the function is nested. If f1(1) had been called inside
the function, the output would have been different and there would be no error.
11. What will be the output of the following Python code?
x=5
def f1():
global x
x=4
def f2(a,b):
global x
return a+b+x
f1()
total = f2(1,2)
print(total)
a) Error
b) 7
c) 8
d) 15
Answer: b
Explanation: In the code shown above, the variable ‘x’ has been declared as a global variable under both the functions f1 and f2.
The value returned is a+b+x = 1+2+4 = 7.
12. What will be the output of the following Python code?
x=100
def f1():
global x
x=90
def f2():
global x
x=80
print(x)
a) 100
b) 90
c) 80
d) Error
Answer: a
Explanation: The output of the code shown above is 100. This is because the variable ‘x’ has been declared as global within the
functions f1 and f2.
13. Read the following Python code carefully and point out the global variables?
y, z = 1, 2
def f():
global x
x = y+z
a) x
b) y and z
c) x, y and z
d) Neither x, nor y, nor z
Answer: c
Explanation: In the code shown above, x, y and z are global variables inside the function f. y and z are global because they are
not assigned in the function. x is a global variable because it is explicitly specified so in the code. Hence, x, y and z are global
variables.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Global vs Local Variables – 2”.
1. Which of the following data structures is returned by the functions globals() and locals()?
a) list
b) set
c) dictionary
d) tuple
Answer: c
Explanation: Both the functions, that is, globals() and locals() return value of the data structure dictionary.
2. What will be the output of the following Python code?
x=1
def cg():
global x
x=x+1
cg()
x
a) 2
b) 1
c) 0
d) Error
Answer: a
Explanation: Since ‘x’ has been declared a global variable, it can be modified very easily within the function. Hence the output is
2.
3. On assigning a value to a variable inside a function, it automatically becomes a global variable.
a) True
b) False
Answer: b
Explanation: On assigning a value to a variable inside a function, t automatically becomes a local variable. Hence the above
statement is false.
4. What will be the output of the following Python code?
e="butter"
def f(a): print(a)+e
f("bitter")
a) error
b)
butter
error
c)
bitter
error
d) bitterbutter
Answer: c
Explanation: The output of the code shown above will be ‘bitter’, followed by an error. The error is because the operand ‘+’ is
unsupported on the types used above.
5. What happens if a local variable exists with the same name as the global variable you want to access?
a) Error
b) The local variable is shadowed
c) Undefined behavior
d) The global variable is shadowed
Answer: d
Explanation: If a local variable exists with the same name as the local variable that you want to access, then the global variable is
shadowed. That is, preference is given to the local variable.
6. What will be the output of the following Python code?
a=10
globals()['a']=25
print(a)
a) 10
b) 25
c) Junk value
d) Error
Answer: b
Explanation: In the code shown above, the value of ‘a’ can be changed by using globals() function. The dictionary returned is
accessed using key of the variable ‘a’ and modified to 25.
7. What will be the output of the following Python code?
def f(): x=4
x=1
f()
x
a) Error
b) 4
c) Junk value
d) 1
Answer: d
Explanation: In the code shown above, when we call the function f, a new namespace is created. The assignment x=4 is
performed in the local namespace and does not affect the global namespace. Hence the output is 1.
8. ______________ returns a dictionary of the module namespace.
________________ returns a dictionary of the current namespace.
a)
locals()
globals()
b)
locals()
locals()
c)
globals()
locals()
d)
globals()
globals()
Answer: c
Explanation: The function globals() returns a dictionary of the module namespace, whereas the function locals() returns a
dictionary of the current namespace.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Inheritance – 1”.
1. Which of the following best describes inheritance?
a) Ability of a class to derive members of another class as a part of its own definition
b) Means of bundling instance variables and methods in order to restrict access to certain class members
c) Focuses on variables and passing of variables to functions
d) Allows for implementation of elegant software that is well designed and easily modified
Answer: a
Explanation: If the class definition is class B(A): then class B inherits the methods of class A. This is called inheritance.
2. Which of the following statements is wrong about inheritance?
a) Protected members of a class can be inherited
b) The inheriting class is called a subclass
c) Private members of a class can be inherited and accessed
d) Inheritance is one of the features of OOP
Answer: c
Explanation: Any changes made to the private members of the class in the subclass aren’t reflected in the original members.
3. What will be the output of the following Python code?
class Demo:
def __new__(self):
self.__init__(self)
print("Demo's __new__() invoked")
def __init__(self):
print("Demo's __init__() invoked")
class Derived_Demo(Demo):
def __new__(self):
print("Derived_Demo's __new__() invoked")
def __init__(self):
print("Derived_Demo's __init__() invoked")
def main():
obj1 = Derived_Demo()
obj2 = Demo()
main()
a)
Derived_Demo’s __init__() invoked
Derived_Demo's __new__() invoked
Demo's __init__() invoked
Demo's __new__() invoked
b)
Derived_Demo's __new__() invoked
Demo's __init__() invoked
Demo's __new__() invoked
c)
Derived_Demo's __new__() invoked
Demo's __new__() invoked
d)
Derived_Demo’s __init__() invoked
Demo's __init__() invoked
Answer: b
Explanation: Since the object for the derived class is declared first, __new__() method of the derived class is invoked first,
followed by the constructor and the __new__() method of main class.

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


class Test:
def __init__(self):
self.x = 0
class Derived_Test(Test):
def __init__(self):
self.y = 1
def main():
b = Derived_Test()
print(b.x,b.y)
main()
a) 0 1
b) 0 0
c) Error because class B inherits A but variable x isn’t inherited
d) Error because when object is created, argument must be passed like Derived_Test(1)
Answer: c
Explanation: Since the invoking method, Test.__init__(self), isn’t present in the derived class, variable x can’t be inherited.
5. What will be the output of the following Python code?
class A():
def disp(self):
print("A disp()")
class B(A):
pass
obj = B()
obj.disp()
a) Invalid syntax for inheritance
b) Error because when object is created, argument must be passed
c) Nothing is printed
d) A disp()
Answer: d
Explanation: Class B inherits class A hence the function disp () becomes part of class B’s definition. Hence disp() method is
properly executed and the line is printed.
6. All subclasses are a subtype in object-oriented programming.
a) True
b) False
Answer: b
Explanation: A subtype is something that be substituted for and behave as its parent type. All subclass may not be a subtype in
object-oriented programming.
7. When defining a subclass in Python that is meant to serve as a subtype, the subtype Python keyword is used.
a) True
b) False
Answer: b
Explanation: B is a subtype of B if instances of type B can substitute for instances of type A without affecting semantics.
8. Suppose B is a subclass of A, to invoke the __init__ method in A from B, what is the line of code you should write?
a) A.__init__(self)
b) B.__init__(self)
c) A.__init__(B)
d) B.__init__(A)
Answer: a
Explanation: To invoke the __init__ method in A from B, either of the following should be written: A.__init__(self) or
super().__init__(self).
9. What will be the output of the following Python code?
class Test:
def __init__(self):
self.x = 0
class Derived_Test(Test):
def __init__(self):
Test.__init__(self)
self.y = 1
def main():
b = Derived_Test()
print(b.x,b.y)
main()
a) Error because class B inherits A but variable x isn’t inherited
b) 0 0
c) 0 1
d) Error, the syntax of the invoking method is wrong
Answer: c
Explanation: Since the invoking method has been properly invoked, variable x from the main class has been properly inherited
and it can also be accessed.
10. What will be the output of the following Python code?
class A:
def __init__(self, x= 1):
self.x = x
class der(A):
def __init__(self,y = 2):
super().__init__()
self.y = y
def main():
obj = der()
print(obj.x, obj.y)
main()
a) Error, the syntax of the invoking method is wrong
b) The program runs fine but nothing is printed
c) 1 0
d) 1 2
Answer: d
Explanation: In the above piece of code, the invoking method has been properly implemented and hence x=1 and y=2.
11. What does built-in function type do in context of classes?
a) Determines the object name of any value
b) Determines the class name of any value
c) Determines class description of any value
d) Determines the file name of any value
Answer: b
Explanation: For example: >>> type((1,)) gives <class ‘tuple’>.
12. Which of the following is not a type of inheritance?
a) Double-level
b) Multi-level
c) Single-level
d) Multiple
Answer: a
Explanation: Multiple, multi-level, single-level and hierarchical inheritance are all types of inheritance.
13. What does built-in function help do in context of classes?
a) Determines the object name of any value
b) Determines the class identifiers of any value
c) Determines class description of any built-in type
d) Determines class description of any user-defined built-in type
Answer: c
Explanation: help() usually gives information of the class on any built-in type or function.
14. What will be the output of the following Python code?
class A:
def one(self):
return self.two()

def two(self):
return 'A'

class B(A):
def two(self):
return 'B'
obj1=A()
obj2=B()
print(obj1.two(),obj2.two())
a) A A
b) A B
c) B B
d) An exception is thrown
Answer: b
Explanation: obj1.two() invokes the method two() in class A which returns ‘A’ and obj2.two() invokes the method two() in class B
which returns ‘B’.
15. What type of inheritance is illustrated in the following Python code?
class A():
pass
class B():
pass
class C(A,B):
pass
a) Multi-level inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Single-level inheritance
Answer: b
Explanation: In multiple inheritance, two or more subclasses are derived from the superclass as shown in the above piece of
code.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Inheritance – 2”.
1. What type of inheritance is illustrated in the following Python code?
class A():
pass
class B(A):
pass
class C(B):
pass
a) Multi-level inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Single-level inheritance
Answer: a
Explanation: In multi-level inheritance, a subclass derives from another class which itself is derived from another class.
2. What does single-level inheritance mean?
a) A subclass derives from a class which in turn derives from another class
b) A single superclass inherits from multiple subclasses
c) A single subclass derives from a single superclass
d) Multiple base classes inherit a single derived class
Answer: c
Explanation: In single-level inheritance, there is a single subclass which inherits from a single superclass. So the class definition
of the subclass will be: class B(A): where A is the superclass.
3. What will be the output of the following Python code?
class A:
def __init__(self):
self.__i = 1
self.j = 5

def display(self):
print(self.__i, self.j)
class B(A):
def __init__(self):
super().__init__()
self.__i = 2
self.j = 7
c = B()
c.display()
a) 2 7
b) 1 5
c) 1 7
d) 2 5
Answer: c
Explanation: Any change made in variable i isn’t reflected as it is the private member of the superclass.
4. Which of the following statements isn’t true?
a) A non-private method in a superclass can be overridden
b) A derived class is a subset of superclass
c) The value of a private variable in the superclass can be changed in the subclass
d) When invoking the constructor from a subclass, the constructor of superclass is automatically invoked
Answer: c
Explanation: If the value of a private variable in a superclass is changed in the subclass, the change isn’t reflected.
5. What will be the output of the following Python code?
class A:
def __init__(self,x):
self.x = x
def count(self,x):
self.x = self.x+1
class B(A):
def __init__(self, y=0):
A.__init__(self, 3)
self.y = y
def count(self):
self.y += 1
def main():
obj = B()
obj.count()
print(obj.x, obj.y)
main()
a) 3 0
b) 3 1
c) 0 1
d) An exception in thrown
Answer: b
Explanation: Initially x=3 and y=0. When obj.count() is called, y=1.
6. What will be the output of the following Python code?
>>> class A:
pass
>>> class B(A):
pass
>>> obj=B()
>>> isinstance(obj,A)
a) True
b) False
c) Wrong syntax for isinstance() method
d) Invalid method for classes
Answer: a
Explanation: isinstance(obj,class) returns True if obj is an object class.
7. Which of the following statements is true?
a) The __new__() method automatically invokes the __init__ method
b) The __init__ method is defined in the object class
c) The __eq(other) method is defined in the object class
d) The __repr__() method is defined in the object class
Answer: c
Explanation: The __eq(other) method is called if any comparison takes place and it is defined in the object class.
8. Method issubclass() checks if a class is a subclass of another class.
a) True
b) False
Answer: a
Explanation: Method issubclass() returns True if a class is a subclass of another class and False otherwise.
9. What will be the output of the following Python code?
class A:
def __init__(self):
self.__x = 1
class B(A):
def display(self):
print(self.__x)
def main():
obj = B()
obj.display()
main()
a) 1
b) 0
c) Error, invalid syntax for object declaration
d) Error, private class member can’t be accessed in a subclass
Answer: d
Explanation: Private class members in the superclass can’t be accessed in the subclass.
10. What will be the output of the following Python code?
class A:
def __init__(self):
self._x = 5
class B(A):
def display(self):
print(self._x)
def main():
obj = B()
obj.display()
main()
a) Error, invalid syntax for object declaration
b) Nothing is printed
c) 5
d) Error, private class member can’t be accessed in a subclass
Answer: c
Explanation: The class member x is protected, not private and hence can be accessed by subclasses.
11. What will be the output of the following Python code?
class A:
def __init__(self,x=3):
self._x = x
class B(A):
def __init__(self):
super().__init__(5)
def display(self):
print(self._x)
def main():
obj = B()
obj.display()

main()
a) 5
b) Error, class member x has two values
c) 3
d) Error, protected class member can’t be accessed in a subclass
Answer: a
Explanation: The super() method re-assigns the variable x with value 5. Hence 5 is printed.
12. What will be the output of the following Python code?
class A:
def test1(self):
print(" test of A called ")
class B(A):
def test(self):
print(" test of B called ")
class C(A):
def test(self):
print(" test of C called ")
class D(B,C):
def test2(self):
print(" test of D called ")
obj=D()
obj.test()
a)
test of B called
test of C called
b)
test of C called
test of B called
c) test of B called
d) Error, both the classes from which D derives has same method test()
Answer: c
Explanation: Execute in Python shell to verify. If class D(B,C): is switched is class D(C,B): test of C is called.
13. What will be the output of the following Python code?
class A:
def test(self):
print("test of A called")
class B(A):
def test(self):
print("test of B called")
super().test()
class C(A):
def test(self):
print("test of C called")
super().test()
class D(B,C):
def test2(self):
print("test of D called")
obj=D()
obj.test()
a)
test of B called
test of C called
test of A called
b)
test of C called
test of B called
c)
test of B called
test of C called
d) Error, all the three classes from which D derives has same method test()
Answer: a
Explanation: Since the invoking method, super().test() is called in the subclasses, all the three methods of test() in three different
classes is called.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “List Comprehension – 1”.
1. What will be the output of the following Python code?
l=[1,2,3,4,5]
[x&1 for x in l]
a) [1, 1, 1, 1, 1]
b) [1, 0, 1, 0, 1]
c) [1, 0, 0, 0, 0]
d) [0, 1, 0, 1, 0]
Answer: b
Explanation: In the code shown above, each of the numbers of the list, that is, 1, 2, 3, 4 and 5 are AND-ed with 1 and the result is
printed in the form of a list. Hence the output is [1, 0, 1, 0, 1].
2. What will be the output of the following Python code?
l1=[1,2,3]
l2=[4,5,6]
[x*y for x in l1 for y in l2]
a) [4, 8, 12, 5, 10, 15, 6, 12, 18]
b) [4, 10, 18]
c) [4, 5, 6, 8, 10, 12, 12, 15, 18]
d) [18, 12, 6, 15, 10, 5, 12, 8, 4]
Answer: c
Explanation: The code shown above returns x*y, where x belongs to the list l1 and y belongs to the list l2. Therefore, the output is:
[4, 5, 6, 8, 10, 12, 12, 15, 18].
3. Write the list comprehension to pick out only negative integers from a given list ‘l’.
a) [x<0 in l]
b) [x for x<0 in l]
c) [x in l for x<0]
d) [x for x in l if x<0]
Answer: d
Explanation: To pick out only the negative numbers from a given list ‘l’, the correct list comprehension statement would be: [x for x
in l if x<0].

For example if we have a list l=[-65, 2, 7, -99, -4, 3]


>>> [x for x in l if x<0]
The output would be: [-65, -99, -4].
4. What will be the output of the following Python code?
s=["pune", "mumbai", "delhi"]
[(w.upper(), len(w)) for w in s]
a) Error
b) [‘PUNE’, 4, ‘MUMBAI’, 6, ‘DELHI’, 5]
c) [PUNE, 4, MUMBAI, 6, DELHI, 5]
d) [(‘PUNE’, 4), (‘MUMBAI’, 6), (‘DELHI’, 5)]
Answer: d
Explanation: If we need to generate two results, we need to put it in the form of a tuple. The code shown above returns each word
of list in uppercase, along with the length of the word. Hence the output of the code is: [(‘PUNE’, 4), (‘MUMBAI’, 6), (‘DELHI’, 5)].
5. What will be the output of the following Python code?
l1=[2,4,6]
l2=[-2,-4,-6]
for i in zip(l1, l2):
print(i)
a)
2, -2
4, -4
6, -6
b) [(2, -2), (4, -4), (6, -6)]
c)
(2, -2)
(4, -4)
(6, -6)
d) [-4, -16, -36]
Answer: c
Explanation: The output of the code shown will be:
(2, -2)
(4, -4)
(6, -6)
This format is due to the statement print(i).
6. What will be the output of the following Python code?
l1=[10, 20, 30]
l2=[-10, -20, -30]
l3=[x+y for x, y in zip(l1, l2)]
l3
a) Error
b) 0
c) [-20, -60, -80]
d) [0, 0, 0]
Answer: d
Explanation: The code shown above returns x+y, for x belonging to the list l1 and y belonging to the list l2. That is, l3=[10-10, 20-
20, 30-20], which is, [0, 0, 0].
7. Write a list comprehension for number and its cube for l=[1, 2, 3, 4, 5, 6, 7, 8, 9].
a) [x**3 for x in l]
b) [x^3 for x in l]
c) [x**3 in l]
d) [x^3 in l]
Answer: a
Explanation: The list comprehension to print a list of cube of the numbers for the given list is: [x**3 for x in l].
8. What will be the output of the following Python code?
l=[[1 ,2, 3], [4, 5, 6], [7, 8, 9]]
[[row[i] for row in l] for i in range(3)]
a) Error
b) [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
c)
147
258
369
d)
(1 4 7)
(2 5 8)
(3 6 9)
Answer: b
Explanation: In the code shown above, ‘3’ is the index of the list. Had we used a number greater than 3, it would result in an error.
The output of this code is: [[1, 4, 7], [2, 5, 8], [3, 6, 9]].

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


import math
[str(round(math.pi)) for i in range (1, 6)]
a) [‘3’, ‘3’, ‘3’, ‘3’, ‘3’, ‘3’]
b) [‘3.1’, ‘3.14’, ‘3.142’, ‘3.1416’, ‘3.14159’, ‘3.141582’]
c) [‘3’, ‘3’, ‘3’, ‘3’, ‘3’]
d) [‘3.1’, ‘3.14’, ‘3.142’, ‘3.1416’, ‘3.14159’]
Answer: c
Explanation: The list comprehension shown above rounds off pi(3.141) and returns its value, that is 3. This is done 5 times.
Hence the output is: [‘3’, ‘3’, ‘3’, ‘3’, ‘3’].
10. What will be the output of the following Python code?
l1=[1,2,3]
l2=[4,5,6]
l3=[7,8,9]
for x, y, z in zip(l1, l2, l3):
print(x, y, z)
a)
147
258
369
b)
(1 4 7)
(2 5 8)
(3 6 9)
c) [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
d) Error
Answer: a
Explanation: The output of the code shown above is:
147
258
369
This is due to the statement: print(x, y,z).
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “List Comprehension – 2”.
1. Read the information given below carefully and write a list comprehension such that the output is: [‘e’, ‘o’]
w="hello"
v=('a', 'e', 'i', 'o', 'u')
a) [x for w in v if x in v]
b) [x for x in w if x in v]
c) [x for x in v if w in v]
d) [x for v in w for x in w]
Answer: b
Explanation: The tuple ‘v’ is used to generate a list containing only vowels in the string ‘w’. The result is a list containing only
vowels present in the string “hello”. Hence the required list comprehension is: [x for x in w if x in v].
2. What will be the output of the following Python code?
[ord(ch) for ch in 'abc']
a) [97, 98, 99]
b) [‘97’, ‘98’, ‘99’]
c) [65, 66, 67]
d) Error
Answer: a
Explanation: The list comprehension shown above returns the ASCII value of each alphabet of the string ‘abc’. Hence the output
is: [97, 98, 99]. Had the string been ‘ABC’, the output would be: [65, 66, 67].
3. What will be the output of the following Python code?
t=32.00
[round((x-32)*5/9) for x in t]
a) [0]
b) 0
c) [0.00]
d) Error
Answer: d
Explanation: The value of t in the code shown above is equal to 32.00, which is a floating point value. ‘Float’ objects are not
iterable. Hence the code results in an error.
4. Write a list comprehension for producing a list of numbers between 1 and 1000 that are divisible by 3.
a) [x in range(1, 1000) if x%3==0]
b) [x for x in range(1000) if x%3==0]
c) [x%3 for x in range(1, 1000)]
d) [x%3=0 for x in range(1, 1000)]
Answer: b
Explanation: The list comprehension [x for x in range(1000) if x%3==0] produces a list of numbers between 1 and 1000 that are
divisible by 3.
5. Write a list comprehension equivalent for the Python code shown below.
for i in range(1, 101):
if int(i*0.5)==i*0.5:
print(i)
a) [i for i in range(1, 100) if int(i*0.5)==(i*0.5)]
b) [i for i in range(1, 101) if int(i*0.5)==(i*0.5)]
c) [i for i in range(1, 101) if int(i*0.5)=(i*0.5)]
d) [i for i in range(1, 100) if int(i*0.5)=(i*0.5)]
Answer: b
Explanation: The code shown above prints the value ‘i’ only if it satisfies the condition: int(i*0.5) is equal to (i*0.5). Hence the
required list comprehension is: [i for i in range(1, 101) if int(i*0.5)==(i*0.5)].
6. What is the list comprehension equivalent for: list(map(lambda x:x**-1, [1, 2, 3]))?
a) [1|x for x in [1, 2, 3]]
b) [-1**x for x in [1, 2, 3]]
c) [x**-1 for x in [1, 2, 3]]
d) [x^-1 for x in range(4)]
Answer: c
Explanation: The output of the function list(map(lambda x:x**-1, [1, 2, 3])) is [1.0, 0.5, 0.3333333333333333] and that of the list
comprehension [x**-1 for x in [1, 2, 3]] is [1.0, 0.5, 0.3333333333333333]. Hence the answer is: [x**-1 for x in [1, 2, 3]].
7. Write a list comprehension to produce the list: [1, 2, 4, 8, 16……212].
a) [(2**x) for x in range(0, 13)]
b) [(x**2) for x in range(1, 13)]
c) [(2**x) for x in range(1, 13)]
d) [(x**2) for x in range(0, 13)]
Answer: a
Explanation: The required list comprehension will print the numbers from 1 to 12, each raised to 2. The required answer is thus,
[(2**x) for x in range(0, 13)].
8. What is the list comprehension equivalent for?
{x : x is a whole number less than 20, x is even} (including zero)
a) [x for x in range(1, 20) if (x%2==0)]
b) [x for x in range(0, 20) if (x//2==0)]
c) [x for x in range(1, 20) if (x//2==0)]
d) [x for x in range(0, 20) if (x%2==0)]
Answer: d
Explanation: The required list comprehension will print a whole number, less than 20, provided that the number is even. Since the
output list should contain zero as well, the answer to this question is: [x for x in range(0, 20) if (x%2==0)].
9. What will be the output of the following Python list comprehension?
[j for i in range(2,8) for j in range(i*2, 50, i)]
a) A list of prime numbers up to 50
b) A list of numbers divisible by 2, up to 50
c) A list of non prime numbers, up to 50
d) Error
Answer: c
Explanation: The list comprehension shown above returns a list of non-prime numbers up to 50. The logic behind this is that the
square root of 50 is almost equal to 7. Hence all the multiples of 2-7 are not prime in this range.
10. What will be the output of the following Python code?
l=["good", "oh!", "excellent!", "#450"]
[n for n in l if n.isalpha() or n.isdigit()]
a) [‘good’, ‘oh’, ‘excellent’, ‘450’ ]
b) [‘good’]
c) [‘good’, ‘#450’]
d) [‘oh!’, ‘excellent!’, ‘#450’]
Answer: b
Explanation: The code shown above returns a new list containing only strings which do not have any punctuation in them. The
only string from the list which does not contain any punctuation is ‘good’. Hence the output of the code shown above is [‘good’].
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “List Comprehension”.
1. What will be the output of the following Python code snippet?
k = [print(i) for i in my_string if i not in "aeiou"]
a) prints all the vowels in my_string
b) prints all the consonants in my_string
c) prints all characters of my_string that aren’t vowels
d) prints only on executing print(k)
Answer: c
Explanation: print(i) is executed if the given character is not a vowel.
2. What is the output of print(k) in the following Python code snippet?
k = [print(i) for i in my_string if i not in "aeiou"]
print(k)
a) all characters of my_string that aren’t vowels
b) a list of Nones
c) list of Trues
d) list of Falses
Answer: b
Explanation: print() returns None.
3. What will be the output of the following Python code snippet?
my_string = "hello world"
k = [(i.upper(), len(i)) for i in my_string]
print(k)
a) [(‘HELLO’, 5), (‘WORLD’, 5)]
b) [(‘H’, 1), (‘E’, 1), (‘L’, 1), (‘L’, 1), (‘O’, 1), (‘ ‘, 1), (‘W’, 1), (‘O’, 1), (‘R’, 1), (‘L’, 1), (‘D’, 1)]
c) [(‘HELLO WORLD’, 11)]
d) none of the mentioned
Answer: b
Explanation: We are iterating over each letter in the string.
4. Which of the following is the correct expansion of list_1 = [expr(i) for i in list_0 if func(i)]?
a)
list_1 = []
for i in list_0:
if func(i):
list_1.append(i)
b)
for i in list_0:
if func(i):
list_1.append(expr(i))
c)
list_1 = []
for i in list_0:
if func(i):
list_1.append(expr(i))
d) none of the mentioned
Answer: c
Explanation: We have to create an empty list, loop over the contents of the existing list and check if a condition is satisfied
before performing some operation and adding it to the new list.
5. What will be the output of the following Python code snippet?
x = [i**+1 for i in range(3)]; print(x);
a) [0, 1, 2]
b) [1, 2, 5]
c) error, **+ is not a valid operator
d) error, ‘;’ is not allowed
Answer: a
Explanation: i**+1 is evaluated as (i)**(+1).
6. What will be the output of the following Python code snippet?
print([i.lower() for i in "HELLO"])
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) ‘hello’
c) [‘hello’]
d) hello
Answer: a
Explanation: We are iterating over each letter in the string.
7. What will be the output of the following Python code snippet?
print([i+j for i in "abc" for j in "def"])
a) [‘da’, ‘ea’, ‘fa’, ‘db’, ‘eb’, ‘fb’, ‘dc’, ‘ec’, ‘fc’]
b) [[‘ad’, ‘bd’, ‘cd’], [‘ae’, ‘be’, ‘ce’], [‘af’, ‘bf’, ‘cf’]]
c) [[‘da’, ‘db’, ‘dc’], [‘ea’, ‘eb’, ‘ec’], [‘fa’, ‘fb’, ‘fc’]]
d) [‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’, ‘cf’]
Answer: d
Explanation: If it were to be executed as a nested for loop, i would be the outer loop and j the inner loop.
8. What will be the output of the following Python code snippet?
print([[i+j for i in "abc"] for j in "def"])
a) [‘da’, ‘ea’, ‘fa’, ‘db’, ‘eb’, ‘fb’, ‘dc’, ‘ec’, ‘fc’]
b) [[‘ad’, ‘bd’, ‘cd’], [‘ae’, ‘be’, ‘ce’], [‘af’, ‘bf’, ‘cf’]]
c) [[‘da’, ‘db’, ‘dc’], [‘ea’, ‘eb’, ‘ec’], [‘fa’, ‘fb’, ‘fc’]]
d) [‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’, ‘cf’]
Answer: b
Explanation: The inner list is generated once for each value of j.
9. What will be the output of the following Python code snippet?
print([if i%2==0: i; else: i+1; for i in range(4)])
a) [0, 2, 2, 4]
b) [1, 1, 3, 3]
c) error
d) none of the mentioned
Answer: c
Explanation: Syntax error.
10. Which of the following is the same as list(map(lambda x: x**-1, [1, 2, 3]))?
a) [x**-1 for x in [(1, 2, 3)]]
b) [1/x for x in [(1, 2, 3)]]
c) [1/x for x in (1, 2, 3)]
d) error
Answer: c
Explanation: x**-1 is evaluated as (x)**(-1).
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Lists-6”.
1. What will be the output of the following Python code?
a=[10,23,56,[78]]
b=list(a)
a[3][0]=95
a[1]=34
print(b)
a) [10,34,56,[95]]
b) [10,23,56,[78]]
c) [10,23,56,[95]]
d) [10,34,56,[78]]
Answer: c
Explanation: The above copy is a type of shallow copy and only changes made in sublist is reflected in the copied list.
2. What will be the output of the following Python code?
print(list(zip((1,2,3),('a'),('xxx','yyy'))))
print(list(zip((2,4),('b','c'),('yy','xx'))))
a)
[(1,2,3),(‘a’),(‘xxx’,’yyy’)]
[(2,4),(‘b’,’c’),(‘yy’,’xx’)]
b)
[(1, 'a', 'xxx'),(2,’ ‘,’yyy’),(3,’ ‘,’ ‘)]
[(2, 'b', 'yy'), (4, 'c', 'xx')]
c) Syntax error
d)
[(1, 'a', 'xxx')]
[(2, 'b', 'yy'), (4, 'c', 'xx')]
Answer: d
Explanation: The zip function combines the individual attributes of the lists into a list of tuples.

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


import copy
a=[10,23,56,[78]]
b=copy.deepcopy(a)
a[3][0]=95
a[1]=34
print(b)
a) [10,34,56,[95]]
b) [10,23,56,[78]]
c) [10,23,56,[95]]
d) [10,34,56,[78]]
Answer: b
Explanation: The above copy is deepcopy. Any change made in the original list isn’t reflected.
4. What will be the output of the following Python code?
s="@"
a=list(s.partition("@"))
print(a)
b=list(s.split("@",3))
print(b)
a)
[‘a’,’b’,’c’,’d’]
[‘a’,’b’,’c’,’d’]
b)
[‘a’,’@’,’b’,’@’,’c’,’@’,’d’]
[‘a’,’b’,’c’,’d’]
c)
[‘a’,’@’,’@d’]
[‘a’,’b’,’c’,’d’]
d)
[‘a’,’@’,’@d’]
[‘a’,’@’,’b’,’@’,’c’,’@’,’d’]
Answer: c
Explanation: The partition function only splits for the first parameter along with the separator while split function splits for the
number of times given in the second argument but without the separator.

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


a=[1,2,3,4]
b=[sum(a[0:x+1]) for x in range(0,len(a))]
print(b)
a) 10
b) [1,3,5,7]
c) 4
d) [1,3,6,10]
Answer: d
Explanation: The above code returns the cumulative sum of elements in a list.
6. What will be the output of the following Python code?
a="hello"
b=list((x.upper(),len(x)) for x in a)
print(b)
a) [(‘H’, 1), (‘E’, 1), (‘L’, 1), (‘L’, 1), (‘O’, 1)]
b) [(‘HELLO’, 5)]
c) [(‘H’, 5), (‘E’, 5), (‘L’, 5), (‘L’, 5), (‘O’, 5)]
d) Syntax error
Answer: a
Explanation: Variable x iterates over each letter in string a hence the length of each letter is 1.
7. What will be the output of the following Python code?
a=[1,2,3,4]
b=[sum(a[0:x+1]) for x in range(0,len(a))]
print(b)
a) 10
b) [1,3,5,7]
c) 4
d) [1,3,6,10]
Answer: d
Explanation: The above code returns the cumulative sum of elements in a list.
8. What will be the output of the following Python code?
a=[[]]*3
a[1].append(7)
print(a)
a) Syntax error
b) [[7], [7], [7]]
c) [[7], [], []]
d) [[],7, [], []]
Answer: b
Explanation: The first line of the code creates multiple reference copies of sublist. Hence when 7 is appended, it gets appended
to all the sublists.
9. What will be the output of the following Python code?
b=[2,3,4,5]
a=list(filter(lambda x:x%2,b))
print(a)
a) [2,4]
b) [ ]
c) [3,5]
d) Invalid arguments for filter function
Answer: c
Explanation: The filter function gives value from the list b for which the condition is true, that is, x%2==1.
10. What will be the output of the following Python code?
lst=[3,4,6,1,2]
lst[1:2]=[7,8]
print(lst)
a) [3, 7, 8, 6, 1, 2]
b) Syntax error
c) [3,[7,8],6,1,2]
d) [3,4,6,7,8]
Answer: a
Explanation: In the piece of code, slice assignment has been implemented. The sliced list is replaced by the assigned elements
in the list. Type in python shell to verify.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Lists-7”.
1. What will be the output of the following Python code?
a=[1,2,3]
b=a.append(4)
print(a)
print(b)
a)
[1,2,3,4]
[1,2,3,4]
b)
[1, 2, 3, 4]
None
c) Syntax error
d)
[1,2,3]
[1,2,3,4]
Answer: b
Explanation: Append function on lists doesn’t return anything. Thus the value of b is None.

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


>>> a=[14,52,7]
>>>> b=a.copy()
>>> b is a
a) True
b) False
Answer: b
Explanation: List b is just a copy of the original list. Any copy made in list b will not be reflected in list a.
3. What will be the output of the following Python code?
a=[13,56,17]
a.append([87])
a.extend([45,67])
print(a)
a) [13, 56, 17, [87], 45, 67]
b) [13, 56, 17, 87, 45, 67]
c) [13, 56, 17, 87,[ 45, 67]]
d) [13, 56, 17, [87], [45, 67]]
Answer: a
Explanation: The append function simply adds its arguments to the list as it is while extend function extends its arguments and
later appends it.
4. What is the output of the following piece of code?
a=list((45,)*4)
print((45)*4)
print(a)
a)
180
[(45),(45),(45),(45)]
b)
(45,45,45,45)
[45,45,45,45]
c)
180
[45,45,45,45]
d) Syntax error
Answer: c
Explanation: (45) is an int while (45,) is a tuple of one element. Thus when a tuple is multiplied, it created references of itself
which is later converted to a list.
5. What will be the output of the following Python code?
lst=[[1,2],[3,4]]
print(sum(lst,[]))
a) [[3],[7]]
b) [1,2,3,4]
c) Error
d) [10]
Answer: b
Explanation: The above piece of code is used for flattening lists.
6. What will be the output of the following Python code?
word1="Apple"
word2="Apple"
list1=[1,2,3]
list2=[1,2,3]
print(word1 is word2)
print(list1 is list2)
a)
True
True
b)
False
True
c)
False
False
d)
True
False
Answer: d
Explanation: In the above case, both the lists are equivalent but not identical as they have different objects.

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


def unpack(a,b,c,d):
print(a+d)
x = [1,2,3,4]
unpack(*x)
a) Error
b) [1,4]
c) [5]
d) 5
Answer: d
Explanation: unpack(*x) unpacks the list into the separate variables. Now, a=1 and d=4. Thus 5 gets printed.
8. What will be the output of the following Python code?
places = ['Bangalore', 'Mumbai', 'Delhi']
<br class="blank" />places1 = places
places2 = places[:]
<br class="blank" />places1[1]="Pune"
places2[2]="Hyderabad"
print(places)
a) [‘Bangalore’, ‘Pune’, ‘Hyderabad’]
b) [‘Bangalore’, ‘Pune’, ‘Delhi’]
c) [‘Bangalore’, ‘Mumbai’, ‘Delhi’]
d) [‘Bangalore’, ‘Mumbai’, ‘Hyderabad’]
Answer: b
Explanation: places1 is an alias of the list places. Hence, any change made to places1 is reflected in places. places2 is a copy
of the list places. Thus, any change made to places2 isn’t reflected in places.
9. What will be the output of the following Python code?
x=[[1],[2]]
print(" ".join(list(map(str,x))))
a) [1] [2]
b) [49] [50]
c) Syntax error
d) [[1]] [[2]]
Answer: a
Explanation: The elements 1 and 2 are first put into separate lists and then combined with a space in between using the join
attribute.
10. What will be the output of the following Python code?
a=165
b=sum(list(map(int,str(a))))
print(b)
a) 561
b) 5
c) 12
d) Syntax error
Answer: c
Explanation: First, map converts the number to string and then places the individual digits in a list. Then, sum finds the sum of the
digits in the list. The code basically finds the sum of digits in the number.
11. What will be the output of the following Python code?
a= [1, 2, 3, 4, 5]
for i in range(1, 5):
a[i-1] = a[i]
for i in range(0, 5):
print(a[i],end = " ")
a) 5 5 1 2 3
b) 5 1 2 3 4
c) 2 3 4 5 1
d) 2 3 4 5 5
Answer: d
Explanation: The items having indexes from 1 to 4 are shifted forward by one index due to the first for-loop and the item of index
four is printed again because of the second for-loop.
12. What will be the output of the following Python code?
def change(var, lst):
var = 1
lst[0] = 44
k=3
a = [1, 2, 3]
change(k, a)
print(k)
print(a)
a)
3
[44, 2, 3]
b)
1
[1,2,3]
c)
3
[1,2,3]
d)
1
[44,2,3]
Answer: a
Explanation: A list is mutable, hence it’s value changes after function call. However, integer isn’t mutable. Thus its value doesn’t
change.

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


a = [1, 5, 7, 9, 9, 1]
<br class="blank" />b=a[0]
<br class="blank" />x= 0
for x in range(1, len(a)):
if a[x] > b:
b = a[x]
b= x
print(b)
a) 5
b) 3
c) 4
d) 0
Answer: c
Explanation: The above piece of code basically prints the index of the largest element in the list.
14. What will be the output of the following Python code?
a=["Apple","Ball","Cobra"]
<br class="blank" />a.sort(key=len)
print(a)
a) [‘Apple’, ‘Ball’, ‘Cobra’]
b) [‘Ball’, ‘Apple’, ‘Cobra’]
c) [‘Cobra’, ‘Apple’, ‘Ball’]
d) Invalid syntax for sort()
Answer: b
Explanation: The syntax isn’t invalid and the list is sorted according to the length of the strings in the list since key is given as len.
15. What will be the output of the following Python code?
num = ['One', 'Two', 'Three']
for i, x in enumerate(num):
print('{}: {}'.format(i, x),end=" ")
a) 1: 2: 3:
b) Exception is thrown
c) One Two Three
d) 0: One 1: Two 2: Three
Answer: d
Explanation: enumerate(iterator,start=0) is a built-in function which returns (0,lst[0]),(1,lst[1]) and so on where lst is a list(iterator).
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Matrix List Comprehension”.
1. Which of the following matrices will throw an error in Python?
a)
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
b)
B = [[3, 3, 3]
[4, 4, 4]
[5, 5, 5]]
c)
C = [(1, 2, 4),
(5, 6, 7),
(8, 9, 10)]
d)
D = [2, 3, 4,
3, 3, 3,
4, 5, 6]
Answer: b
Explanation: In matrix B will result in an error because in the absence of a comma at the end of each row, it behaves like three
separate lists. The error thrown states that the list integers must be integers or slices, not tuples.

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


A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
A[1]
a) [4, 5, 6]
b) [3, 6, 9]
c) [1, 4, 7]
d) [1, 2, 3]
Answer: a
Explanation: We can index the rows and columns using normal index operations. The statement A[1] represents the second row,
that is, the middle row. Hence the output of the code will be: [4, 5, 6].
3. Which of the following Python statements will result in the output: 6?
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
a) A[2][3]
b) A[2][1]
c) A[1][2]
d) A[3][2]
Answer: c
Explanation: The output that is required is 6, that is, row 2, item 3. This position is represented by the statement: A[1][2].
4. What will be the output of the following Python code?
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
[A[row][1] for row in (0, 1, 2)]
a) [7, 8, 9]
b) [4, 5, 6]
c) [2, 5, 8]
d) [1, 4, 7]
Answer: c
Explanation: To get a particular column as output, we can simple iterate across the rows and pull out the desired column, or
iterate through positions in rows and index as we go. Hence the output of the code shown above is: [2, 5, 8].
5. What will be the output of the following Python code?
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
[A[i][i] for i in range(len(A))]
a) [1, 5, 9]
b) [3, 5, 7]
c) [4, 5, 6]
d) [2, 5, 8]
Answer: a
Explanation: We can also perform tasks like pulling out a diagonal. The expression shown above uses range to generate the list
of offsets and the indices with the row and column the same, picking out A[0][0], then A[1][1] and so on. Hence the output of the
code is: [1, 5, 9].
6. What will be the output of the following Python code?
l=[[1, 2, 3], [4, 5, 6]]
for i in range(len(l)):
for j in range(len(l[i])):
l[i][j]+=10
l
a) No output
b) Error
c) [[1, 2, 3], [4, 5, 6]]
d) [[11, 12, 13], [14, 15, 16]]
Answer: d
Explanation: We use range twice if the shapes differ. Each element of list l is increased by 10. Hence the output is: [[11, 12, 13],
[14, 15, 16]]
7. What will be the output of the following Python code?
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

[[col + 10 for col in row] for row in A]


a) [[11, 12, 13], [14, 15, 16], [17, 18, 19]]
b) Error
c) [11, 12, 13], [14, 15, 16], [17, 18, 19]
d) [11, 12, 13, 14, 15, 16, 17, 18, 19]
Answer: a
Explanation: The code shown above shows a list comprehension which adds 10 to each element of the matrix A and prints it
row-wise. Hence the output of the code is: [[11, 12, 13], [14, 15, 16], [17, 18, 19]]
8. What will be the output of the following Python code?
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
[A[i][len(A)-1-i] for i in range(len(A))]
a) [1, 5, 9]
b) [4, 5, 6]
c) [3, 5, 7]
d) [2, 5, 8]
Answer: c
Explanation: This expression scales the common index to fetch A[0][2], A[1][1], etc. We assume the matrix has the same number
of rows and columns.
9. What will be the output of the following Python code?
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
B = [[3, 3, 3],
[4, 4, 4],
[5, 5, 5]]
[B[row][col]*A[row][col] for row in range(3) for col in range(3)]
a) [3, 6, 9, 16, 20, 24, 35, 40, 45]
b) Error
c) [0, 30, 60, 120, 160, 200, 300, 350, 400]
d) 0
Answer: a
Explanation: In the code shown above, we have used list comprehension to combine values of multiple matrices. We have
multiplied the elements of the matrix B with that of the matrix A, in the range(3). Hence the output of this code is: [3, 6, 9, 16, 20,
24, 35, 40, 45].
10. What will be the output of the following Python code?
r = [11, 12, 13, 14, 15, 16, 17, 18, 19]
A = [[0, 10, 20],
[30, 40, 50],
[60, 70, 80]]
for row in A:
for col in row:
r.append(col+10)
r
a) [11, 12, 13, 14, 15, 16, 17, 18, 19, 10, 20, 30, 40, 50, 60, 70, 80, 90]
b) [10, 20, 30, 40, 50, 60, 70, 80, 90]
c) [11, 12, 13, 14, 15, 16, 17, 18, 19]
d) [0, 10, 20, 30, 40, 50, 60, 70, 80]
Answer: a
Explanation: The code shown above adds 10 to each element of the matrix and prints the output row-wise. Since the list l already
contains some elements, the new elements are appended to it. Hence the output of this code is: [11, 12, 13, 14, 15, 16, 17, 18,
19, 10, 20, 30, 40, 50, 60, 70, 80, 90].
11. What will be the output of the following Python code?
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
B = [[3, 3, 3],
[4, 4, 4],
[5, 5, 5]]
[[col1 * col2 for (col1, col2) in zip(row1, row2)] for (row1, row2) in zip(A, B)]
a) [0, 30, 60, 120, 160, 200, 300, 350, 400]
b) [[3, 6, 9], [16, 20, 24], [35, 40, 45]]
c) No output
d) Error
Answer: b
Explanation: The list comprehension shown above results in the output: [[3, 6, 9], [16, 20, 24], [35, 40, 45]].
12. What will be the output of the following Python code?
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
B = [[3, 3, 3],
[4, 4, 4],
[5, 5, 5]]
zip(A, B)
a) Address of the zip object
b) Address of the matrices A and B
c) No output
d) [3, 6, 9, 16, 20, 24, 35, 40, 45]
Answer: a
Explanation: The output of the code shown above returns the address of the zip object. If we print it in the form of a list, we get:
>>> list(zip(A, B))
[([1, 2, 3], [3, 3, 3]), ([4, 5, 6], [4, 4, 4]), ([7, 8, 9], [5, 5, 5])]
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Python Modules”.
1. Which of these definitions correctly describes a module?
a) Denoted by triple quotes for providing the specification of certain program elements
b) Design and implementation of specific functionality to be incorporated into a program
c) Defines the specification of how it is to be used
d) Any program that reuses code
Answer: b
Explanation: The term “module” refers to the implementation of specific functionality to be incorporated into a program.
2. Which of the following is not an advantage of using modules?
a) Provides a means of reuse of program code
b) Provides a means of dividing up tasks
c) Provides a means of reducing the size of the program
d) Provides a means of testing individual parts of the program
Answer: c
Explanation: The total size of the program remains the same regardless of whether modules are used or not. Modules simply
divide the program.
3. Program code making use of a given module is called a ______ of the module.
a) Client
b) Docstring
c) Interface
d) Modularity
Answer: a
Explanation: Program code making use of a given module is called the client of the module. There may be multiple clients for a
module.
4. ______ is a string literal denoted by triple quotes for providing the specifications of certain program elements.
a) Interface
b) Modularity
c) Client
d) Docstring
Answer: d
Explanation: Docstring used for providing the specifications of program elements.
5. Which of the following is true about top-down design process?
a) The details of a program design are addressed before the overall design
b) Only the details of the program are addressed
c) The overall design of the program is addressed before the details
d) Only the design of the program is addressed
Answer: c
Explanation: Top-down design is an approach for deriving a modular design in which the overall design.
6. In top-down design every module is broken into same number of submodules.
a) True
b) False
Answer: b
Explanation: In top-down design every module can even be broken down into different number of submodules.
7. All modular designs are because of a top-down design process.
a) True
b) False
Answer: b
Explanation: The details of the program can be addressed before the overall design too. Hence, all modular designs are not
because of a top-down design process.
8. What will be the output of the following Python code?
#mod1
def change(a):
b=[x*2 for x in a]
print(b)
#mod2
def change(a):
b=[x*x for x in a]
print(b)
from mod1 import change
from mod2 import change
#main
s=[1,2,3]
change(s)
a) [2,4,6]
b) [1,4,9]
c)
[2,4,6]
[1,4,9]
d) There is a name clash
Answer: d
Explanation: A name clash is when two different entities with the same identifier become part of the same scope. Since both the
modules have the same function name, there is a name clash.
9. Which of the following isn’t true about main modules?
a) When a python file is directly executed, it is considered main module of a program
b) Main modules may import any number of modules
c) Special name given to main modules is: __main__
d) Other main modules can import main modules
Answer: d
Explanation: Main modules are not meant to be imported into other modules.
10. Which of the following is not a valid namespace?
a) Global namespace
b) Public namespace
c) Built-in namespace
d) Local namespace
Answer: b
Explanation: During a Python program execution, there are as many as three namespaces – built-in namespace, global
namespace and local namespace.
11. Which of the following is false about “import modulename” form of import?
a) The namespace of imported module becomes part of importing module
b) This form of import prevents name clash
c) The namespace of imported module becomes available to importing module
d) The identifiers in module are accessed as: modulename.identifier
Answer: a
Explanation: In the “import modulename” form of import, the namespace of imported module becomes available to, but not part
of, the importing module.
12. Which of the following is false about “from-import” form of import?
a) The syntax is: from modulename import identifier
b) This form of import prevents name clash
c) The namespace of imported module becomes part of importing module
d) The identifiers in module are accessed directly as: identifier
Answer: b
Explanation: In the “from-import” form of import, there may be name clashes because names of the imported identifiers aren’t
specified along with the module name.
13. Which of the statements about modules is false?
a) In the “from-import” form of import, identifiers beginning with two underscores are private and aren’t imported
b) dir() built-in function monitors the items in the namespace of the main module
c) In the “from-import” form of import, all identifiers regardless of whether they are private or public are imported
d) When a module is loaded, a compiled version of the module with file extension .pyc is automatically produced
Answer: c
Explanation: In the “from-import” form of import, identifiers beginning with two underscores are private and aren’t imported.
14. What will be the output of the following Python code?
from math import factorial
print(math.factorial(5))
a) 120
b) Nothing is printed
c) Error, method factorial doesn’t exist in math module
d) Error, the statement should be: print(factorial(5))
Answer: d
Explanation: In the “from-import” form of import, the imported identifiers (in this case factorial()) aren’t specified along with the
module name.
15. What is the order of namespaces in which Python looks for an identifier?
a) Python first searches the global namespace, then the local namespace and finally the built-in namespace
b) Python first searches the local namespace, then the global namespace and finally the built-in namespace
c) Python first searches the built-in namespace, then the global namespace and finally the local namespace
d) Python first searches the built-in namespace, then the local namespace and finally the global namespace
Answer: b
Explanation: Python first searches for the local, then the global and finally the built-in namespace.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Numeric Types”.
1. What is the output of print 0.1 + 0.2 == 0.3?
a) True
b) False
c) Machine dependent
d) Error
Answer: b
Explanation: Neither of 0.1, 0.2 and 0.3 can be represented accurately in binary. The round off errors from 0.1 and 0.2
accumulate and hence there is a difference of 5.5511e-17 between (0.1 + 0.2) and 0.3.
2. Which of the following is not a complex number?
a) k = 2 + 3j
b) k = complex(2, 3)
c) k = 2 + 3l
d) k = 2 + 3J
Answer: c
Explanation: l (or L) stands for long.
3. What is the type of inf?
a) Boolean
b) Integer
c) Float
d) Complex
Answer: c
Explanation: Infinity is a special case of floating point numbers. It can be obtained by float(‘inf’).
4. What does ~4 evaluate to?
a) -5
b) -4
c) -3
d) +3
Answer: a
Explanation: ~x is equivalent to -(x+1).
5. What does ~~~~~~5 evaluate to?
a) +5
b) -11
c) +11
d) -5
Answer: a
Explanation: ~x is equivalent to -(x+1).
~~x = – (-(x+1) + 1) = (x+1) – 1 = x
~~x is equivalent to x
Extrapolating further ~~~~~~x would be same as x in the final result.
In the question, x value is given as 5 and “~” is repeated 6 times. So, the correct answer for “~~~~~~5” is 5.
6. Which of the following is incorrect?
a) x = 0b101
b) x = 0x4f5
c) x = 19023
d) x = 03964
Answer: d
Explanation: Numbers starting with a 0 are octal numbers but 9 isn’t allowed in octal numbers.
7. What is the result of cmp(3, 1)?
a) 1
b) 0
c) True
d) False
Answer: a
Explanation: cmp(x, y) returns 1 if x > y, 0 if x == y and -1 if x < y.
8. Which of the following is incorrect?
a) float(‘inf’)
b) float(‘nan’)
c) float(’56’+’78’)
d) float(’12+34′)
Answer: d
Explanation: ‘+’ cannot be converted to a float.
9. What is the result of round(0.5) – round(-0.5)?
a) 1.0
b) 2.0
c) 0.0
d) Value depends on Python version
Answer: d
Explanation: The behavior of the round() function is different in Python 2 and Python 3. In Python 2, it rounds off numbers away
from 0 when the number to be rounded off is exactly halfway through. round(0.5) is 1 and round(-0.5) is -1 whereas in Python 3, it
rounds off numbers towards nearest even number when the number to be rounded off is exactly halfway through. See the below
output.
Here’s the runtime output for Python version 2.7 interpreter.
$ python
Python 2.7.17 (default, Nov 7 2019, 10:07:09)
>>> round(0.5)
1.0
>>> round(-0.5)
-1.0
>>>
In the above output, you can see that the round() functions on 0.5 and -0.5 are moving away from 0 and hence “ round(0.5) –
(round(-0.5)) = 1 – (-1) = 2 ”
Here’s the runtime output for Python version 3.6 interpreter.
$ python3
Python 3.6.8 (default, Oct 7 2019, 12:59:55)
>>> round(0.5)
0
>>> round(-0.5)
0
>>> round(2.5)
2
>>> round(3.5)
4
>>>
In the above output, you can see that the round() functions on 0.5 and -0.5 are moving towards 0 and hence “ round(0.5) –
(round(-0.5)) = 0 – 0 = 0 “. Also note that the round(2.5) is 2 (which is an even number) whereas round(3.5) is 4 (which is an
even number).
10. What does 3 ^ 4 evaluate to?
a) 81
b) 12
c) 0.75
d) 7
Answer: d
Explanation: ^ is the Binary XOR operator.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Pickle Module”.
1. The process of pickling in Python includes:
a) conversion of a list into a datatable
b) conversion of a byte stream into Python object hierarchy
c) conversion of a Python object hierarchy into byte stream
d) conversion of a datatable into a list
Answer: c
Explanation: Pickling is the process of sterilizing a Python object, that is, conversion of a byte stream into Python object
hierarchy. The reverse of this process is known as unpickling.
2. To sterilize an object hierarchy, the _____________ function must be called. To desterilize a data stream, the
______________ function must be called.
a) dumps(), undumps()
b) loads(), unloads()
c) loads(), dumps()
d) dumps(), loads()
Answer: d
Explanation: To sterilize an object hierarchy, the dumps() function must be called. To desterilize a data stream, the loads function
must be called.
3. Pick the correct statement regarding pickle and marshal modules.
a) The pickle module supports primarily .pyc files whereas marshal module is used to sterilize Python objects
b) The pickle module keeps track of the objects that have already been sterilized whereas the marshal module does not do this
c) The pickle module cannot be used to sterilize user defined classes and their instances whereas marshal module can be used
to perform this task
d) The format of sterilization of the pickle module is not guaranteed to be supported across all versions of Python. The marshal
module sterilization is compatible across all the versions of Python
Answer: b
Explanation: The correct statement from among the above options is that the python module keeps track of the objects that have
already been sterilized whereas the marshal module does not do this. The rest of the statements are incorrect.
4. What will be the output of the following Python code?
pickle.HIGHEST_PROTOCOL
a) 4
b) 5
c) 3
d) 6
Answer: a
Explanation: There are five protocol versions available of the pickle module, namely, 0, 1, 2, 3 and 4. In the code shown above,
the highest protocol version is returned, that is, 4.
5. Which of the following Python codes will result in an error?
object = ‘a’
a) >>> pickle.dumps(object)
b) >>> pickle.dumps(object, 3)
c) >>> pickle.dumps(object, 3, True)
d) >>> pickle.dumps(‘a’, 2)
Answer: c
Explanation: The function pickle.dumps requires either 1 or 2 arguments. If any other number of arguments are passed to it, it
results in an error. An error is thrown even when no arguments are passed to it.
6. Which of the following functions can be used to find the protocol version of the pickle module currently being used?
a) pickle.DEFAULT
b) pickle.CURRENT
c) pickle.CURRENT_PROTOCOL
d) pickle.DEFAULT_PROTOCOL
Answer: d
Explanation: The function pickle.DEFAULT_PROTOCOL can be used to find the protocol version of the pickle module currently
being used by the system.
7. The output of the following two Python codes is exactly the same.
object
'a'
CODE 1
>>> pickle.dumps('a', 3)
CODE 2
>>> pickle.dumps(object, 3)
a) True
b) False
Answer: a
Explanation: The two codes shown above result in the same output, that is, b’\x80\x03X\x01\x00\x00\x00aq\x00.’ Hence this
statement is true.
8. Which of the following functions can accept more than one positional argument?
a) pickle.dumps
b) pickle.loads
c) pickle.dump
d) pickle.load
Answer: a
Explanation: The functions pickle.loads, pickle.dump and pickle.load accept only one argument. The function pickle.dumps can
accept more than one argument.
9. Which of the following functions raises an error when an unpicklable object is encountered by Pickler?
a) pickle.PickleError
b) pickle.PicklingError
c) pickle.UnpickleError
d) pickle.UnpicklingError
Answer: b
Explanation: The function pickle.PicklingError raises an error when an unpickable object is encountered by Pickler.
10. The pickle module defines ______ exceptions and exports _______ classes.
a) 2, 3
b) 3, 4
c) 3, 2
d) 4, 3
Answer: c
Explanation: The pickle module defines three exceptions, namely, pickle.PickleError, pickle.PicklingError, pickle.UnpickleError
and exports two classes, namely, pickle.Pickler and pickle.Unpickler.
11. Which of the following cannot be pickled?
a) Functions which are defined at the top level of a module with lambda
b) Functions which are defined at the top level of a module with def
c) Built-in functions which are defined at the top level of a module
d) Classes which are defined at the top level of a module
Answer: a
Explanation: Functions which are defined at the top level of a module with lambda cannot be pickled.
12. If __getstate__() returns _______________ the __setstate__() module will not be called on pickling.
a) True value
b) False value
c) ValueError
d) OverflowError
Answer: b
Explanation: If getstate__() returns a false value, the __setstate__() module will not be called on pickling.
13. Lambda functions cannot be pickled because:
a) Lambda functions only deal with binary values, that is, 0 and 1
b) Lambda functions cannot be called directly
c) Lambda functions cannot be identified by the functions of the pickle module
d) All lambda functions have the same name, that is, <lambda>
Answer: d
Explanation: Lambda functions cannot be pickled because all the lambda functions have the same name, that is, <lambda>
14. The module _______________ is a comparatively faster implementation of the pickle module.
a) cPickle
b) nPickle
c) gPickle
d) tPickle
Answer: a
Explanation: The module cPickle is a comparatively faster implementation of the pickle module.
15. The copy module uses the ___________________ protocol for shallow and deep copy.
a) pickle
b) marshal
c) shelve
d) copyreg
Answer: a
Explanation: The copy module uses the pickle protocol for shallow and deep copy.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Polymorphism”.
1. Which of the following best describes polymorphism?
a) Ability of a class to derive members of another class as a part of its own definition
b) Means of bundling instance variables and methods in order to restrict access to certain class members
c) Focuses on variables and passing of variables to functions
d) Allows for objects of different types and behaviour to be treated as the same general type
Answer: d
Explanation: Polymorphism is a feature of object-oriented programming languages. It allows for the implementation of elegant
software that is well designed and easily modified.
2. What is the biggest reason for the use of polymorphism?
a) It allows the programmer to think at a more abstract level
b) There is less program code to write
c) The program will have a more elegant design and will be easier to maintain and update
d) Program code takes up less space
Answer: c
Explanation: Polymorphism allows for the implementation of elegant software.
3. What is the use of duck typing?
a) More restriction on the type values that can be passed to a given method
b) No restriction on the type values that can be passed to a given method
c) Less restriction on the type values that can be passed to a given method
d) Makes the program code smaller
Answer: c
Explanation: In Python, any set of classes with a common set of methods can be treated similarly. This is called duck typing.
Hence duck typing imposes less restrictions.
4. What will be the output of the following Python code?
class A:
def __str__(self):
return '1'
class B(A):
def __init__(self):
super().__init__()
class C(B):
def __init__(self):
super().__init__()
def main():
obj1 = B()
obj2 = A()
obj3 = C()
print(obj1, obj2,obj3)
main()
a) 1 1 1
b) 1 2 3
c) ‘1’ ‘1’ ‘1’
d) An exception is thrown
Answer: a
Explanation: The super().__init__() in the subclasses has been properly invoked and none of other subclasses return any other
value. Hence 1 is returned each time the object is created and printed.
5. What will be the output of the following Python code?
class Demo:
def __init__(self):
self.x = 1
def change(self):
self.x = 10
class Demo_derived(Demo):
def change(self):
self.x=self.x+1
return self.x
def main():
obj = Demo_derived()
print(obj.change())

main()
a) 11
b) 2
c) 1
d) An exception is thrown
Answer: b
Explanation: The derived class method change() overrides the base class method.
6. A class in which one or more methods are only implemented to raise an exception is called an abstract class.
a) True
b) False
Answer: a
Explanation: A class in which one or more methods are unimplemented or implemented for the methods throw an exception is
called an abstract class.
7. Overriding means changing behaviour of methods of derived class methods in the base class.
a) True
b) False
Answer: b
Explanation: Overriding means if there are two same methods present in the superclass and the subclass, the contents of the
subclass method are executed.
8. What will be the output of the following Python code?
class A:
def __repr__(self):
return "1"
class B(A):
def __repr__(self):
return "2"
class C(B):
def __repr__(self):
return "3"
o1 = A()
o2 = B()
o3 = C()
print(obj1, obj2, obj3)
a) 1 1 1
b) 1 2 3
c) ‘1’ ‘1’ ‘1’
d) An exception is thrown
Answer: b
Explanation: When different objects are invoked, each of the individual classes return their individual values and hence it is
printed.
9. What will be the output of the following Python code?
class A:
def __init__(self):
self.multiply(15)
print(self.i)

def multiply(self, i):


self.i = 4 * i;
class B(A):
def __init__(self):
super().__init__()

def multiply(self, i):


self.i = 2 * i;
obj = B()
a) 15
b) 60
c) An exception is thrown
d) 30
Answer: d
Explanation: The derived class B overrides base class A.
10. What will be the output of the following Python code?
class Demo:
def check(self):
return " Demo's check "
def display(self):
print(self.check())
class Demo_Derived(Demo):
def check(self):
return " Derived's check "
Demo().display()
Demo_Derived().display()
a) Demo’s check Derived’s check
b) Demo’s check Demo’s check
c) Derived’s check Demo’s check
d) Syntax error
Answer: a
Explanation: Demo().display() invokes the display() method in class Demo and Demo_Derived().display() invokes the display()
method in class Demo_Derived.
11. What will be the output of the following Python code?
class A:
def __init__(self):
self.multiply(15)
def multiply(self, i):
self.i = 4 * i;
class B(A):
def __init__(self):
super().__init__()
print(self.i)

def multiply(self, i):


self.i = 2 * i;
obj = B()
a) 15
b) 30
c) An exception is thrown
d) 60
Answer: b
Explanation: The derived class B overrides base class A.
12. What will be the output of the following Python code?
class Demo:
def __check(self):
return " Demo's check "
def display(self):
print(self.check())
class Demo_Derived(Demo):
def __check(self):
return " Derived's check "
Demo().display()
Demo_Derived().display()
a) Demo’s check Derived’s check
b) Demo’s check Demo’s check
c) Derived’s check Demo’s check
d) Syntax error
Answer: b
Explanation: The method check is private so it can’t be accessed by the derived class. Execute the code in the Python shell.
13. What will be the output of the following Python code?
class A:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 1
def __eq__(self, other):
return self.x * self.y == other.x * other.y
obj1 = A(5, 2)
obj2 = A(2, 5)
print(obj1 == obj2)
a) False
b) 1
c) True
d) An exception is thrown
Answer: c
Explanation: Since 5*2==2*5, True is printed. Execute it in the Python shell to verify.
14. What will be the output of the following Python code?
class A:
def one(self):
return self.two()
def two(self):
return 'A'
class B(A):
def two(self):
return 'B'
obj2=B()
print(obj2.two())
a) A
b) An exception is thrown
c) A B
d) B
Answer: d
Explanation: The derived class method two() overrides the method two() in the base class A.
15. Which of the following statements is true?
a) A non-private method in a superclass can be overridden
b) A subclass method can be overridden by the superclass
c) A private method in a superclass can be overridden
d) Overriding isn’t possible in Python
Answer: a
Explanation: A public method in the base class can be overridden by the same named method in the subclass.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Precedence and Associativity – 1”.
1. The value of the expressions 4/(3*(2-1)) and 4/3*(2-1) is the same.
a) True
b) False
Answer: a
Explanation: Although the presence of parenthesis does affect the order of precedence, in the case shown above, it is not
making a difference. The result of both of these expressions is 1.333333333. Hence the statement is true.
2. What will be the value of the following Python expression?
4+3%5
a) 4
b) 7
c) 2
d) 0
Answer: b
Explanation: The order of precedence is: %, +. Hence the expression above, on simplification results in 4 + 3 = 7. Hence the
result is 7.
3. Evaluate the expression given below if A = 16 and B = 15.
A % B // A
a) 0.0
b) 0
c) 1.0
d) 1
Answer: b
Explanation: The above expression is evaluated as: 16%15//16, which is equal to 1//16, which results in 0.
4. Which of the following operators has its associativity from right to left?
a) +
b) //
c) %
d) **
Answer: d
Explanation: All of the operators shown above have associativity from left to right, except exponentiation operator (**) which has
its associativity from right to left.
5. What will be the value of x in the following Python expression?
x = int(43.55+2/2)
a) 43
b) 44
c) 22
d) 23
Answer: b
Explanation: The expression shown above is an example of explicit conversion. It is evaluated as int(43.55+1) = int(44.55) = 44.
Hence the result of this expression is 44.
6. What is the value of the following expression?
2+4.00, 2**4.0
a) (6.0, 16.0)
b) (6.00, 16.00)
c) (6, 16)
d) (6.00, 16.0)
Answer: a
Explanation: The result of the expression shown above is (6.0, 16.0). This is because the result is automatically rounded off to
one decimal place.
7. Which of the following is the truncation division operator?
a) /
b) %
c) //
d) |
Answer: c
Explanation: // is the operator for truncation division. It is called so because it returns only the integer part of the quotient,
truncating the decimal part. For example: 20//3 = 6.
8. What are the values of the following Python expressions?
2**(3**2)
(2**3)**2
2**3**2
a) 64, 512, 64
b) 64, 64, 64
c) 512, 512, 512
d) 512, 64, 512
Answer: d
Explanation: Expression 1 is evaluated as: 2**9, which is equal to 512. Expression 2 is evaluated as 8**2, which is equal to 64.
The last expression is evaluated as 2**(3**2). This is because the associativity of ** operator is from right to left. Hence the result
of the third expression is 512.
9. What is the value of the following expression?
8/4/2, 8/(4/2)
a) (1.0, 4.0)
b) (1.0, 1.0)
c) (4.0. 1.0)
d) (4.0, 4.0)
Answer: a
Explanation: The above expressions are evaluated as: 2/2, 8/2, which is equal to (1.0, 4.0).
10. What is the value of the following expression?
float(22//3+3/3)
a) 8
b) 8.0
c) 8.3
d) 8.33
Answer: b
Explanation: The expression shown above is evaluated as: float( 7+1) = float(8) = 8.0. Hence the result of this expression is 8.0.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Precedence and Associativity – 2”.
1. What will be the output of the following Python expression?
print(4.00/(2.0+2.0))
a) Error
b) 1.0
c) 1.00
d) 1
Answer: b
Explanation: The result of the expression shown above is 1.0 because print rounds off digits.
2. What will be the value of X in the following Python expression?
X = 2+9*((3*12)-8)/10
a) 30.0
b) 30.8
c) 28.4
d) 27.2
Answer: d
Explanation: The expression shown above is evaluated as: 2+9*(36-8)/10, which simplifies to give 2+9*(2.8), which is equal to
2+25.2 = 27.2. Hence the result of this expression is 27.2.
3. Which of the following expressions involves coercion when evaluated in Python?
a) 4.7 – 1.5
b) 7.9 * 6.3
c) 1.7 % 2
d) 3.4 + 4.6
Answer: c
Explanation: Coercion is the implicit (automatic) conversion of operands to a common type. Coercion is automatically performed
on mixed-type expressions. The expression 1.7 % 2 is evaluated as 1.7 % 2.0 (that is, automatic conversion of int to float).
4. What will be the output of the following Python expression?
24//6%3, 24//4//2
a) (1,3)
b) (0,3)
c) (1,0)
d) (3,1)
Answer: a
Explanation: The expressions are evaluated as: 4%3 and 6//2 respectively. This results in the answer (1,3). This is because the
associativity of both of the expressions shown above is left to right.
5. Which among the following list of operators has the highest precedence?
+, -, **, %, /, <<, >>, |
a) <<, >>
b) **
c) |
d) %
Answer: b
Explanation: The highest precedence is that of the exponentiation operator, that is of **.
6. What will be the value of the following Python expression?
float(4+int(2.39)%2)
a) 5.0
b) 5
c) 4.0
d) 4
Answer: c
Explanation: The above expression is an example of explicit conversion. It is evaluated as: float(4+int(2.39)%2) = float(4+2%2) =
float(4+0) = 4.0. Hence the result of this expression is 4.0.
7. Which of the following expressions is an example of type conversion?
a) 4.0 + float(3)
b) 5.3 + 6.3
c) 5.0 + 3
d) 3 + 7
Answer: a
Explanation: Type conversion is nothing but explicit conversion of operands to a specific type. Options 5.3 + 6.3 and 5.0 + 3 are
examples of implicit conversion whereas option 4.0 + float(3) is an example of explicit conversion or type conversion.
8. Which of the following expressions results in an error?
a) float(‘10’)
b) int(‘10’)
c) float(’10.8’)
d) int(’10.8’)
Answer: d
Explanation: All of the above examples show explicit conversion. However the expression int(’10.8’) results in an error.
9. What will be the value of the following Python expression?
4+2**5//10
a) 3
b) 7
c) 77
d) 0
Answer: b
Explanation: The order of precedence is: **, //, +. The expression 4+2**5//10 is evaluated as 4+32//10, which is equal to 4+3 = 7.
Hence the result of the expression shown above is 7.
10. The expression 2**2**3 is evaluates as: (2**2)**3.
a) True
b) False
Answer: b
Explanation: The value of the expression (2**2)**3 = 4**3 = 64. When the expression 2**2**3 is evaluated in python, we get the
result as 256, because this expression is evaluated as 2**(2**3). This is because the associativity of exponentiation operator (**)
is from right to left and not from left to right.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Random module – 1”.
1. To include the use of functions which are present in the random library, we must use the option:
a) import random
b) random.h
c) import.random
d) random.random
Answer: a
Explanation: The command import random is used to import the random module, which enables us to use the functions which
are present in the random library.
2. The output of the following Python code is either 1 or 2.
import random
random.randint(1,2)
a) True
b) False
Answer: a
Explanation: The function random.randint(a,b) helps us to generate an integer between ‘a’ and ‘b’, including ‘a’ and ‘b’. In this
case, since there are no integers between 1 and 2, the output will necessarily be either 1 or 2’.
3. What will be the output of the following Python code?
import random
random.choice(2,3,4)
a) An integer other than 2, 3 and 4
b) Either 2, 3 or 4
c) Error
d) 3 only
Answer: c
Explanation: The code shown above displays the incorrect syntax of the function random.choice(). This functions takes its
numeric parameter in the form of a list. Hence the correct syntax world be: random.choice([2,3,4]).
4. What will be the output of the following Python code?
import random
random.choice([10.4, 56.99, 76])
a) Error
b) Either 10.4, 56.99 or 76
c) Any number other than 10.4, 56.99 and 76
d) 56.99 only
Answer: b
Explanation: The function random.choice(a,b,c,d) returns a random number which is selected from a, b, c and d. The output can
be either a, b, c or d. Hence the output of the snippet of code shown above can be either 10.4, 56.99 or 76.
5. What will be the output of the following Python function (random module has already been imported)?
random.choice('sun')
a) sun
b) u
c) either s, u or n
d) error
Answer: c
Explanation: The above function works with alphabets just as it does with numbers. The output of this expression will be either s,
u or n.
6. What will be the output of the following Python function, assuming that the random module has already been imported?
random.uniform(3,4)
a) Error
b) Either 3 or 4
c) Any integer other than 3 and 4
d) Any decimal value between 3 and 4
Answer: d
Explanation: This question depicts the basic difference between the functions random.randint(a, b) and random.uniform(a, b).
While random.randint(a,b) generates an integer between ‘a’ and ‘b’, including ‘a’ and ‘b’, the function random.uniform(a,b)
generates a decimal value between ‘a’ and ‘b’.
7. What will be the output of the following Python function if the random module has already been imported?
random.randint(3.5,7)
a) Error
b) Any integer between 3.5 and 7, including 7
c) Any integer between 3.5 and 7, excluding 7
d) The integer closest to the mean of 3.5 and 7
Answer: a
Explanation: The function random.randint() does not accept a decimal value as a parameter. Hence the function shown above
will throw an error.
8. Which of the following functions helps us to randomize the items of a list?
a) seed
b) randomise
c) shuffle
d) uniform
Answer: c
Explanation: The function shuffle, which is included in the random module, helps us to randomize the items of a list. This function
takes the list as a parameter.
9. What will be the output of the following Python code?
random.seed(3)
random.randint(1,5)
2
random.seed(3)
random.randint(1,5)
a) 3
b) 2
c) Any integer between 1 and 5, including 1 and 5
d) Any integer between 1 and 5, excluding 1 and 5
Answer: b
Explanation: We use the seed function when we want to use the same random number once again in our program. Hence the
output of the code shown above will be 2, since 2 was generated previously following which we used the seed function.
10. What is the interval of the value generated by the function random.random(), assuming that the random module has already
been imported?
a) (0,1)
b) (0,1]
c) [0,1]
d) [0,1)
Answer: d
Explanation: The function random.random() generates a random value in the interval [0,1), that is, including zero but excluding
one.
11. What will be the output of the following Python code?
random.randrange(0,91,5)
a) 10
b) 18
c) 79
d) 95
Answer: a
Explanation: The function shown above will generate an output which is a multiple of 5 and is between 0 and 91. The only option
which satisfies these criteria is 10. Hence the only possible output of this function is 10.
12. Both the functions randint and uniform accept ____________ parameters.
a) 0
b) 1
c) 3
d) 2
Answer: d
Explanation: Both of these functions, that is, randint and uniform are included in the random module and both of these functions
accept 2 parameters. For example: random.uniform(a,b) where ‘a’ and ‘b’ specify the range.
13. The randrange function returns only an integer value.
a) True
b) False
Answer: a
Explanation: The function randrange returns only an integer value. Hence this statement is true.
14. What will be the output of the following Python code?
random.randrange(1,100,10)
a) 32
b) 67
c) 91
d) 80
Answer: c
Explanation: The output of this function can be any value which is a multiple of 10, plus 1. Hence a value like 11, 21, 31, 41…91
can be the output. Also, the value should necessarily be between 1 and 100. The only option which satisfies this criteria is 91.
15. What will be the output of the following Python function, assuming that the random library has already been included?
random.shuffle[1,2,24]
a) Randomized list containing the same numbers in any order
b) The same list, that is [1,2,24]
c) A list containing any random numbers between 1 and 24
d) Error
Answer: d
Explanation: The function shown above will result in an error because this is the incorrect syntax for the usage of the function
shuffle(). The list should be previously declared and then passed to this function to get an output.
An example of the correct syntax:
>>> l=['a','b','c','d']
>>> random.shuffle(l)
>>> print(l)
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Recursion”.
1. Which is the most appropriate definition for recursion?
a) A function that calls itself
b) A function execution instance that calls another execution instance of the same function
c) A class method that calls another class method
d) An in-built method that is automatically called
Answer: b
Explanation: The appropriate definition for a recursive function is a function execution instance that calls another execution
instance of the same function either directly or indirectly.
2. Only problems that are recursively defined can be solved using recursion.
a) True
b) False
Answer: b
Explanation: There are many other problems can also be solved using recursion.
3. Which of these is false about recursion?
a) Recursive function can be replaced by a non-recursive function
b) Recursive functions usually take more memory space than non-recursive function
c) Recursive functions run faster than non-recursive function
d) Recursion makes programs easier to understand
Answer: c
Explanation: The speed of a program using recursion is slower than the speed of its non-recursive equivalent.
4. Fill in the line of the following Python code for calculating the factorial of a number.
def fact(num):
if num == 0:
return 1
else:
return _____________________
a) num*fact(num-1)
b) (num-1)*(num-2)
c) num*(num-1)
d) fact(num)*fact(num-1)
Answer: a
Explanation: Suppose n=5 then, 5*4*3*2*1 is returned which is the factorial of 5.
5. What will be the output of the following Python code?
def test(i,j):
if(i==0):
return j
else:
return test(i-1,i+j)
print(test(4,7))
a) 13
b) 7
c) Infinite loop
d) 17
Answer: d
Explanation: The test(i-1,i+j) part of the function keeps calling the function until the base condition of the function is satisfied.
6. What will be the output of the following Python code?
l=[]
def convert(b):
if(b==0):
return l
dig=b%2
l.append(dig)
convert(b//2)
convert(6)
l.reverse()
for i in l:
print(i,end="")
a) 011
b) 110
c) 3
d) Infinite loop
Answer: b
Explanation: The above code gives the binary equivalent of the number.
7. What is tail recursion?
a) A recursive function that has two base cases
b) A function where the recursive functions leads to an infinite loop
c) A recursive function where the function doesn’t return anything and just prints the values
d) A function where the recursive call is the last thing executed by the function
Answer: d
Explanation: A recursive function is tail recursive when recursive call is executed by the function in the last.
8. Observe the following Python code?
def a(n):
if n == 0:
return 0
else:
return n*a(n - 1)
def b(n, tot):
if n == 0:
return tot
else:
return b(n-2, tot-2)
a) Both a() and b() aren’t tail recursive
b) Both a() and b() are tail recursive
c) b() is tail recursive but a() isn’t
d) a() is tail recursive but b() isn’t
Answer: c
Explanation: A recursive function is tail recursive when recursive call is executed by the function in the last.
9. Which of the following statements is false about recursion?
a) Every recursive function must have a base case
b) Infinite recursion can occur if the base case isn’t properly mentioned
c) A recursive function makes the code easier to understand
d) Every recursive function must have a return value
Answer: d
Explanation: A recursive function needn’t have a return value.
10. What will be the output of the following Python code?
def fun(n):
if (n > 100):
return n - 5
return fun(fun(n+11));

print(fun(45))
a) 50
b) 100
c) 74
d) Infinite loop
Answer: b
Explanation: The fun(fun(n+11)) part of the code keeps executing until the value of n becomes greater than 100, after which n-5 is
returned and printed.
11. Recursion and iteration are the same programming approach.
a) True
b) False
Answer: b
Explanation: In recursion, the function calls itself till the base condition is reached whereas iteration means repetition of process
for example in for-loops.
12. What happens if the base condition isn’t defined in recursive programs?
a) Program gets into an infinite loop
b) Program runs once
c) Program runs n number of times where n is the argument given to the function
d) An exception is thrown
Answer: a
Explanation: The program will run until the system gets out of memory.
13. Which of these is not true about recursion?
a) Making the code look clean
b) A complex task can be broken into sub-problems
c) Recursive calls take up less memory
d) Sequence generation is easier than a nested iteration
Answer: c
Explanation: Recursive calls take up a lot of memory and time as memory is taken up each time the function is called.
14. Which of these is not true about recursion?
a) It’s easier to code some real-world problems using recursion than non-recursive equivalent
b) Recursive functions are easy to debug
c) Recursive calls take up a lot of memory
d) Programs using recursion take longer time than their non-recursive equivalent
Answer: b
Explanation: Recursive functions may be hard to debug as the logic behind recursion may be hard to follow.
15. What will be the output of the following Python code?
def a(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return a(n-1)+a(n-2)
for i in range(0,4):
print(a(i),end=" ")
a) 0 1 2 3
b) An exception is thrown
c) 0 1 1 2 3
d) 0 1 1 2
Answer: d
Explanation: The above piece of code prints the Fibonacci series.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Regular Expressions – 1”.
1. The character Dot (that is, ‘.’) in the default mode, matches any character other than _____________
a) caret
b) ampersand
c) percentage symbol
d) newline
Answer: d
Explanation: The character Dot (that is, ‘,’) in the default mode, matches any character other than newline. If DOTALL flag is
used, then it matches any character other than newline.
2. The expression a{5} will match _____________ characters with the previous regular expression.
a) 5 or less
b) exactly 5
c) 5 or more
d) exactly 4
Answer: b
Explanation: The character {m} is used to match exactly m characters to the previous regular expression. Hence the expression
a{5} will match exactly 5 characters and not less than that.
3. ________ matches the start of the string.
________ matches the end of the string.
a) ‘^’, ‘$’
b) ‘$’, ‘^’
c) ‘$’, ‘?’
d) ‘?’, ‘^’
Answer: a
Explanation: ‘^’ (carat) matches the start of the string.
‘$’ (dollar sign) matches the end of the string.
4. Which of the following will result in an error?
a)
>>> p = re.compile("d")
>>> p.search("door")
b) >>> p = re.escape(‘hello’)
c) >>> p = re.subn()
d) >>> p = re.purge()
Answer: c
Explanation: The function re.subn() will result in an error. This is because subn() requires 3 positional arguments while we have
entered none.
5. What will be the output of the following Python code?
re.split('\W+', 'Hello, hello, hello.')
a) [‘Hello’, ‘hello’, ‘hello.’]
b) [‘Hello, ‘hello’, ‘hello’]
c) [‘Hello’, ‘hello’, ‘hello’, ‘.’]
d) [‘Hello’, ‘hello’, ‘hello’, ”]
Answer: d
Explanation: In the code shown above, the function split() splits the string based on the pattern given as an argument in the
parenthesis. Note: split will never split a string on an empty pattern match. Hence the output of this code is: [‘Hello’, ‘hello’, ‘hello’,
”].
6. What will be the output of the following Python function?
re.findall("hello world", "hello", 1)
a) [“hello”]
b) [ ]
c) hello
d) hello world
Answer: b
Explanation: The function findall returns the word matched if and only if both the pattern and the string match completely, that is,
they are exactly the same. Observe the example shown below:
>>> re.findall(“hello”, “hello”, 1) The output is: [‘hello’] Hence the output of the code shown in this question is [].
7. Choose the function whose output can be: <_sre.SRE_Match object; span=(4, 8), match=’aaaa’>.
a) >>> re.search(‘aaaa’, “alohaaaa”, 0)
b) >>> re.match(‘aaaa’, “alohaaaa”, 0)
c) >>> re.match(‘aaa’, “alohaaa”, 0)
d) >>> re.search(‘aaa’, “alohaaa”, 0)
Answer: a
Explanation: The output shown above is that of a search function, whose pattern is ‘aaaa’ and the string is that of 8 characters.
The only option which matches all these criteria is:
>>> re.search(‘aaaa’, “alohaaaa”, 0)
8. Which of the following functions clears the regular expression cache?
a) re.sub()
b) re.pos()
c) re.purge()
d) re.subn()
Answer: c
Explanation: The function which clears the regular expression cache is re.purge(). Note that this function takes zero positional
arguments.
9. What will be the output of the following Python code?
import re
re.ASCII
a) 8
b) 32
c) 64
d) 256
Answer: d
Explanation: The expression re.ASCII returns the total number of ASCII characters that are present, that is 256. This can also be
abbreviated as re.A, which results in the same output (that is, 256).
10. Which of the following functions results in case insensitive matching?
a) re.A
b) re.U
c) re.I
d) re.X
Answer: c
Explanation: The function re.I (that is, re.IGNORECASE) results in case-insensitive matching. That is, expressions such as [A-Z]
will match lowercase characters too.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Regular Expressions – 2”.
1. What will be the output of the following Python code?
re.compile('hello', re.X)
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) re.compile(‘hello’, re.VERBOSE)
c) Error
d) Junk value
Answer: b
Explanation: The compile function compiles a pattern of regular expression into an object of regular expression. Re.X is a flag
which is also used as re.VERBOSE. Hence the output of this code is: re.compile(‘hello’, re.VERBOSE).
2. What will be the output of the following Python code?
re.split('[a-c]', '0a3B6', re.I)
a) Error
b) [‘a’, ‘B’]
c) [‘0’, ‘3B6’]
d) [‘a’]
Answer: c
Explanation: The function re.split() splits the string on the basis of the pattern given in the parenthesis. Since we have used the
flag e.I (that is, re.IGNORECASE), the output is: [‘0’, ‘3B6’].
3. What will be the output of the following Python code?
re.sub('morning', 'evening', 'good morning')
a) ‘good evening’
b) ‘good’
c) ‘morning’
d) ‘evening’
Answer: a
Explanation: The code shown above first searches for the pattern ‘morning’ in the string ‘good morning’ and then replaces this
pattern with ‘evening’. Hence the output of this code is: ‘good evening’.
4. The function re.error raises an exception if a particular string contains no match for the given pattern.
a) True
b) False
Answer: b
Explanation: The function re.error raises an exception when a string passed to one of its functions here is not a valid regular
expression. It does not raise an exception if a particular string does not contain a match for the given pattern.
5. What will be the output of the following Python code?
re.escape('new**world')
a) ‘new world’
b) ‘new\\*\\*world’
c) ‘**’
d) ‘new’, ‘*’, ‘*’, ‘world’
Answer: b
Explanation: The function re.escape escapes all the characters in the pattern other than ASCII letters and numbers. Hence the
output of the code shown above is: ‘new\\*\\*world’.
6. What will be the output of the following Python code?
re.fullmatch('hello', 'hello world')
a) No output
b) []
c) <_sre.SRE_Match object; span=(0, 5), match='hello'>
d) Error
Answer: a
Explanation: The function re.fullmatch applies the pattern to the entire string and returns an object if match is found and none if
match in not found. In the code shown above, match is not found. Hence there is no output.
7. Choose the option wherein the two choices do not refer to the same option.
a)
re.I
re.IGNORECASE
b)
re.M
re.MULTILINE
c)
re.X
re.VERBOSE
d)
re.L
re.LOWERCASE
Answer: d
Explanation: The function re.L is also written as re.LOCALE. There is no function such as re.LOWERCASE in the re module of
Python.

8. The difference between the functions re.sub and re.subn is that re.sub returns a _______________ whereas re.subn returns a
__________________
a) string, list
b) list, tuple
c) string, tuple
d) tuple, list
Answer: c
Explanation: The difference the functions re.sub and re.subn is that re.sub returns a string whereas re.subn returns a tuple.
9. What will be the output of the following Python code?
re.split('mum', 'mumbai*', 1)
a) Error
b) [”, ‘bai*’]
c) [”, ‘bai’]
d) [‘bai*’]
Answer: b
Explanation: The code shown above splits the string based on the pattern given as an argument. Hence the output of the code is:
[”, ‘bai*’].
10. What will be the output of the following Python code?
re.findall('good', 'good is good')
re.findall('good', 'bad is good')
a)
[‘good’, ‘good’]
[‘good’]
b)
(‘good’, ‘good’)
(good)
c)
(‘good’)
(‘good’)
d)
[‘good’]
[‘good’]
Answer: a
Explanation: The function findall returns a list of all the non overlapping matches in a string. Hence the output of the first function
is: [‘good’, ‘good’] and that of the second function is: [‘good’].
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Regular Expressions – 3”.
1. What will be the output of the following Python code?
re.split(r'(n\d)=', 'n1=3.1, n2=5, n3=4.565')
a) Error
b) [”, ‘n1’, ‘3.1, ‘, ‘n2’, ‘5, ‘, ‘n3’, ‘4.565’]
c) [‘n1’, ‘3.1, ‘, ‘n2’, ‘5, ‘, ‘n3’, ‘4.565’]
d) [‘3.1, ‘, ‘5, ‘, ‘4.565’]
Answer: b
Explanation: In the snippet of code shown above, we extract the numbers as a list of floating point values, including the initial
empty string. The example shown above demonstrate how groups in the regular expression influence the result of re.split. Hence
the output of the code shown above is:
[”, ‘n1’, ‘3.1, ‘, ‘n2’, ‘5, ‘, ‘n3’, ‘4.565’].
2. The function of re.search is __________
a) Matches a pattern at the start of the string
b) Matches a pattern at the end of the string
c) Matches a pattern from any part of a string
d) Such a function does not exist
Answer: c
Explanation: The re module of Python consists of a function re.search. It’s function is to match a pattern from anywhere in a
string.
3. Which of the following functions creates a Python object?
a) re.compile(str)
b) re.assemble(str)
c) re.regex(str)
d) re.create(str)
Answer: a
Explanation: The function re.compile(srt) compiles a pattern of regular expression into an object of regular expression. Hence
re.compile(str) is the only function from the above options which creates an object.
4. Which of the following pattern matching modifiers permits whitespace and comments inside the regular expression?
a) re.L
b) re.S
c) re.U
d) re.X
Answer: d
Explanation: The modifier re.X allows whitespace and comments inside the regular expressions.
5. What will be the output of the following Python code?
s = 'welcome home'
m = re.match(r'(.*)(.*?)', s)
print(m.group())
a) (‘welcome’, ‘home’)
b) [‘welcome’, ‘home’]
c) welcome home
d) [‘welcome’ // ‘home’ ]
Answer: c
Explanation: The code shown above shows the function re.match combined with the use of special characters. Hence the output
of this code is: welcome home.
6. The function of re.match is ____________
a) Error
b) Matches a pattern anywhere in the string
c) Matches a pattern at the end of the string
d) Matches a pattern at the start of the string
Answer: d
Explanation: The function of re.match matches a pattern at the start of the string.
7. The special character \B matches the empty string, but only when it is _____________
a) at the beginning or end of a word
b) not at the beginning or end of a word
c) at the beginning of the word
d) at the end of the word
Answer: b
Explanation: The special character \B matches the empty string, but only when it is not at the beginning or end of a word.
8. What will be the output of the following Python code?
import re
s = "A new day"
m = re.match(r'(.*)(.*?)', s)
print(m.group(2))

print(m.group(0))
a)
No output
A new day
b)
No output
No output
c)
[‘A’, ‘new’, ‘day’]
(‘A’, ‘new’, ‘day’)
d)
Error
[‘A’, ‘new’, ‘day’]
Answer: a
Explanation: The code shown above demonstrates the use of the function re.match, with different arguments given to the group
method. Hence the first function does not return any output whereas the second function returns the output: A new day

9. Which of the following special characters matches a pattern only at the end of the string?
a) \B
b) \X
c) \Z
d) \A
Answer: c
Explanation: \B matches a pattern which is not at the beginning or end of a string. \X refers to re.VERBOSE. \A matches a
pattern only at the start of a string. \Z matches a pattern only at the end of a string.
10. The output of the following two Python codes are the same.
p = re.compile('hello')
r = p.match('hello everyone')
print(r.group(0))

r = re.match('hello', 'hello everyone')


print(r.group(0))
a) True
b) False
Answer: a
Explanation: The two codes shown above are equivalent. Both of these codes result in the same output, that is: hello. Hence this
statement is true.
11. What will be the output of the following Python code?
re.match('sp(.*)am', 'spam')
a) <_sre.SRE_Match object; span=(1, 4), match=’spam’>
b) <_sre.SRE_Match object; span=(0, 4), match=’spam’>
c) No output
d) Error
Answer: b
Explanation: The code shown above demonstrates the function re.match, combined with a special character. The output of the
code shown is: <_sre.SRE_Match object; span=(0, 4), match=’spam’>
12. Which of the following special characters represents a comment (that is, the contents of the parenthesis are simply ignores)?
a) (?:…)
b) (?=…)
c) (?!…)
d) (?#…)
Answer: d
Explanation: The special character (?#…) represent a comment, that is, the contents of the parenthesis are simply ignored.
13. Which of the codes shown below results in a match?
a) re.match(‘George(?=Washington)’, ‘George Washington’)
b) re.match(‘George(?=Washington)’, ‘George’)
c) re.match(‘George(?=Washington)’, ‘GeorgeWashington’)
d) re.match(‘George(?=Washington)’, ‘Georgewashington’)
Answer: c
Explanation: The code shown above demonstrates the use of the function re.match, along with the special character ?=. This
results in a match only when ‘George’ is immediately followed by ‘Washington’. Also, we have not used the module to ignore
case. Hence the match is case-sensitive. Therefore the only option which results in a match is:
re.match(‘George(?=Washington)’, ‘GeorgeWashington’)
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Regular Expressions – 4”.
1. What will be the output of the following Python code?
re.split(r'(a)(t)', 'Maths is a difficult subject')
a) [‘M a t h s i s a d i f f i c u l t s u b j e c t’]
b) [‘Maths’, ‘is’, ‘a’, ‘difficult’, ‘subject’]
c) ‘Maths is a difficult subject’
d) [‘M’, ‘a’, ‘t’, ‘hs is a difficult subject’]
Answer: d
Explanation: The code shown above demonstrates the use of the function re.match. The first argument of this function specifies
the pattern. Since the pattern contains groups, those groups are incorporated in the resultant list as well. Hence the output of the
code shown above is [‘M’, ‘a’, ‘t’, ‘hs is a difficult subject’].
2. The output of the following two Python codes are the same.
CODE 1
>>> re.split(r'(a)(t)', 'The night sky')
CODE 2
>>> re.split(r'\s+', 'The night sky')
a) True
b) False
Answer: b
Explanation: The output of the first code is: [‘The night sky’] whereas the output of the second code is:[‘The’, ‘night’, ‘sky’].
Clearly, the outputs of the two codes are different. Hence the statement given above is a false one.
3. What will be the output of the following Python code?
import re
s = 'abc123 xyz666 lmn-11 def77'
re.sub(r'\b([a-z]+)(\d+)', r'\2\1:', s)
a) ‘123abc: 666xyz: lmn-11 77def:’
b) ‘77def: lmn-11: 666xyz: 123abc’
c) ‘abc123:’, ‘xyz666:’, ‘lmn-11:’, ‘def77:’
d) ‘abc123: xyz666: lmn-11: def77’
Answer: a
Explanation: The function re.sub returns a string produced by replacing every non overlapping occurrence of the first argument
with the second argument in the third argument. Hence the output is: ‘123abc: 666xyz: lmn-11 77def:’
4. What will be the output of the following Python code?
re.subn('A', 'X', 'AAAAAA', count=4)
a) ‘XXXXAA, 4’
b) (‘AAAAAA’, 4)
c) (‘XXXXAA’, 4)
d) ‘AAAAAA, 4’
Answer: c
Explanation: The line of code shown above demonstrates the function re.subn. This function is very similar to the function re.sub
except that in the former, a tuple is returned instead of a string. The output of the code shown above is: (‘XXXXAA’, 4).
5. What will be the output of the following Python code?
n = re.sub(r'\w+', 'Hello', 'Cats and dogs')
a)
Hello
Hello
Hello
b) ‘Hello Hello Hello’
c) [‘Hello’, ‘Hello’, ‘Hello’]
d) (‘Hello’, ‘Hello’, ‘Hello’)
Answer: b
Explanation: The code shown above demonstrates the function re.sub. Since the string given as an argument consists of three
words. The output of the code is: ‘Hello Hello Hello’. Had the string consisted of 4 words, the output would be: ‘Hello Hello Hello
Hello’
6. What will be the output of the following Python code?
w = re.compile('[A-Za-z]+')
w.findall('It will rain today')
a) ‘It will rain today’
b) (‘It will rain today’)
c) [‘It will rain today’]
d) [‘It’, ‘will’, ‘rain’, ‘today’]
Answer: d
Explanation: The code shown above demonstrates the function re.findall. Since all the words in the string match the criteria, the
output of the code is: [‘It’, ‘will’, ‘rain’, ‘today’].
7. In the functions re.search.start(group) and re.search.end(group), if the argument groups not specified, it defaults to
__________
a) Zero
b) None
c) One
d) Error
Answer: a
Explanation: In the functions re.search.start(group) and re.search.end(group), if the argument groups not specified, it defaults to
Zero.
8. What will be the output of the following Python code?
re.split(r'\s+', 'Chrome is better than explorer', maxspilt=3)
a) [‘Chrome’, ‘is’, ‘better’, ‘than’, ‘explorer’]
b) [‘Chrome’, ‘is’, ‘better’, ‘than explorer’]
c) (‘Chrome’, ‘is’, ‘better’, ‘than explorer’)
d) ‘Chrome is better’ ‘than explorer’
Answer: b
Explanation: The code shown above demonstrates the use of the function re.split, including the use of maxsplit. Since maxsplit is
equal to 3, the output of the code shown above is:[‘Chrome’, ‘is’, ‘better’, ‘than explorer’]
9. What will be the output of the following Python code?
a=re.compile('[0-9]+')
a.findall('7 apples and 3 mangoes')
a) [‘apples’ ‘and’ ‘mangoes’]
b) (7, 4)
c) [‘7’, ‘4’]
d) Error
Answer: c
Explanation: The code shown above demonstrates the use of the functions re.compile and re.findall. Since we have specified in
the code that only digits from 0-9 be found, hence the output of this code is: [‘7’, ‘4’].
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Regular Expressions – 5”.
1. Which of the following functions returns a dictionary mapping group names to group numbers?
a) re.compile.group
b) re.compile.groupindex
c) re.compile.index
d) re.compile.indexgroup
Answer: b
Explanation: The function re.compile.groupindex returns a dictionary mapping group names to group numbers.
2. Which of the following statements regarding the output of the function re.match is incorrect?
a) ‘pq*’ will match ‘pq’
b) ‘pq?’ matches ‘p’
c) ‘p{4}, q’ does not match ‘pppq’
d) ‘pq+’ matches ‘p’
Answer: d
Explanation: All of the above statements are correct except that ‘pq+’ match ‘p’. ‘pq+’ will match ‘p’ followed by any non-zero
number of q’s, but it will not match ‘p’.
3. The following Python code snippet results in an error.
c=re.compile(r'(\d+)(\[A-Z]+)([a-z]+)')
c.groupindex
a) True
b) False
Answer: b
Explanation: In the code shown above, none of the group names match the group numbers. In such a case, no error is thrown.
The output of the code is an empty dictionary, that is, {}.
4. Which of the following functions does not accept any argument?
a) re.purge
b) re.compile
c) re.findall
d) re.match
Answer: a
Explanation: The function re.purge is used to clear the cache and it does not accept any arguments.
5. What will be the output of the following Python code?
a = re.compile('0-9')
a.findall('3 trees')
a) []
b) [‘3’]
c) Error
d) [‘trees’]
Answer: c
Explanation: The output of the code shown above is an empty list. This is due to the way the arguments have been passed to the
function re.compile. Carefully read the code shown below in order to understand the correct syntax:
>>> a = re.compile(‘[0-9]’)
>>> a.findall(‘3 trees’)
[‘3’].
6. Which of the following lines of code will not show a match?
a) >>> re.match(‘ab*’, ‘a’)
b) >>> re.match(‘ab*’, ‘ab’)
c) >>> re.match(‘ab*’, ‘abb’)
d) >>> re.match(‘ab*’, ‘ba’)
Answer: d
Explanation: In the code shown above, ab* will match to ‘a’ or ‘ab’ or ‘a’ followed by any number of b’s. Hence the only line of
code from the above options which does not result in a match is:
>>> re.match(‘ab*’, ‘ba’).
7. What will be the output of the following Python code?
m = re.search('a', 'The blue umbrella')
m.re.pattern
a) {}
b) ‘The blue umbrella’
c) ‘a’
d) No output
Answer: c
Explanation: The PatternObject is used to produce the match. The real regular expression pattern string must be retrieved from
the PatternObject’s pattern method. Hence the output of this code is: ‘a’.
8. What will be the output of the following Python code?
re.sub('Y', 'X', 'AAAAAA', count=2)
a) ‘YXAAAA’
b) (‘YXAAAA’)
c) (‘AAAAAA’)
d) ‘AAAAAA’
Answer: d
Explanation: The code shown above demonstrates the function re.sub, which returns a string. The pattern specified is substituted
in the string and returned. Hence the output of the code shown above is: ‘AAAAAA’.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Regular Expressions”.
1. Which module in Python supports regular expressions?
a) re
b) regex
c) pyregex
d) none of the mentioned
Answer: a
Explanation: re is a part of the standard library and can be imported using: import re.
2. Which of the following creates a pattern object?
a) re.create(str)
b) re.regex(str)
c) re.compile(str)
d) re.assemble(str)
Answer: c
Explanation: It converts a given string into a pattern object.
3. What does the function re.match do?
a) matches a pattern at the start of the string
b) matches a pattern at any position in the string
c) such a function does not exist
d) none of the mentioned
Answer: a
Explanation: It will look for the pattern at the beginning and return None if it isn’t found.
4. What does the function re.search do?
a) matches a pattern at the start of the string
b) matches a pattern at any position in the string
c) such a function does not exist
d) none of the mentioned
Answer: b
Explanation: It will look for the pattern at any position in the string.
5. What will be the output of the following Python code?
sentence = 'we are humans'
matched = re.match(r'(.*) (.*?) (.*)', sentence)
print(matched.groups())
a) (‘we’, ‘are’, ‘humans’)
b) (we, are, humans)
c) (‘we’, ‘humans’)
d) ‘we are humans’
Answer: a
Explanation: This function returns all the subgroups that have been matched.
6. What will be the output of the following Python code?
sentence = 'we are humans'
matched = re.match(r'(.*) (.*?) (.*)', sentence)
print(matched.group())
a) (‘we’, ‘are’, ‘humans’)
b) (we, are, humans)
c) (‘we’, ‘humans’)
d) ‘we are humans’
Answer: d
Explanation: This function returns the entire match.
7. What will be the output of the following Python code?
sentence = 'we are humans'
matched = re.match(r'(.*) (.*?) (.*)', sentence)
print(matched.group(2))
a) ‘are’
b) ‘we’
c) ‘humans’
d) ‘we are humans’
Answer: c
Explanation: This function returns the particular subgroup.
8. What will be the output of the following Python code?
sentence = 'horses are fast'
regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')
matched = re.search(regex, sentence)
print(matched.groupdict())
a) {‘animal’: ‘horses’, ‘verb’: ‘are’, ‘adjective’: ‘fast’}
b) (‘horses’, ‘are’, ‘fast’)
c) ‘horses are fast’
d) ‘are’
Answer: a
Explanation: This function returns a dictionary that contains all the matches.
9. What will be the output of the following Python code?
sentence = 'horses are fast'
regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')
matched = re.search(regex, sentence)
print(matched.groups())
a) {‘animal’: ‘horses’, ‘verb’: ‘are’, ‘adjective’: ‘fast’}
b) (‘horses’, ‘are’, ‘fast’)
c) ‘horses are fast’
d) ‘are’
Answer: b
Explanation: This function returns all the subgroups that have been matched.
10. What will be the output of the following Python code?
sentence = 'horses are fast'
regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')
matched = re.search(regex, sentence)
print(matched.group(2))
a) {‘animal’: ‘horses’, ‘verb’: ‘are’, ‘adjective’: ‘fast’}
b) (‘horses’, ‘are’, ‘fast’)
c) ‘horses are fast’
d) ‘are’
Answer: d
Explanation: This function returns the particular subgroup.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Sets – 1”.
1. Which of these about a set is not true?
a) Mutable data type
b) Allows duplicate values
c) Data type with unordered values
d) Immutable data type
Answer: d
Explanation: A set is a mutable data type with non-duplicate, unordered values, providing the usual mathematical set operations.
2. Which of the following is not the correct syntax for creating a set?
a) set([[1,2],[3,4]])
b) set([1,2,2,3,4])
c) set((1,2,3,4))
d) {1,2,3,4}
Answer: a
Explanation: The argument given for the set must be an iterable.
3. What will be the output of the following Python code?
nums = set([1,1,2,3,3,3,4,4])
print(len(nums))
a) 7
b) Error, invalid syntax for formation of set
c) 4
d) 8
Answer: c
Explanation: A set doesn’t have duplicate items.
4. What will be the output of the following Python code?
a = [5,5,6,7,7,7]
b = set(a)
def test(lst):
if lst in b:
return 1
else:
return 0
for i in filter(test, a):
print(i,end=" ")
a) 5 5 6
b) 5 6 7
c) 5 5 6 7 7 7
d) 5 6 7 7 7
Answer: c
Explanation: The filter function will return all the values from list a which are true when passed to function test. Since all the
members of the set are non-duplicate members of the list, all of the values will return true. Hence all the values in the list are
printed.
5. Which of the following statements is used to create an empty set?
a) { }
b) set()
c) [ ]
d) ( )
Answer: b
Explanation: { } creates a dictionary not a set. Only set() creates an empty set.
6. What will be the output of the following Python code?
>>> a={5,4}
>>> b={1,2,4,5}
>>> a<b
a) {1,2}
b) True
c) False
d) Invalid operation
Answer: b
Explanation: a<b returns True if a is a proper subset of b.
7. If a={5,6,7,8}, which of the following statements is false?
a) print(len(a))
b) print(min(a))
c) a.remove(5)
d) a[2]=45
Answer: d
Explanation: The members of a set can be accessed by their index values since the elements of the set are unordered.
8. If a={5,6,7}, what happens when a.add(5) is executed?
a) a={5,5,6,7}
b) a={5,6,7}
c) Error as there is no add function for set data type
d) Error as 5 already exists in the set
Answer: b
Explanation: There exists add method for set data type. However 5 isn’t added again as set consists of only non-duplicate
elements and 5 already exists in the set. Execute in python shell to verify.
9. What will be the output of the following Python code?
>>> a={4,5,6}
>>> b={2,8,6}
>>> a+b
a) {4,5,6,2,8}
b) {4,5,6,2,8,6}
c) Error as unsupported operand type for sets
d) Error as the duplicate item 6 is present in both sets
Answer: c
Explanation: Execute in python shell to verify.
10. What will be the output of the following Python code?
>>> a={4,5,6}
>>> b={2,8,6}
>>> a-b
a) {4,5}
b) {6}
c) Error as unsupported operand type for set data type
d) Error as the duplicate item 6 is present in both sets
Answer: a
Explanation: – operator gives the set of elements in set a but not in set b.
11. What will be the output of the following Python code?
>>> a={5,6,7,8}
>>> b={7,8,10,11}
>>> a^b
a) {5,6,7,8,10,11}
b) {7,8}
c) Error as unsupported operand type of set data type
d) {5,6,10,11}
Answer: d
Explanation: ^ operator returns a set of elements in set A or set B, but not in both (symmetric difference).
12. What will be the output of the following Python code?
>>> s={5,6}
>>> s*3
a) Error as unsupported operand type for set data type
b) {5,6,5,6,5,6}
c) {5,6}
d) Error as multiplication creates duplicate elements which isn’t allowed
Answer: a
Explanation: The multiplication operator isn’t valid for the set data type.
13. What will be the output of the following Python code?
>>> a={5,6,7,8}
>>> b={7,5,6,8}
>>> a==b
a) True
b) False
Answer: a
Explanation: It is possible to compare two sets and the order of elements in both the sets doesn’t matter if the values of the
elements are the same.
14. What will be the output of the following Python code?
>>> a={3,4,5}
>>> b={5,6,7}
>>> a|b
a) Invalid operation
b) {3, 4, 5, 6, 7}
c) {5}
d) {3,4,6,7}
Answer: b
Explanation: The operation in the above piece of code is union operation. This operation produces a set of elements in both set
a and set b.
15. Is the following Python code valid?
a={3,4,{7,5}}
print(a[2][0])
a) Yes, 7 is printed
b) Error, elements of a set can’t be printed
c) Error, subsets aren’t allowed
d) Yes, {7,5} is printed
Answer: c
Explanation: In python, elements of a set must not be mutable and sets are mutable. Thus, subsets can’t exist.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Sets – 2”.
1. Which of these about a frozenset is not true?
a) Mutable data type
b) Allows duplicate values
c) Data type with unordered values
d) Immutable data type
Answer: a
Explanation: A frozenset is an immutable data type.
2. What is the syntax of the following Python code?
>>> a=frozenset(set([5,6,7]))
>>> a
a) {5,6,7}
b) frozenset({5,6,7})
c) Error, not possible to convert set into frozenset
d) Syntax error
Answer: b
Explanation: The above piece of code is the correct syntax for creating a frozenset.
3. Is the following Python code valid?
>>> a=frozenset([5,6,7])
>>> a
>>> a.add(5)
a) Yes, now a is {5,5,6,7}
b) No, frozen set is immutable
c) No, invalid syntax for add method
d) Yes, now a is {5,6,7}
Answer: b
Explanation: Since a frozen set is immutable, add method doesn’t exist for frozen method.
4. Set members must not be hashable.
a) True
b) False
Answer: b
Explanation: Set members must always be hashable.
5. What will be the output of the following Python code?
>>> a={3,4,5}
>>> a.update([1,2,3])
>>> a
a) Error, no method called update for set data type
b) {1, 2, 3, 4, 5}
c) Error, list can’t be added to set
d) Error, duplicate item present in list
Answer: b
Explanation: The method update adds elements to a set.
6. What will be the output of the following Python code?
>>> a={1,2,3}
>>> a.intersection_update({2,3,4,5})
>>> a
a) {2,3}
b) Error, duplicate item present in list
c) Error, no method called intersection_update for set data type
d) {1,4,5}
Answer: a
Explanation: The method intersection_update returns a set which is an intersection of both the sets.
7. What will be the output of the following Python code?
>>> a={1,2,3}
>>> b=a
>>> b.remove(3)
>>> a
a) {1,2,3}
b) Error, copying of sets isn’t allowed
c) {1,2}
d) Error, invalid syntax for remove
Answer: c
Explanation: Any change made in b is reflected in a because b is an alias of a.
8. What will be the output of the following Python code?
>>> a={1,2,3}
>>> b=a.copy()
>>> b.add(4)
>>> a
a) {1,2,3}
b) Error, invalid syntax for add
c) {1,2,3,4}
d) Error, copying of sets isn’t allowed
Answer: a
Explanation: In the above piece of code, b is barely a copy and not an alias of a. Hence any change made in b isn’t reflected in
a.
9. What will be the output of the following Python code?
>>> a={1,2,3}
>>> b=a.add(4)
>>> b
a) 0
b) {1,2,3,4}
c) {1,2,3}
d) Nothing is printed
Answer: d
Explanation: The method add returns nothing, hence nothing is printed.
10. What will be the output of the following Python code?
>>> a={1,2,3}
>>> b=frozenset([3,4,5])
>>> a-b
a) {1,2}
b) Error as difference between a set and frozenset can’t be found out
c) Error as unsupported operand type for set data type
d) frozenset({1,2})
Answer: a
Explanation: – operator gives the set of elements in set a but not in set b.
11. What will be the output of the following Python code?
>>> a={5,6,7}
>>> sum(a,5)
a) 5
b) 23
c) 18
d) Invalid syntax for sum method, too many arguments
Answer: b
Explanation: The second parameter is the start value for the sum of elements in set a. Thus, sum(a,5) = 5+(5+6+7)=23.
12. What will be the output of the following Python code?
>>> a={1,2,3}
>>> {x*2 for x in a|{4,5}}
a) {2,4,6}
b) Error, set comprehensions aren’t allowed
c) {8, 2, 10, 4, 6}
d) {8,10}
Answer: c
Explanation: Set comprehensions are allowed.
13. What will be the output of the following Python code?
>>> a={5,6,7,8}
>>> b={7,8,9,10}
>>> len(a+b)
a) 8
b) Error, unsupported operand ‘+’ for sets
c) 6
d) Nothing is displayed
Answer: b
Explanation: Duplicate elements in a+b is eliminated and the length of a+b is computed.
14. What will be the output of the following Python code?
a={1,2,3}
b={1,2,3}
c=a.issubset(b)
print(c)
a) True
b) Error, no method called issubset() exists
c) Syntax error for issubset() method
d) False
Answer: a
Explanation: The method issubset() returns True if b is a proper subset of a.
15. Is the following Python code valid?
a={1,2,3}
b={1,2,3,4}
c=a.issuperset(b)
print(c)
a) False
b) True
c) Syntax error for issuperset() method
d) Error, no method called issuperset() exists
Answer: a
Explanation: The method issubset() returns True if b is a proper subset of a.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Sets – 3”.
1. What will be the output of the following Python code?
s=set()
type(s)
a) <’set’>
b) <class ‘set’>
c) set
d) class set
Answer: b
Explanation: When we find the type of a set, the output returned is: .
2. The following Python code results in an error.
s={2, 3, 4, [5, 6]}
a) True
b) False
Answer: a
Explanation: The set data type makes use of a principle known as hashing. This means that each item in the set should be
hashable. Hashable in this context means immutable. List is mutable and hence the line of code shown above will result in an
error.
3. Set makes use of __________
Dictionary makes use of ____________
a) keys, keys
b) key values, keys
c) keys, key values
d) key values, key values
Answer: c
Explanation: Set makes use of keys.
Dictionary makes use of key values.
4. Which of the following lines of code will result in an error?
a) s={abs}
b) s={4, ‘abc’, (1,2)}
c) s={2, 2.2, 3, ‘xyz’}
d) s={san}
Answer: d
Explanation: The line: s={san} will result in an error because ‘san’ is not defined. The line s={abs} does not result in an error
because abs is a built-in function. The other sets shown do not result in an error because all the items are hashable.
5. What will be the output of the following Python code?
s={2, 5, 6, 6, 7}
s
a) {2, 5, 7}
b) {2, 5, 6, 7}
c) {2, 5, 6, 6, 7}
d) Error
Answer: b
Explanation: Duplicate values are not allowed in sets. Hence, the output of the code shown above will be a set containing the
duplicate value only once. Therefore the output is: {2, 5, 6, 7}
6. Input order is preserved in sets.
a) True
b) False
Answer: b
Explanation: The input order in sets is not maintained. This is demonstrated by the code shown below:
>>> s={2, 6, 8, 1, 5}
>>> s
{8, 1, 2, 5, 6}
7. Write a list comprehension for number and its cube for:
l=[1, 2, 3, 4, 5, 6, 7, 8, 9]
a) [x**3 for x in l]
b) [x^3 for x in l]
c) [x**3 in l]
d) [x^3 in l]
Answer: a
Explanation: The list comprehension to print a list of cube of the numbers for the given list is: [x**3 for x in l].
8. What will be the output of the following Python code?
s={1, 2, 3}
s.update(4)
s
a) {1, 2, 3, 4}
b) {1, 2, 4, 3}
c) {4, 1, 2, 3}
d) Error
Answer: d
Explanation: The code shown above will result in an error because the argument given to the function update should necessarily
be an iterable. Hence if we write this function as: s.update([4]), there will be no error.
9. Which of the following functions cannot be used on heterogeneous sets?
a) pop
b) remove
c) update
d) sum
Answer: d
Explanation: The functions sum, min and max cannot be used on mixed type (heterogeneous) sets. The functions pop, remove,
update etc can be used on homogenous as well as heterogeneous sets. An example of heterogeneous sets is: {‘abc’, 4, (1, 2)}
10. What will be the output of the following Python code?
s={4>3, 0, 3-3}
all(s)
any(s)
a)
True
False
b)
False
True
c)
True
True
d)
False
False
Answer: b
Explanation: The function all returns true only if all the conditions given are true. But in the example shown above, we have 0 as a
value. Hence false is returned. Similarly, any returns true if any one condition is true. Since the condition 4>3 is true, true is
returned.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Sets – 4”.
1. Which of the following functions will return the symmetric difference between two sets, x and y?
a) x | y
b) x ^ y
c) x & y
d) x – y
Answer: b
Explanation: The function x ^ y returns the symmetric difference between the two sets x and y. This is basically an XOR operation
being performed on the two sets.
2. What will be the output of the following Python code snippet?
z=set('abc$de')
'a' in z
a) True
b) False
c) No output
d) Error
Answer: a
Explanation: The code shown above is used to check whether a particular item is a part of a given set or not. Since ‘a’ is a part
of the set z, the output is true. Note that this code would result in an error in the absence of the quotes.
3. What will be the output of the following Python code snippet?
z=set('abc')
z.add('san')
z.update(set(['p', 'q']))
z
a) {‘abc’, ‘p’, ‘q’, ‘san’}
b) {‘a’, ‘b’, ‘c’, [‘p’, ‘q’], ‘san}
c) {‘a’, ‘c’, ‘c’, ‘p’, ‘q’, ‘s’, ‘a’, ‘n’}
d) {‘a’, ‘b’, ‘c’, ‘p’, ‘q’, ‘san’}
Answer: d
Explanation: The code shown first adds the element ‘san’ to the set z. The set z is then updated and two more elements, namely,
‘p’ and ‘q’ are added to it. Hence the output is: {‘a’, ‘b’, ‘c’, ‘p’, ‘q’, ‘san’}
4. What will be the output of the following Python code snippet?
s=set([1, 2, 3])
s.union([4, 5])
s|([4, 5])
a)
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
b)
Error
{1, 2, 3, 4, 5}
c)
{1, 2, 3, 4, 5}
Error
d)
Error
Error
Answer: c
Explanation: The first function in the code shown above returns the set {1, 2, 3, 4, 5}. This is because the method of the function
union allows any iterable. However the second function results in an error because of unsupported data type, that is list and set.
5. What will be the output of the following Python code snippet?
for x in set('pqr'):
print(x*2)
a)
pp
qq
rr
b)
pqr
pqr
c) ppqqrr
d) pqrpqr
Answer: a
Explanation: The code shown above prints each element of the set twice separately. Hence the output of this code is:
pp
qq
rr
6. What will be the output of the following Python code snippet?
{a**2 for a in range(4)}
a) {1, 4, 9, 16}
b) {0, 1, 4, 9, 16}
c) Error
d) {0, 1, 4, 9}
Answer: d
Explanation: The code shown above returns a set containing the square of values in the range 0-3, that is 0, 1, 2 and 3. Hence
the output of this line of code is: {0, 1, 4, 9}.
7. What will be the output of the following Python function?
{x for x in 'abc'}
{x*3 for x in 'abc'}
a)
{abc}
aaa
bbb
ccc
b)
abc
abc abc abc
c)
{‘a’, ‘b’, ‘c’}
{‘aaa’, ‘bbb’, ‘ccc’}
d)
{‘a’, ‘b’, ‘c’}
abc
abc
abc
Answer: c
Explanation: The first function prints each element of the set separately, hence the output is: {‘a’, ‘b’, ‘c’}. The second function
prints each element of the set thrice, contained in a new set. Hence the output of the second function is: {‘aaa’, ‘bbb’, ‘ccc’}.
(Note that the order may not be the same)
8. The output of the following code is: class<’set’>.
type({})
a) True
b) False
Answer: b
Explanation: The output of the line of code shown above is: class<’dict’>. This is because {} represents an empty dictionary,
whereas set() initializes an empty set. Hence the statement is false.
9. What will be the output of the following Python code snippet?
a=[1, 4, 3, 5, 2]
b=[3, 1, 5, 2, 4]
a==b
set(a)==set(b)
a)
True
False
b)
False
False
c)
False
True
d)
True
True
Answer: c
Explanation: In the code shown above, when we check the equality of the two lists, a and b, we get the output false. This is
because of the difference in the order of elements of the two lists. However, when these lists are converted to sets and checked
for equality, the output is true. This is known as order-neutral equality. Two sets are said to be equal if and only if they contain
exactly the same elements, regardless of order.

10. What will be the output of the following Python code snippet?
l=[1, 2, 4, 5, 2, 'xy', 4]
set(l)
l
a)
{1, 2, 4, 5, 2, ‘xy’, 4}
[1, 2, 4, 5, 2, ‘xy’, 4]
b)
{1, 2, 4, 5, ‘xy’}
[1, 2, 4, 5, 2, ‘xy’, 4]
c)
{1, 5, ‘xy’}
[1, 5, ‘xy’]
d)
{1, 2, 4, 5, ‘xy’}
[1, 2, 4, 5, ‘xy’]
Answer: b
Explanation: In the code shown above, the function set(l) converts the given list into a set. When this happens, all the duplicates
are automatically removed. Hence the output is: {1, 2, 4, 5, ‘xy’}. On the other hand, the list l remains unchanged. Therefore the
output is: [1, 2, 4, 5, 2, ‘xy’, 4].
Note that the order of the elements may not be the same.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Sets – 5”.
1. What will be the output of the following Python code?
s1={3, 4}
s2={1, 2}
s3=set()
i=0
j=0
for i in s1:
for j in s2:
s3.add((i,j))
i+=1
j+=1
print(s3)
a) {(3, 4), (1, 2)}
b) Error
c) {(4, 2), (3, 1), (4, 1), (5, 2)}
d) {(3, 1), (4, 2)}
Answer: c
Explanation: The code shown above finds the Cartesian product of the two sets, s1 and s2. The Cartesian product of these two
sets is stored in a third set, that is, s3. Hence the output of this code is: {(4, 2), (3, 1), (4, 1), (5, 2)}.
2. The ____________ function removes the first element of a set and the last element of a list.
a) remove
b) pop
c) discard
d) dispose
Answer: b
Explanation: The function pop removes the first element when used on a set and the last element when used to a list.
3. The difference between the functions discard and remove is that:
a) Discard removes the last element of the set whereas remove removes the first element of the set
b) Discard throws an error if the specified element is not present in the set whereas remove does not throw an error in case of
absence of the specified element
c) Remove removes the last element of the set whereas discard removes the first element of the set
d) Remove throws an error if the specified element is not present in the set whereas discard does not throw an error in case of
absence of the specified element
Answer: d
Explanation: The function remove removes the element if it is present in the set. If the element is not present, it throws an error.
The function discard removes the element if it is present in the set. If the element is not present, no action is performed (Error is
not thrown).
4. What will be the output of the following Python code?
s1={1, 2, 3}
s2={3, 4, 5, 6}
s1.difference(s2)
s2.difference(s1)
a)
{1, 2}
{4, 5, 6}
b)
{1, 2}
{1, 2}
c)
{4, 5, 6}
{1, 2}
d)
{4, 5, 6}
{4, 5, 6}
Answer: a
Explanation: The function s1.difference(s2) returns a set containing the elements which are present in the set s1 but not in the set
s2. Similarly, the function s2.difference(s1) returns a set containing elements which are present in the set s2 but not in the set s1.
Hence the output of the code shown above will be:
{1, 2}
{4, 5, 6}.

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


s1={1, 2, 3}
s2={4, 5, 6}
s1.isdisjoint(s2)
s2.isdisjoint(s1)
a)
True
False
b)
False
True
c)
True
True
d)
False
False
Answer: c
Explanation: The function isdisjoint returns true the two sets in question are disjoint, that is if they do not have even a single
element in common. The two sets s1 and s2 do not have any elements in common, hence true is returned in both the cases.

6. If we have two sets, s1 and s2, and we want to check if all the elements of s1 are present in s2 or not, we can use the function:
a) s2.issubset(s1)
b) s2.issuperset(s1)
c) s1.issuperset(s2)
d) s1.isset(s2)
Answer: b
Explanation: Since we are checking whether all the elements present in the set s1 are present in the set s2. This means that s1
is the subset and s1 is the superset. Hence the function to be used is: s2.issuperset(s1). This operation can also be performed
by the function: s1.issubset(s2).
7. What will be the output of the following Python code?
s1={1, 2, 3, 8}
s2={3, 4, 5, 6}
s1|s2
s1.union(s2)
a)
{3}
{1, 2, 3, 4, 5, 6, 8}
b)
{1, 2, 4, 5, 6, 8}
{1, 2, 4, 5, 6, 8}
c)
{3}
{3}
d)
{1, 2, 3, 4, 5, 6, 8}
{1, 2, 3, 4, 5, 6, 8}
Answer: d
Explanation: The function s1|s2 as well as the function s1.union(s2) returns a union of the two sets s1 and s2. Hence the output of
both of these functions is: {1, 2, 3, 4, 5, 6, 8}.

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


a=set('abc')
b=set('def')
b.intersection_update(a)
a
b
a)
set()
(‘e’, ‘d’, ‘f’}
b)
{}
{}
c)
{‘b’, ‘c’, ‘a’}
set()
d)
set()
set()
Answer: c
Explanation: The function b.intersection_update(a) puts those elements in the set b which are common to both the sets a and b.
The set a remains as it is. Since there are no common elements between the sets a and b, the output is:
‘b’, ‘c’, ‘a’}
set().

9. What will be the output of the following Python code, if s1= {1, 2, 3}?
s1.issubset(s1)
a) True
b) Error
c) No output
d) False
Answer: a
Explanation: Every set is a subset of itself and hence the output of this line of code is true.
10. What will be the output of the following Python code?
x=set('abcde')
y=set('xyzbd')
x.difference_update(y)
x
y
a)
{‘a’, ‘b’, ‘c’, ‘d’, ‘e’}
{‘x’, ‘y’, ‘z’}
b)
{‘a’, ‘c’, ‘e’}
{‘x’, ‘y’, ‘z’, ‘b’, ‘d’}
c)
{‘b’, ‘d’}
{‘b’, ‘d’}
d)
{‘a’, ‘c’, ‘e’}
{‘x’, ‘y’, ‘z’}
Answer: b
Explanation: The function x.difference_update(y) removes all the elements of the set y from the set x. Hence the output of the
code is:
{‘a’, ‘c’, ‘e’}
{‘x’, ‘y’, ‘z’, ‘b’, ‘d’}.

Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with
latest contests, videos, internships and jobs!
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Shallow copy vs Deep copy”.
1. Which type of copy is shown in the following python code?
l1=[[10, 20], [30, 40], [50, 60]]
ls=list(l1)
ls
[[10, 20], [30, 40], [50, 60]]
a) Shallow copy
b) Deep copy
c) memberwise
d) All of the mentioned
Answer: a
Explanation: The code shown above depicts shallow copy. For deep copy, the command given is: l2 = l1.copy().
2. What will be the output of the following Python code?
l=[2, 3, [4, 5]]
l2=l.copy()
l2[0]=88
l
l2
a)
[88, 2, 3, [4, 5]]
[88, 2, 3, [4, 5]]
b)
[2, 3, [4, 5]]
[88, 2, 3, [4, 5]]
c)
[88, 2, 3, [4, 5]]
[2, 3, [4, 5]]
d)
[2, 3, [4, 5]]
[2, 3, [4, 5]]
Answer: b
Explanation: The code shown above depicts deep copy. In deep copy, the base address of the objects is not copied. Hence the
modification done on one list does not affect the other list.

3. In _______________ copy, the base address of the objects are copied. In _______________ copy, the base address of the
objects are not copied.
a) deep. shallow
b) memberwise, shallow
c) shallow, deep
d) deep, memberwise
Answer: c
Explanation: In shallow copy, the base address of the objects are copied.
In deep copy, the base address of the objects are not copied.
Note that memberwise copy is another name for shallow copy.
4. The nested list undergoes shallow copy even when the list as a whole undergoes deep copy.
a) True
b) False
Answer: a
Explanation: A nested list undergoes shallow copy even when the list as a whole undergoes deep copy. Hence, this statement is
true.
5. What will be the output of the following Python code and state the type of copy that is depicted?
l1=[2, 4, 6, 8]
l2=[1, 2, 3]
l1=l2
l2
a) [2, 4, 6, 8], shallow copy
b) [2, 4, 6, 8], deep copy
c) [1, 2, 3], shallow copy
d) [1, 2, 3], deep copy
Answer: c
Explanation: The code shown above depicts shallow copy and the output of the code is: [1, 2, 3].
6. What will be the output of the following Python code?
l1=[10, 20, 30]
l2=l1
id(l1)==id(l2)

l2=l1.copy()
id(l1)==id(l2)
a) False, False
b) False, True
c) True, True
d) True, False
Answer: d
Explanation: The first code shown above represents shallow copy. Hence the output of the expression id(l1)==id(l2) is True. The
second code depicts deep copy. Hence the output of the expression id(l1)==id(l2) in the second case is False.
7. What will be the output of the following Python code?
l1=[1, 2, 3, [4]]
l2=list(l1)
id(l1)==id(l2)
a) True
b) False
c) Error
d) Address of l1
Answer: b
Explanation: The code shown above shows a nested list. A nested list will undergo shallow copy when the list as a whole
undergoes deep copy. Hence the output of this code is False.
8. What will be the output of the following Python code?
l1=[10, 20, 30, [40]]
l2=copy.deepcopy(l1)
l1[3][0]=90
l1
l2
a)
[10, 20, 30, [40]]
[10, 20, 30, 90]
b) Error
c)
[10, 20, 30 [90]]
[10, 20, 30, [40]]
d)
[10, 20, 30, [40]]
[10, 20, 30, [90]]
Answer: c
Explanation: The code shown above depicts deep copy. Hence at the end of the code, l1=[10, 20, 30, [90]] and l2=[10, 20, 30,
[40]].

9. In ____________________ copy, the modification done on one list affects the other list. In ____________________ copy,
the modification done on one list does not affect the other list.
a) shallow, deep
b) memberwise, shallow
c) deep, shallow
d) deep, memberwise
Answer: a
Explanation: In shallow copy, the modification done on one list affects the other list. In deep copy, the modification done on one
list does not affect the other list.
10. What will be the output of the following Python code?
l1=[1, 2, 3, (4)]
l2=l1.copy()
l2
l1
a)
[1, 2, 3, (4)]
[1, 2, 3, 4]
b)
[1, 2, 3, 4]
[1, 2, 3, (4)]
c)
[1, 2, 3, 4]
[1, 2, 3, 4]
d)
[1, 2, 3, (4)]
[1, 2, 3, (4)]
Answer: c
Explanation: In the code shown above, the list l1 is enclosed in a tuple. When we print this list, it is printed as [1, 2, 3, 4]. Note the
absence of the tuple. The code shown depicts deep copy. Hence the output of this program is: l1=[1, 2, 3, 4] and l2=[1, 2, 3, 4].

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


def check(n):
if n < 2:
return n % 2 == 0
return check(n - 2)
print(check(11))
a) False
b) True
c) 1
d) An exception is thrown
Answer: a
Explanation: The above piece of code checks recursively whether a number is even or odd.
12. What is the base case in the Merge Sort algorithm when it is solved recursively?
a) n=0
b) n=1
c) A list of length one
d) An empty list
Answer: c
Explanation: Merge Sort algorithm implements the recursive algorithm and when the recursive function receives a list of length 1
which is the base case, the list is returned.
13. What will be the output of the following Python code?
a = [1, 2, 3, 4, 5]
b = lambda x: (b (x[1:]) + x[:1] if x else [])
print(b (a))
a) 1 2 3 4 5
b) [5,4,3,2,1]
c) []
d) Error, lambda functions can’t be called recursively
Answer: c
Explanation: The above piece of code appends the first element of the list to a reversed sublist and reverses the list using
recursion.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Sys Module”.
1. Which of the following functions can help us to find the version of python that we are currently working on?
a) sys.version
b) sys.version()
c) sys.version(0)
d) sys.version(1)
Answer: a
Explanation: The function sys.version can help us to find the version of python that we are currently working on. For example,
3.5.2, 2.7.3 etc. this function also returns the current date, time, bits etc along with the version.
2. Which of the following functions is not defined under the sys module?
a) sys.platform
b) sys.path
c) sys.readline
d) sys.argv
Answer: c
Explanation: The functions sys.platform, sys.path and sys.argv are defined under the sys module. The function sys.readline is not
defined. However, sys.stdin.readline is defined.
3. The output of the functions len(“abc”) and sys.getsizeof(“abc”) will be the same.
a) True
b) False
Answer: b
Explanation: The function len returns the length of the string passed, and hence it’s output will be 3. The function getsizeof,
present under the sys module returns the size of the object passed. It’s output will be a value much larger than 3. Hence the
above statement is false.
4. What will be the output of the following Python code, if the code is run on Windows operating system?
import sys
if sys.platform[:2]== 'wi':
print("Hello")
a) Error
b) Hello
c) No output
d) Junk value
Answer: b
Explanation: The output of the function sys.platform[:2] is equal to ‘wi’, when this code is run on windows operating system.
Hence the output printed is ‘hello’.
5. What will be the output of the following Python code, if the sys module has already been imported?
sys.stdout.write("hello world")
a) helloworld
b) hello world10
c) hello world11
d) error
Answer: c
Explanation: The function shown above prints the given string along with the length of the string. Hence the output of the function
shown above will be hello world11.
6. What will be the output of the following Python code?
import sys
sys.stdin.readline()
Sanfoundry
a) ‘Sanfoundry\n’
b) ‘Sanfoundry’
c) ‘Sanfoundry10’
d) Error
Answer: a
Explanation: The function shown above works just like raw_input. Hence it automatically adds a ‘\n’ character to the input string.
Therefore, the output of the function shown above will be: Sanfoundry\n.
7. What will be the output of the following Python code?
import sys
eval(sys.stdin.readline())
"India"
a) India5
b) India
c) ‘India\n’
d) ‘India’
Answer: d
Explanation: The function shown above evaluates the input into a string. Hence if the input entered is enclosed in double quotes,
the output will be enclosed in single quotes. Therefore, the output of this code is ‘India’.
8. What will be the output of the following Python code?
import sys
eval(sys.stdin.readline())
Computer
a) Error
b) ‘Computer\n’
c) Computer8
d) Computer
Answer: a
Explanation: The code shown above will result in an error. This is because this particular function accepts only strings enclosed
in single or double inverted quotes, or numbers. Since the string entered above is not enclosed in single or double inverted
quotes, an error will be thrown.
9. What will be the output of the following Python code?
import sys
sys.argv[0]
a) Junk value
b) ‘ ‘
c) No output
d) Error
Answer: b
Explanation: The output of the function shown above will be a blank space enclosed in single quotes. Hence the output of the
code shown above is ‘ ‘.
10. What will be the output of the following Python code?
import sys
sys.stderr.write(“hello”)
a) ‘hello’
b) ‘hello\n’
c) hello
d) hello5
Answer: d
Explanation: The code shown above returns the string, followed by the length of the string. Hence the output of the code shown
above is hello5.
11. What will be the output of the following Python code?
import sys
sys.argv
a) ‘ ‘
b) [ ]
c) [‘ ‘]
d) Error
Answer: c
Explanation: The output of the code shown above is a blank space inserted in single quotes, which is enclosed by square
brackets. Hence the output will be [‘ ‘].
12. To obtain a list of all the functions defined under sys module, which of the following functions can be used?
a) print(sys)
b) print(dir.sys)
c) print(dir[sys])
d) print(dir(sys))
Answer: d
Explanation: The function print(dir(sys)) helps us to obtain a list of all the functions defined under the sys module. The function can
be used to obtain the list of functions under any given module in Python.
13. The output of the function len(sys.argv) is ____________
a) Error
b) 1
c) 0
d) Junk value
Answer: b
Explanation: The output of the function sys.argv is [‘ ‘]. When we execute the function len([‘ ‘]), the output is 1. Hence the output of
the function len(sys.argv) is also 1.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Tuples – 2”.
1. What is the data type of (1)?
a) Tuple
b) Integer
c) List
d) Both tuple and integer
Answer: b
Explanation: A tuple of one element must be created as (1,).
2. If a=(1,2,3,4), a[1:-1] is _________
a) Error, tuple slicing doesn’t exist
b) [2,3]
c) (2,3,4)
d) (2,3)
Answer: d
Explanation: Tuple slicing exists and a[1:-1] returns (2,3).
3. What will be the output of the following Python code?
>>> a=(1,2,(4,5))
>>> b=(1,2,(3,4))
>>> a<b
a) False
b) True
c) Error, < operator is not valid for tuples
d) Error, < operator is valid for tuples but not if there are sub-tuples
Answer: a
Explanation: Since the first element in the sub-tuple of a is larger that the first element in the subtuple of b, False is printed.
4. What will be the output of the following Python code?
>>> a=("Check")*3
>>> a
a) (‘Check’,’Check’,’Check’)
b) * Operator not valid for tuples
c) (‘CheckCheckCheck’)
d) Syntax error
Answer: c
Explanation: Here (“Check”) is a string not a tuple because there is no comma after the element.
5. What will be the output of the following Python code?
>>> a=(1,2,3,4)
>>> del(a[2])
a) Now, a=(1,2,4)
b) Now, a=(1,3,4)
c) Now a=(3,4)
d) Error as tuple is immutable
Answer: d
Explanation: ‘tuple’ object doesn’t support item deletion.
6. What will be the output of the following Python code?
>>> a=(2,3,4)
>>> sum(a,3)
a) Too many arguments for sum() method
b) The method sum() doesn’t exist for tuples
c) 12
d) 9
Answer: c
Explanation: In the above case, 3 is the starting value to which the sum of the tuple is added to.
7. Is the following Python code valid?
>>> a=(1,2,3,4)
>>> del a
a) No because tuple is immutable
b) Yes, first element in the tuple is deleted
c) Yes, the entire tuple is deleted
d) No, invalid syntax for del method
Answer: c
Explanation: The command del a deletes the entire tuple.
8. What type of data is: a=[(1,1),(2,4),(3,9)]?
a) Array of tuples
b) List of tuples
c) Tuples of lists
d) Invalid type
Answer: b
Explanation: The variable a has tuples enclosed in a list making it a list of tuples.
9. What will be the output of the following Python code?
>>> a=(0,1,2,3,4)
>>> b=slice(0,2)
>>> a[b]
a) Invalid syntax for slicing
b) [0,2]
c) (0,1)
d) (0,2)
Answer: c
Explanation: The method illustrated in the above piece of code is that of naming of slices.
10. Is the following Python code valid?
>>> a=(1,2,3)
>>> b=('A','B','C')
>>> c=tuple(zip(a,b))
a) Yes, c will be ((1, ‘A’), (2, ‘B’), (3, ‘C’))
b) Yes, c will be ((1,2,3),(‘A’,’B’,’C’))
c) No because tuples are immutable
d) No because the syntax for zip function isn’t valid
Answer: a
Explanation: Zip function combines individual elements of two iterables into tuples. Execute in Python shell to verify.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Tuples – 3”.
1. Is the following Python code valid?
>>> a,b,c=1,2,3
>>> a,b,c
a) Yes, [1,2,3] is printed
b) No, invalid syntax
c) Yes, (1,2,3) is printed
d) 1 is printed
Answer: c
Explanation: A tuple needn’t be enclosed in parenthesis.
2. What will be the output of the following Python code?
a = ('check',)
n=2
for i in range(int(n)):
a = (a,)
print(a)
a) Error, tuples are immutable
b)
(('check',),)
((('check',),),)
c) ((‘check’,)’check’,)
d)
(('check',)’check’,)
((('check',)’check’,)’check’,)
Answer: b
Explanation: The loop runs two times and each time the loop runs an extra parenthesis along with a comma is added to the tuple
(as a=(a’)).

3. Is the following Python code valid?


>>> a,b=1,2,3
a) Yes, this is an example of tuple unpacking. a=1 and b=2
b) Yes, this is an example of tuple unpacking. a=(1,2) and b=3
c) No, too many values to unpack
d) Yes, this is an example of tuple unpacking. a=1 and b=(2,3)
Answer: c
Explanation: For unpacking to happen, the number of values of the right hand side must be equal to the number of variables on
the left hand side.
4. What will be the output of the following Python code?
>>> a=(1,2)
>>> b=(3,4)
>>> c=a+b
>>> c
a) (4,6)
b) (1,2,3,4)
c) Error as tuples are immutable
d) None
Answer: b
Explanation: In the above piece of code, the values of the tuples aren’t being changed. Both the tuples are simply concatenated.
5. What will be the output of the following Python code?
>>> a,b=6,7
>>> a,b=b,a
>>> a,b
a) (6,7)
b) Invalid syntax
c) (7,6)
d) Nothing is printed
Answer: c
Explanation: The above piece of code illustrates the unpacking of variables.
6. What will be the output of the following Python code?
>>> import collections
>>> a=collections.namedtuple('a',['i','j'])
>>> obj=a(i=4,j=7)
>>> obj
a) a(i=4, j=7)
b) obj(i=4, j=7)
c) (4,7)
d) An exception is thrown
Answer: a
Explanation: The above piece of code illustrates the concept of named tuples.
7. Tuples can’t be made keys of a dictionary.
a) True
b) False
Answer: b
Explanation: Tuples can be made keys of a dictionary because they are hashable.
8. Is the following Python code valid?
>>> a=2,3,4,5
>>> a
a) Yes, 2 is printed
b) Yes, [2,3,4,5] is printed
c) No, too many values to unpack
d) Yes, (2,3,4,5) is printed
Answer: d
Explanation: A tuple needn’t be enclosed in parenthesis.
9. What will be the output of the following Python code?
>>> a=(2,3,1,5)
>>> a.sort()
>>> a
a) (1,2,3,5)
b) (2,3,1,5)
c) None
d) Error, tuple has no attribute sort
Answer: d
Explanation: A tuple is immutable thus it doesn’t have a sort attribute.
10. Is the following Python code valid?
>>> a=(1,2,3)
>>> b=a.update(4,)
a) Yes, a=(1,2,3,4) and b=(1,2,3,4)
b) Yes, a=(1,2,3) and b=(1,2,3,4)
c) No because tuples are immutable
d) No because wrong syntax for update() method
Answer: c
Explanation: Tuple doesn’t have any update() attribute because it is immutable.
11. What will be the output of the following Python code?
>>> a=[(2,4),(1,2),(3,9)]
>>> a.sort()
>>> a
a) [(1, 2), (2, 4), (3, 9)]
b) [(2,4),(1,2),(3,9)]
c) Error because tuples are immutable
d) Error, tuple has no sort attribute
Answer: a
Explanation: A list of tuples is a list itself. Hence items of a list can be sorted.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Turtle Module – 1”.
1. What will be the output shape of the following Python code?
import turtle
t=turtle.Pen()
for i in range(0,4):
t.forward(100)
t.left(120)
a) square
b) rectangle
c) triangle
d) kite
Answer: c
Explanation: According to the code shown above, 4 lines will be drawn. Three lines will be in the shape of a triangle. The fourth
line will trace the base, which is already drawn. Hence the base will be slightly thicker than the rest of the lines. However there will
be no change in the shape due to this extra line. Hence the output shape will be a triangle.
2. The number of lines drawn in each case, assuming that the turtle module has been imported:
Case 1:
for i in range(0,10):
turtle.forward(100)
turtle.left(90)
Case 2:
for i in range(1,10):
turtle.forward(100)
turtle.left(90)
a) 10, 9
b) 9, 10
c) 9, 9
d) 10, 10
Answer: a
Explanation: The number of lines drawn in the first case is 10, while that in the second case is 9.
3. The command which helps us to reset the pen (turtle):
a) turtle.reset
b) turtle.penreset
c) turtle.penreset()
d) turtle.reset()
Answer: d
Explanation: The command turtle.reset() helps us to reset the pen. After the execution of this command, we get a blank page with
an arrow on it. We can then perform any desired operation on this page.
4. Fill in the blank such that the following Python code results in the formation of an inverted, equilateral triangle.
import turtle
t=turtle.Pen()
for i in range(0,3):
t.forward(150)
t.right(_____)
a) -60
b) 120
c) -120
d) 60
Answer: b
Explanation: An angle of -120 will result in the formation of an upright, equilateral triangle. An angle of 120 will result in the
formation of an inverted triangle. The angles of 60 and -60 do not result in the formation of a triangle.
5. What will be the output shape of the following Python code?
import turtle
t=turtle.Pen()
for i in range(1,4):
t.forward(60)
t.left(90)
a) Rectangle
b) Trapezium
c) Triangle
d) Square
Answer: d
Explanation: The code shown above will result in the formation of a square, with each of side 60.
6. What will be the output of the following Python code?
import turtle
t=turtle.Pen()
for i in range(0,4):
t.forward(100)
t.left(90)

t.penup()
t.left(90)
t.forward(200)
for i in range(0,4):
t.forward(100)
t.left(90)
a) Error
b) 1 square
c) 2 squares, at a separation of100 units, joined by a straight line
d) 2 squares, at a separation of 100 units, without a line joining them
Answer: b
Explanation: The output of the code shown above will be a single square. This is because the function t.penup() is used to lift the
pen after the construction of the first square. However, the function t.pendown() has not been used to put the pen back down.
Hence, the output shape of this code is one square, of side 100 units.
7. Which of the following functions does not accept any arguments?
a) position
b) fillcolor
c) goto
d) setheading()
Answer: a
Explanation: The functions fillcolor(), goto() and setheading() accept arguments, whereas the function position() does not accept
any arguments. The function position() returns the current position of the turtle.
8. What will be the output of the following Python code?
import turtle
t=turtle.Pen()
t.goto(300,9)
t.position()
a) 300.00, 9.00
b) 9, 300
c) 300, 9
d) 9.00, 300.00
Answer: a
Explanation: The goto functions takes the arrow to the position specified by the user as arguments. The position function returns
the current position of the arrow. Hence the output of the code shown above will be: 300.00, 9.00.
9. What will be the output of the following Python code?
import turtle
t=turtle.Pen()
for i in range(0,5):
t.left(144)
t.forward(100)
a) Trapezium
b) Parallelepiped
c) Tetrahedron
d) Star
Answer: d
Explanation: It is clear from the above code that 5 lines will be drawn on the canvas, at an angle of 144 degrees. The only shape
which fits this description is star. Hence the output of the code shown above is star.
10. What will be the output of the following Python functions?
import turtle
t=turtle.Pen()
for i in range(0,3):
t.forward(100)
t.left(120)

t.back(100)
for i in range(0,3):
t.forward(100)
t.left(120)
a) Error
b) Two triangles, joined by a straight line
c) Two triangles, joined at one vertex
d) Two separate triangles, not connected by a line
Answer: c
Explanation: The output of the code shown above is two equilateral triangles (of side 100 units), joined at the vertex.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Turtle Module – 2”.
1. What will be the output of the following Python code?
import turtle
t=turtle.Pen()
t.color(0,0,1)
t.begin_fill()
t.circle(15)
t.end_fill()
a) Error
b) A circle filled in with the colour red
c) A circle filled in with the colour blue
d) A circle filled in with the colour green
Answer: c
Explanation: The function t.colour(0, 0, 1) is used to fill in the colour blue into any given shape. Hence the output of the code
shown above will be a circle filled in with the colour blue.
2. Which of the following functions can be used to make the arrow black?
a) turtle.color(0,1,0)
b) turtle.color(1,0,0)
c) turtle.color(0,0,1)
d) turtle.color(0,0,0)
Answer: d
Explanation: The function turtle.color(0,0,0) can change the colour of the arrow. The function turtle.color(0,1,0) will make the arrow
green. The function turtle.color(1,0,0) will make the arrow red. The function turtle.color(0,0,1) will make the arrow blue. The
function turtle.color(0,0,0) will make the arrow black.
3. What will be the output of the following Python code?
import turtle
t=turtle.Pen()
t.color(1,1,1)
t.begin_fill()
for i in range(0,3):
t.forward(100)
t.right(120)
t.end_fill()
a) Blank page
b) A triangle filled in with the colour yellow
c) A triangle which is not filled in with any colour
d) Error
Answer: a
Explanation: The code shown above will result in a blank page. This is because the command turtle.color(1,1,1) eliminates the
arrow from the page. Hence all the commands after this command are ineffective.
4. What will be the output of the following Python code?
import turtle
t=turtle.Pen()
t.color(0,1,0)
t.begin_fill()
for i in range(0,4):
t.forward(100)
t.right(90)
a) A square filled in with the colour green
b) A square outlined with the colour green
c) Blank canvas
d) Error
Answer: c
Explanation: The output shape of the code shown above is a square, outlined with the colour green, but not filled in with any
colour. This is because we have not used the command t.end_fill() at the end.
5. In which direction is the turtle pointed by default?
a) North
b) South
c) East
d) West
Answer: c
Explanation: By default, the turtle is pointed towards the east direction. We can change the direction of the turtle by using certain
commands. However, whenever the turtle is reset, it points towards east.
6. The command used to set only the x coordinate of the turtle at 45 units is:
a) reset(45)
b) setx(45)
c) xset(45)
d) xreset(45)
Answer: b
Explanation: The command setx(45) is used to set the x coordinate of the turtle. Similarly, the command sety() is used to set the y
coordinate of the turtle. The function reset() takes two values as arguments, one for the x-coordinate and the other for the y-
coordinate.
7. Which of the following functions returns a value in degrees, counterclockwise from the horizontal right?
a) heading()
b) degrees()
c) position()
d) window_height()
Answer: a
Explanation: The function heading() returns the heading of the turtle, which is a value in degrees counterclockwise from the
horizontal right. This measure will be in radians if radians() has been called.
8. What will be the output of the following Python code?
import turtle
t=turtle.Pen()
t.right(90)
t.forward(100)
t.heading()
a) 0.0
b) 90.0
c) 270.0
d) 360.0
Answer: c
Explanation: The output of the code shown above will be 270.0. The function heading() returns the heading of the turtle, a value in
degrees, counterclockwise from the horizontal right. The output shape of this code is a straight line pointing downwards.
9. What will be the output of the following Python code?
import turtle
t=turtle.Pen()
t.clear()
t.isvisible()
a) Yes
b) True
c) No
d) False
Answer: b
Explanation: The function t.clear() returns a blank canvas, without changing the position of the turtle. Since the turtle is visible on
the blank canvas, the output of this code is: Yes.
10. What will be the output of the following Python code?
import turtle
t=turtle.Pen()
t.forward(100)
t.left(90)
t.clear()
t.position()
a) 0.00, 90.00
b) 0.00, 0.00
c) 100.00, 90.00
d) 100.00, 100.00
Answer: d
Explanation: The output of the code shown above is 100.00, 100.00. The function clear() is used to erase the entire canvas and
redraw the turtle. However, the position of the turtle is not changed.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Turtle Module – 3”.
1. Which of the following functions results in an error?
a) turtle.shape(“turtle”)
b) turtle.shape(“square”)
c) turtle.shape(“triangle”)
d) turtle.shape(“rectangle”)
Answer: d
Explanation: The functions shown above will change the arrow to the shape mentioned. The functions turtle.shape(“turtle”),
turtle.shape(“square”) and turtle.shape(“triangle”) are valid whereas the function turtle.shape(“rectangle”) is invalid.
2. What will be the output of the following Python code?
import turtle
t=turtle.Pen
t.tilt(75)
t.forward(100)
a) A straight line of 100 units tiled at 75 degrees from the horizontal
b) A straight line of 100 units tilted at 15 degrees from the horizontal
c) A straight line of 100 units lying along the horizontal
d) Error
Answer: c
Explanation: The function turtle.tilt(75) will tilt the turtle. But the straight line (of 100 units) is drawn along the horizontal. Hence the
output of the code shown above is a straight line of 100 units lying along the horizontal.
3. What will be the output of the following Python code?
import turtle
t=turtle.Pen()
t.backward(100)
t.penup()
t.right(45)
t.isdown()
a) True
b) False
c) Yes
d) No
Answer: b
Explanation: In the code shown above, we have used the function t.penup() to life the pen from the canvas. However, we have not
used the function t.pendown() to keep the pen back down. The function turtle.isdown() returns True if the pen is down and False if
the pen is not down. Hence the output is False.
4. The function used to alter the thickness of the pen to ‘x’ units:
a) turtle.width(x)
b) turtle.span(x)
c) turtle.girth(x)
d) turtle.thickness(x)
Answer: a
Explanation: The function turtle.width(x) is used to alter the thickness of the pen to ‘x’ units. The function turtle.span(x),
turtle.girth(x) and turtle.thickness(x) are invalid.
5. What will be the output of the following Python code if the system date is 18th June, 2017 (Sunday)?
import turtle
t=turtle.Pen()
t.goto(100,0)
t.towards(0,0)
a) 0.0
b) 180.0
c) 270.0
d) 360.0
Answer: b
Explanation: The function t.towards(x,y) returns the angle between the line to the line specified by (x,y). Hence the output will be
180.0.
6. What will be the output of the following Python code?
import turtle
t=turtle.Pen()
t.position()
(100.00,0.00)
t.goto(100,100)
t.distance(100,0)
a) 0.0
b) Error
c) 100.0, 100.0
d) 100.0
Answer: d
Explanation: The distance() function returns the distance between the turtle to the given vector. Hence the output of the code
shown above is 100.0.
7. The output of the following Python code will result in a shape similar to the alphabet ___________
import turtle
t=turtle.Turtle()
t1=turtle.Turtle()
t.left(45)
t1.left(135)
t.forward(100)
t1.forward(100)
a) V
b) Inverted V
c) X
d) T
Answer: a
Explanation: In the code shown above, two pens have been used to create a shape similar to the alphabet ‘V’. The angle
between the two straight lines is 90 degrees.
8. The output of the following Python code is similar to the alphabet _______________
import turtle
t=turtle.Pen()
t1=turtle.Pen()
t2=turtle.Pen()
t.forward(100)
t1.forward(100)
t2.forward(100)
t1.left(90)
t1.forward(75)
t2.right(90)
t2.forward(75)
a) X
b) N
c) T
d) M
Answer: c
Explanation: In the above code, three pens have been used to create a shape similar to the letter ‘T’. All the three straight lines
are mutually perpendicular.
9. The following Python code will result in an error.
import turtle
t=turtle.Pen()
t.speed(-45)
t.circle(30)
a) True
b) False
Answer: b
Explanation: Although a negative speed is not possible, the code shown above does not result in an error. Hence, the answer is
False.
10. What will be the output of the following Python code?
import turtle()
t=turtle.Pen()
t.goto(50,60)
t1=t.clone()
t1.ycor()
a) 0.0
b) 50.0
c) 60.0
d) Error
Answer: c
Explanation: The function clone() is used to create a clone of the turtle, having the same properties such as position, coordinates
etc. Hence, the properties of the t and t1 are the same in the code shown above. The function ycor() returns the y-coordinate of
the turtle. Hence the output of the code is 60.0.
11. What will be the output shape of the following Python code?
import turtle
t=turtle.Pen()
for i in range(0,6):
t.forward(100)
t.left(60)
a) Hexagon
b) Octagon
c) Pentagon
d) Heptagon
Answer: a
Explanation: The code shown above creates a six-sided polygon. The output shape of the code shown above is will be a
hexagon.
12. What will be the output of the following Python code?
import turtle
t=turtle.Pen()
t.resizemode(“sanfoundry”)
t.resizemode()
a) user
b) auto
c) nonresize
d) error
Answer: c
Explanation: When not explicitly specified as auto or user, no adaption of the turtle’s appearance takes place and the mode is
‘noresize’. Hence the output of the code is: noresize.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Variable Names”.
1. Is Python case sensitive when dealing with identifiers?
a) yes
b) no
c) machine dependent
d) none of the mentioned
Answer: a
Explanation: Case is always significant.
2. What is the maximum possible length of an identifier?
a) 31 characters
b) 63 characters
c) 79 characters
d) none of the mentioned
Answer: d
Explanation: Identifiers can be of any length.
3. Which of the following is invalid?
a) _a = 1
b) __a = 1
c) __str__ = 1
d) none of the mentioned
Answer: d
Explanation: All the statements will execute successfully but at the cost of reduced readability.
4. Which of the following is an invalid variable?
a) my_string_1
b) 1st_string
c) foo
d) _
Answer: b
Explanation: Variable names should not start with a number.
5. Why are local variable names beginning with an underscore discouraged?
a) they are used to indicate a private variables of a class
b) they confuse the interpreter
c) they are used to indicate global variables
d) they slow down execution
Answer: a
Explanation: As Python has no concept of private variables, leading underscores are used to indicate variables that must not be
accessed from outside the class.
6. Which of the following is not a keyword?
a) eval
b) assert
c) nonlocal
d) pass
Answer: a
Explanation: eval can be used as a variable.
7. All keywords in Python are in _________
a) lower case
b) UPPER CASE
c) Capitalized
d) None of the mentioned
Answer: d
Explanation: True, False and None are capitalized while the others are in lower case.
8. Which of the following is true for variable names in Python?
a) unlimited length
b) all private members must have leading and trailing underscores
c) underscore and ampersand are the only two special characters allowed
d) none of the mentioned
Answer: a
Explanation: Variable names can be of any length.
9. Which of the following is an invalid statement?
a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000
Answer: b
Explanation: Spaces are not allowed in variable names.
10. Which of the following cannot be a variable?
a) __init__
b) in
c) it
d) on
Answer: b
Explanation: in is a keyword.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “While and For Loops”.
1. What will be the output of the following Python code?
x = ['ab', 'cd']
for i in x:
i.upper()
print(x)
a) [‘ab’, ‘cd’]
b) [‘AB’, ‘CD’]
c) [None, None]
d) none of the mentioned
Answer: a
Explanation: The function upper() does not modify a string in place, it returns a new string which isn’t being stored anywhere.
2. What will be the output of the following Python code?
x = ['ab', 'cd']
for i in x:
x.append(i.upper())
print(x)
a) [‘AB’, ‘CD’]
b) [‘ab’, ‘cd’, ‘AB’, ‘CD’]
c) [‘ab’, ‘cd’]
d) none of the mentioned
Answer: d
Explanation: The loop does not terminate as new elements are being added to the list in each iteration.
3. What will be the output of the following Python code?
i=1
while True:
if i%3 == 0:
break
print(i)

i+=1
a) 1 2
b) 1 2 3
c) error
d) none of the mentioned
Answer: c
Explanation: SyntaxError, there shouldn’t be a space between + and = in +=.
4. What will be the output of the following Python code?
i=1
while True:
if i%0O7 == 0:
break
print(i)
i += 1
a) 1 2 3 4 5 6
b) 1 2 3 4 5 6 7
c) error
d) none of the mentioned
Answer: a
Explanation: Control exits the loop when i becomes 7.
5. What will be the output of the following Python code?
i=5
while True:
if i%0O11 == 0:
break
print(i)
i += 1
a) 5 6 7 8 9 10
b) 5 6 7 8
c) 5 6
d) error
Answer: b
Explanation: 0O11 is an octal number.
6. What will be the output of the following Python code?
i=5
while True:
if i%0O9 == 0:
break
print(i)
i += 1
a) 5 6 7 8
b) 5 6 7 8 9
c) 5 6 7 8 9 10 11 12 13 14 15 ….
d) error
Answer: d
Explanation: 9 isn’t allowed in an octal number.
7. What will be the output of the following Python code?
i=1
while True:
if i%2 == 0:
break
print(i)
i += 2
a) 1
b) 1 2
c) 1 2 3 4 5 6 …
d) 1 3 5 7 9 11 …
Answer: d
Explanation: The loop does not terminate since i is never an even number.
8. What will be the output of the following Python code?
i=2
while True:
if i%3 == 0:
break
print(i)
i += 2
a) 2 4 6 8 10 …
b) 2 4
c) 2 3
d) error
Answer: b
Explanation: The numbers 2 and 4 are printed. The next value of i is 6 which is divisible by 3 and hence control exits the loop.
9. What will be the output of the following Python code?
i=1
while False:
if i%2 == 0:
break
print(i)
i += 2
a) 1
b) 1 3 5 7 …
c) 1 2 3 4 …
d) none of the mentioned
Answer: d
Explanation: Control does not enter the loop because of False.
10. What will be the output of the following Python code?
True = False
while True:
print(True)
break
a) True
b) False
c) None
d) none of the mentioned
Answer: d
Explanation: SyntaxError, True is a keyword and it’s value cannot be changed.
This set of Python Questions for campus interview focuses on “Functions”.
1. Python supports the creation of anonymous functions at runtime, using a construct called __________
a) lambda
b) pi
c) anonymous
d) none of the mentioned
Answer: a
Explanation: Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using
a construct called lambda. Lambda functions are restricted to a single expression. They can be used wherever normal functions
can be used.
2. What will be the output of the following Python code?
1. y = 6
2. z = lambda x: x * y
3. print z(8)
a) 48
b) 14
c) 64
d) None of the mentioned
Answer: a
Explanation: The lambda keyword creates an anonymous function. The x is a parameter, that is passed to the lambda function.
The parameter is followed by a colon character. The code next to the colon is the expression that is executed, when the lambda
function is called. The lambda function is assigned to the z variable.
The lambda function is executed. The number 8 is passed to the anonymous function and it returns 48 as the result. Note that z is
not a name for this function. It is only a variable to which the anonymous function was assigned.
3. What will be the output of the following Python code?
1. lamb = lambda x: x ** 3
2. print(lamb(5))
a) 15
b) 555
c) 125
d) None of the mentioned
Answer: c
Explanation: None.
4. Does Lambda contains return statements?
a) True
b) False
Answer: b
Explanation: lambda definition does not include a return statement. it always contains an expression which is returned. Also note
that we can put a lambda definition anywhere a function is expected. We don’t have to assign it to a variable at all.
5. Lambda is a statement.
a) True
b) False
Answer: b
Explanation: lambda is an anonymous function in Python. Hence this statement is false.
6. Lambda contains block of statements.
a) True
b) False
Answer: b
Explanation: None.
7. What will be the output of the following Python code?
1. def f(x, y, z): return x + y + z
2. f(2, 30, 400)
a) 432
b) 24000
c) 430
d) No output
Answer: a
Explanation: None.
8. What will be the output of the following Python code?
1. def writer():
2. title = 'Sir'
3. name = (lambda x:title + ' ' + x)
4. return name
5. who = writer()
6. who('Arthur')
a) Arthur Sir
b) Sir Arthur
c) Arthur
d) None of the mentioned
Answer: b
Explanation: None.
9. What will be the output of the following Python code?
1. L = [lambda x: x ** 2,
2. lambda x: x ** 3,
3. lambda x: x ** 4]
4. for f in L:
5. print(f(3))
a)
27
81
343
b)
6
9
12
c)
9
27
81
d) None of the mentioned
Answer: c
Explanation: None.
10. What will be the output of the following Python code?
1. min = (lambda x, y: x if x < y else y)
2. min(101*99, 102*98)
a) 9997
b) 9999
c) 9996
d) None of the mentioned
Answer: c
Explanation: None.
To practice all campus interview questions on Python, .
This set of Python Questions for entrance examinations focuses on “Functions”.
1. Which are the advantages of functions in python?
a) Reducing duplication of code
b) Decomposing complex problems into simpler pieces
c) Improving clarity of the code
d) All of the mentioned
Answer: d
Explanation: None.
2. What are the two main types of functions?
a) Custom function
b) Built-in function & User defined function
c) User function
d) System function
Answer: b
Explanation: Built-in functions and user defined ones. The built-in functions are part of the Python language. Examples are: dir(),
len() or abs(). The user defined functions are functions created with the def keyword.
3. Where is function defined?
a) Module
b) Class
c) Another function
d) All of the mentioned
Answer: d
Explanation: Functions can be defined inside a module, a class or another function.
4. What is called when a function is defined inside a class?
a) Module
b) Class
c) Another function
d) Method
Answer: d
Explanation: None.
5. Which of the following is the use of id() function in python?
a) Id returns the identity of the object
b) Every object doesn’t have a unique id
c) All of the mentioned
d) None of the mentioned
Answer: a
Explanation: Each object in Python has a unique id. The id() function returns the object’s id.
6. Which of the following refers to mathematical function?
a) sqrt
b) rhombus
c) add
d) rhombus
Answer: a
Explanation: Functions that are always available for usage, functions that are contained within external modules, which must be
imported and functions defined by a programmer with the def keyword.
Eg: math import sqrt
A sqrt() function is imported from the math module.
7. What will be the output of the following Python code?
1. def cube(x):
2. return x * x * x
3. x = cube(3)
4. print x
a) 9
b) 3
c) 27
d) 30
Answer: c
Explanation: A function is created to do a specific task. Often there is a result from such a task. The return keyword is used to
return values from a function. A function may or may not return a value. If a function does not have a return keyword, it will send a
none value.
8. What will be the output of the following Python code?
1. def C2F(c):
2. return c * 9/5 + 32
3. print C2F(100)
4. print C2F(0)
a)
212
32
b)
314
24
c)
567
98
d) None of the mentioned
Answer: a
Explanation: The code shown above is used to convert a temperature in degree celsius to fahrenheit.
9. What will be the output of the following Python code?
1. def power(x, y=2):
2. r=1
3. for i in range(y):
4. r=r*x
5. return r
6. print power(3)
7. print power(3, 3)
a)
212
32
b)
9
27
c)
567
98
d) None of the mentioned
Answer: b
Explanation: The arguments in Python functions may have implicit values. An implicit value is used, if no value is provided. Here
we created a power function. The function has one argument with an implicit value. We can call the function with one or two
arguments.
10. What will be the output of the following Python code?
1. def sum(*args):
2. '''Function returns the sum
3. of all values'''
4. r=0
5. for i in args:
6. r += i
7. return r
8. print sum.__doc__
9. print sum(1, 2, 3)
10. print sum(1, 2, 3, 4, 5)
a)
6
15
b)
6
100
c)
123
12345
d) None of the mentioned
Answer: a
Explanation: We use the * operator to indicate, that the function will accept arbitrary number of arguments. The sum() function will
return the sum of all arguments. The first string in the function body is called the function documentation string. It is used to
document the function. The string must be in triple quotes.
To practice all extrance examination questions on Python, .
This set of Online Python Quiz focuses on “Strings”.
1. What will be the output of the following Python code?
print("ab\tcd\tef".expandtabs())
a) ab  cd  ef
b) abcdef
c) ab\tcd\tef
d) ab cd ef
Answer: a
Explanation: Each \t is converted to 8 blank spaces by default.
2. What will be the output of the following Python code?
print("ab\tcd\tef".expandtabs(4))
a) ab  cd  ef
b) abcdef
c) ab\tcd\tef
d) ab cd ef
Answer: d
Explanation: Each \t is converted to 4 blank spaces.
3. What will be the output of the following Python code?
print("ab\tcd\tef".expandtabs('+'))
a) ab+cd+ef
b) ab++++++++cd++++++++ef
c) ab cd ef
d) none of the mentioned
Answer: d
Explanation: TypeError, an integer should be passed as an argument.
4. What will be the output of the following Python code?
print("abcdef".find("cd") == "cd" in "abcdef")
a) True
b) False
c) Error
d) None of the mentioned
Answer: b
Explanation: The function find() returns the position of the sunstring in the given string whereas the in keyword returns a value of
Boolean type.
5. What will be the output of the following Python code?
print("abcdef".find("cd"))
a) True
b) 2
c) 3
d) None of the mentioned
Answer: b
Explanation: The first position in the given string at which the substring can be found is returned.
6. What will be the output of the following Python code?
print("ccdcddcd".find("c"))
a) 4
b) 0
c) Error
d) True
Answer: b
Explanation: The first position in the given string at which the substring can be found is returned.
7. What will be the output of the following Python code?
print("Hello {0} and {1}".format('foo', 'bin'))
a) Hello foo and bin
b) Hello {0} and {1} foo bin
c) Error
d) Hello 0 and 1
Answer: a
Explanation: The numbers 0 and 1 represent the position at which the strings are present.
8. What will be the output of the following Python code?
print("Hello {1} and {0}".format('bin', 'foo'))
a) Hello foo and bin
b) Hello bin and foo
c) Error
d) None of the mentioned
Answer: a
Explanation: The numbers 0 and 1 represent the position at which the strings are present.
9. What will be the output of the following Python code?
print("Hello {} and {}".format('foo', 'bin'))
a) Hello foo and bin
b) Hello {} and {}
c) Error
d) Hello and
Answer: a
Explanation: It is the same as Hello {0} and {1}.
10. What will be the output of the following Python code?
print("Hello {name1} and {name2}".format('foo', 'bin'))
a) Hello foo and bin
b) Hello {name1} and {name2}
c) Error
d) Hello and
Answer: c
Explanation: The arguments passed to the function format aren’t keyword arguments.
To practice all online quiz questions on Python, .
This set of Python Quiz focuses on “Strings”.
1. What will be the output of the following Python code?
print("xyyzxyzxzxyy".count('yy'))
a) 2
b) 0
c) error
d) none of the mentioned
Answer: a
Explanation: Counts the number of times the substring ‘yy’ is present in the given string.
2. What will be the output of the following Python code?
print("xyyzxyzxzxyy".count('yy', 1))
a) 2
b) 0
c) 1
d) none of the mentioned
Answer: a
Explanation: Counts the number of times the substring ‘yy’ is present in the given string, starting from position 1.
3. What will be the output of the following Python code?
print("xyyzxyzxzxyy".count('yy', 2))
a) 2
b) 0
c) 1
d) none of the mentioned
Answer: c
Explanation: Counts the number of times the substring ‘yy’ is present in the given string, starting from position 2.
4. What will be the output of the following Python code?
print("xyyzxyzxzxyy".count('xyy', 0, 100))
a) 2
b) 0
c) 1
d) error
Answer: a
Explanation: An error will not occur if the end value is greater than the length of the string itself.
5. What will be the output of the following Python code?
print("xyyzxyzxzxyy".count('xyy', 2, 11))
a) 2
b) 0
c) 1
d) error
Answer: b
Explanation: Counts the number of times the substring ‘xyy’ is present in the given string, starting from position 2 and ending at
position 11.
6. What will be the output of the following Python code?
print("xyyzxyzxzxyy".count('xyy', -10, -1))
a) 2
b) 0
c) 1
d) error
Answer: b
Explanation: Counts the number of times the substring ‘xyy’ is present in the given string, starting from position 2 and ending at
position 11.
7. What will be the output of the following Python code?
print('abc'.encode())
a) abc
b) ‘abc’
c) b’abc’
d) h’abc’
Answer: c
Explanation: A bytes object is returned by encode.
8. What is the default value of encoding in encode()?
a) ascii
b) qwerty
c) utf-8
d) utf-16
Answer: c
Explanation: The default value of encoding is utf-8.
9. What will be the output of the following Python code?
print("xyyzxyzxzxyy".endswith("xyy"))
a) 1
b) True
c) 3
d) 2
Answer: b
Explanation: The function returns True if the given string ends with the specified substring.
10. What will be the output of the following Python code?
print("xyyzxyzxzxyy".endswith("xyy", 0, 2))
a) 0
b) 1
c) True
d) False
Answer: d
Explanation: The function returns False if the given string does not end with the specified substring.
To practice all quiz questions on Python, .
This set of Python Scripting Interview Questions & Answers focuses on “Files”.
1. In file handling, what does this terms means “r, a”?
a) read, append
b) append, read
c) write, append
d) none of the mentioned
Answer: a
Explanation: r- reading, a-appending.
2. What is the use of “w” in file handling?
a) Read
b) Write
c) Append
d) None of the mentioned
Answer: b
Explanation: This opens the file for writing. It will create the file if it doesn’t exist, and if it does, it will overwrite it.
fh = open(“filename_here”, “w”).
3. What is the use of “a” in file handling?
a) Read
b) Write
c) Append
d) None of the mentioned
Answer: c
Explanation: This opens the fhe file in appending mode. That means, it will be open for writing and everything will be written to
the end of the file.
fh =open(“filename_here”, “a”).
4. Which function is used to read all the characters?
a) Read()
b) Readcharacters()
c) Readall()
d) Readchar()
Answer: a
Explanation: The read function reads all characters fh = open(“filename”, “r”)
content = fh.read().
5. Which function is used to read single line from file?
a) Readline()
b) Readlines()
c) Readstatement()
d) Readfullline()
Answer: b
Explanation: The readline function reads a single line from the file fh = open(“filename”, “r”)
content = fh.readline().
6. Which function is used to write all the characters?
a) write()
b) writecharacters()
c) writeall()
d) writechar()
Answer: a
Explanation: To write a fixed sequence of characters to a file
fh = open(“hello.txt”,”w”)
write(“Hello World”).
7. Which function is used to write a list of string in a file?
a) writeline()
b) writelines()
c) writestatement()
d) writefullline()
Answer: a
Explanation: With the writeline function you can write a list of strings to a file
fh = open(“hello.txt”, “w”)
lines_of_text = [“a line of text”, “another line of text”, “a third line”] fh.writelines(lines_of_text).
8. Which function is used to close a file in python?
a) Close()
b) Stop()
c) End()
d) Closefile()
Answer: a
Explanation: f.close()to close it and free up any system resources taken up by the open file.
9. Is it possible to create a text file in python?
a) Yes
b) No
c) Machine dependent
d) All of the mentioned
Answer: a
Explanation: Yes we can create a file in python. Creation of file is as shown below.
file = open(“newfile.txt”, “w”)
file.write(“hello world in the new file\n”)
file.write(“and another line\n”)
file.close().
10. Which of the following are the modes of both writing and reading in binary format in file?
a) wb+
b) w
c) wb
d) w+
Answer: a
Explanation: Here is the description below
“w” Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
“wb” Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for
writing.
“w+” Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new
file for reading and writing.
“wb+” Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for reading and writing.
TTo practice all scripting interview questions on Python, .
This set of Python Scripting Questions & Answers focuses on “Files”.
1. Which is/are the basic I/O connections in file?
a) Standard Input
b) Standard Output
c) Standard Errors
d) All of the mentioned
Answer: d
Explanation: Standard input, standard output and standard error. Standard input is the data that goes to the program. The
standard input comes from a keyboard. Standard output is where we print our data with the print keyword. Unless redirected, it is
the terminal console. The standard error is a stream where programs write their error messages. It is usually the text terminal.
2. What will be the output of the following Python code? (If entered name is sanfoundry)
1. import sys
2. print 'Enter your name: ',
3. name = ''
4. while True:
5. c = sys.stdin.read(1)
6. if c == '\n':
7. break
8. name = name + c
9. print 'Your name is:', name
a) sanfoundry
b) sanfoundry, sanfoundry
c) San
d) None of the mentioned
Answer: a
Explanation: In order to work with standard I/O streams, we must import the sys module. The read() method reads one character
from the standard input. In our example we get a prompt saying “Enter your name”. We enter our name and press enter. The
enter key generates the new line character: \n.
Output:
Enter your name: sanfoundry
Your name is: sanfoundry
3. What will be the output of the following Python code?
1. import sys
2. sys.stdout.write(' Hello\n')
3. sys.stdout.write('Python\n')
a) Compilation Error
b) Runtime Error
c) Hello Python
d)
Hello
Python
Answer: d
Explanation: None
Output:
Hello
Python

4. Which of the following mode will refer to binary data?


a) r
b) w
c) +
d) b
Answer:d
Explanation: Mode Meaning is as explained below:
r Reading
w Writing
a Appending
b Binary data
+ Updating.
5. What is the pickling?
a) It is used for object serialization
b) It is used for object deserialization
c) None of the mentioned
d) All of the mentioned
Answer: a
Explanation: Pickle is the standard mechanism for object serialization. Pickle uses a simple stack-based virtual machine that
records the instructions used to reconstruct the object. This makes pickle vulnerable to security risks by malformed or maliciously
constructed data, that may cause the deserializer to import arbitrary modules and instantiate any object.
6. What is unpickling?
a) It is used for object serialization
b) It is used for object deserialization
c) None of the mentioned
d) All of the mentioned
Answer: b
Explanation: We have been working with simple textual data. What if we are working with objects rather than simple text? For
such situations, we can use the pickle module. This module serializes Python objects. The Python objects are converted into byte
streams and written to text files. This process is called pickling. The inverse operation, reading from a file and reconstructing
objects is called deserializing or unpickling.
7. What is the correct syntax of open() function?
a) file = open(file_name [, access_mode][, buffering])
b) file object = open(file_name [, access_mode][, buffering])
c) file object = open(file_name)
d) none of the mentioned
Answer: b
Explanation: Open() function correct syntax with the parameter details as shown below:
file object = open(file_name [, access_mode][, buffering])
Here is parameters’ detail:
file_name: The file_name argument is a string value that contains the name of the file that you want to access.
access_mode: The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A
complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read
(r).
buffering: If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed
while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with
the indicated buffer size. If negative, the buffer size is the system default(default behavior).
8. What will be the output of the following Python code?
1. fo = open("foo.txt", "wb")
2. print "Name of the file: ", fo.name
3. fo.flush()
4. fo.close()
a) Compilation Error
b) Runtime Error
c) No Output
d) Flushes the file when closing them
Answer: d
Explanation: The method flush() flushes the internal buffer. Python automatically flushes the files when closing them. But you may
want to flush the data before closing any file.
9. Correct syntax of file.writelines() is?
a) file.writelines(sequence)
b) fileObject.writelines()
c) fileObject.writelines(sequence)
d) none of the mentioned
Answer: c
Explanation: The method writelines() writes a sequence of strings to the file. The sequence can be any iterable object producing
strings, typically a list of strings. There is no return value.
Syntax
Following is the syntax for writelines() method:
fileObject.writelines( sequence ).
10. Correct syntax of file.readlines() is?
a) fileObject.readlines( sizehint );
b) fileObject.readlines();
c) fileObject.readlines(sequence)
d) none of the mentioned
Answer: a
Explanation: The method readlines() reads until EOF using readline() and returns a list containing the lines. If the optional sizehint
argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up
to an internal buffer size) are read.
Syntax
Following is the syntax for readlines() method:
fileObject.readlines( sizehint );
Parameters
sizehint — This is the number of bytes to be read from the file.
To practice all scripting questions on Python, .
This set of Python Technical Interview Questions & Answers focuses on “Strings”.
1. What will be the output of the following Python statement?
1. >>>chr(ord('A'))
a) A
b) B
c) a
d) Error
Answer: a
Explanation: Execute in shell to verify.
2. What will be the output of the following Python statement?
1. >>>print(chr(ord('b')+1))
a) a
b) b
c) c
d) A
Answer: c
Explanation: Execute in the shell to verify.
3. Which of the following statement prints hello\example\test.txt?
a) print(“hello\example\test.txt”)
b) print(“hello\\example\\test.txt”)
c) print(“hello\”example\”test.txt”)
d) print(“hello”\example”\test.txt”)
Answer: b
Explanation: \is used to indicate that the next \ is not an escape sequence.
4. Suppose s is “\t\tWorld\n”, what is s.strip()?
a) \t\tWorld\n
b) \t\tWorld\n
c) \t\tWORLD\n
d) World
Answer: d
Explanation: Execute help(string.strip) to find details.
5. The format function, when applied on a string returns ___________
a) Error
b) int
c) bool
d) str
Answer: d
Explanation: Format function returns a string.
6. What will be the output of the “hello” +1+2+3?
a) hello123
b) hello
c) Error
d) hello6
Answer: c
Explanation: Cannot concatenate str and int objects.
7. What will be the output of the following Python code?
1. >>>print("D", end = ' ')
2. >>>print("C", end = ' ')
3. >>>print("B", end = ' ')
4. >>>print("A", end = ' ')
a) DCBA
b) A, B, C, D
c) D C B A
d) D, C, B, A will be displayed on four lines
Answer: c
Explanation: Execute in the shell.
8. What will be the output of the following Python statement?(python 3.xx)
1. >>>print(format("Welcome", "10s"), end = '#')
2. >>>print(format(111, "4d"), end = '#')
3. >>>print(format(924.656, "3.2f"))
a) Welcome# 111#924.66
b) Welcome#111#924.66
c) Welcome#111#.66
d) Welcome # 111#924.66
Answer: d
Explanation: Execute in the shell to verify.
9. What will be displayed by print(ord(‘b’) – ord(‘a’))?
a) 0
b) 1
c) -1
d) 2
Answer: b
Explanation: ASCII value of b is one more than a. Hence the output of this code is 98-97, which is equal to 1.
10. Say s=”hello” what will be the return value of type(s)?
a) int
b) bool
c) str
d) String
Answer: c
Explanation: str is used to represent strings in python.
To practice all technical interview questions on Python, .
This set of Python Technical Questions & Answers focuses on “While/For Loops”.
1. What will be the output of the following Python code?
for i in range(10):
if i == 5:
break
else:
print(i)
else:
print("Here")
a) 0 1 2 3 4 Here
b) 0 1 2 3 4 5 Here
c) 0 1 2 3 4
d) 1 2 3 4 5
Answer: c
Explanation: The else part is executed if control doesn’t break out of the loop.
2. What will be the output of the following Python code?
for i in range(5):
if i == 5:
break
else:
print(i)
else:
print("Here")
a) 0 1 2 3 4 Here
b) 0 1 2 3 4 5 Here
c) 0 1 2 3 4
d) 1 2 3 4 5
Answer: a
Explanation: The else part is executed if control doesn’t break out of the loop.
3. What will be the output of the following Python code?
x = (i for i in range(3))
for i in x:
print(i)
a) 0 1 2
b) error
c) 0 1 2 0 1 2
d) none of the mentioned
Answer: a
Explanation: The first statement creates a generator object.
4. What will be the output of the following Python code?
x = (i for i in range(3))
for i in x:
print(i)
for i in x:
print(i)
a) 0 1 2
b) error
c) 0 1 2 0 1 2
d) none of the mentioned
Answer: a
Explanation: We can loop over a generator object only once.
5. What will be the output of the following Python code?
string = "my name is x"
for i in string:
print (i, end=", ")
a) m, y, , n, a, m, e, , i, s, , x,
b) m, y, , n, a, m, e, , i, s, , x
c) my, name, is, x,
d) error
Answer: a
Explanation: Variable i takes the value of one character at a time.
6. What will be the output of the following Python code?
string = "my name is x"
for i in string.split():
print (i, end=", ")
a) m, y, , n, a, m, e, , i, s, , x,
b) m, y, , n, a, m, e, , i, s, , x
c) my, name, is, x,
d) error
Answer: c
Explanation: Variable i takes the value of one word at a time.
7. What will be the output of the following Python code snippet?
a = [0, 1, 2, 3]
for a[-1] in a:
print(a[-1])
a) 0 1 2 3
b) 0 1 2 2
c) 3 3 3 3
d) error
Answer: b
Explanation: The value of a[-1] changes in each iteration.
8. What will be the output of the following Python code snippet?
a = [0, 1, 2, 3]
for a[0] in a:
print(a[0])
a) 0 1 2 3
b) 0 1 2 2
c) 3 3 3 3
d) error
Answer: a
Explanation: The value of a[0] changes in each iteration. Since the first value that it takes is itself, there is no visible error in the
current example.
9. What will be the output of the following Python code snippet?
a = [0, 1, 2, 3]
i = -2
for i not in a:
print(i)
i += 1
a) -2 -1
b) 0
c) error
d) none of the mentioned
Answer: c
Explanation: SyntaxError, not in isn’t allowed in for loops.
10. What will be the output of the following Python code snippet?
string = "my name is x"
for i in ' '.join(string.split()):
print (i, end=", ")
a) m, y, , n, a, m, e, , i, s, , x,
b) m, y, , n, a, m, e, , i, s, , x
c) my, name, is, x,
d) error
Answer: a
Explanation: Variable i takes the value of one character at a time.
To practice all technical questions on Python, .
This set of Python Test focuses on “Strings”.
1. What will be the output of the following Python code snippet?
print('for'.isidentifier())
a) True
b) False
c) None
d) Error
Answer: a
Explanation: Even keywords are considered as valid identifiers.
2. What will be the output of the following Python code snippet?
print('abc'.islower())
a) True
b) False
c) None
d) Error
Answer: a
Explanation: There are no uppercase letters.
3. What will be the output of the following Python code snippet?
print(' 1,'.islower())
a) True
b) False
c) None
d) Error
Answer: a
Explanation: There are no uppercase letters.
4. What will be the output of the following Python code snippet?
print('11'.isnumeric())
a) True
b) False
c) None
d) Error
Answer: a
Explanation: All the character are numeric.
5. What will be the output of the following Python code snippet?
print('1.1'.isnumeric())
a) True
b) False
c) None
d) Error
Answer: b
Explanation: The character . is not a numeric character.
6. What will be the output of the following Python code snippet?
print(' a'.isprintable())
a) True
b) False
c) None
d) Error
Answer: a
Explanation: All those characters are printable.
7. What will be the output of the following Python code snippet?
print(''''''.isspace())
a) True
b) False
c) None
d) Error
Answer: b
Explanation: None.
8. What will be the output of the following Python code snippet?
print('\t'.isspace())
a) True
b) False
c) None
d) Error
Answer: a
Explanation: Tab Spaces are considered as spaces.
9. What will be the output of the following Python code snippet?
print('HelloWorld'.istitle())
a) True
b) False
c) None
d) Error
Answer: b
Explanation: The letter W is uppercased.
10. What will be the output of the following Python code snippet?
print('Hello World'.istitle())
a) True
b) False
c) None
d) Error
Answer: a
Explanation: It is in title form.
To practice all test questions on Python, .
This set of Python written test Questions & Answers focuses on “Files”.
1. Which of the following is not a valid mode to open a file?
a) ab
b) rw
c) r+
d) w+
Answer: b
Explanation: Use r+, w+ or a+ to perform both read and write operations using a single file object.
2. What is the difference between r+ and w+ modes?
a) no difference
b) in r+ the pointer is initially placed at the beginning of the file and the pointer is at the end for w+
c) in w+ the pointer is initially placed at the beginning of the file and the pointer is at the end for r+
d) depends on the operating system
Answer: b
Explanation: none.
3. How do you get the name of a file from a file object (fp)?
a) fp.name
b) fp.file(name)
c) self.__name__(fp)
d) fp.__name__()
Answer: a
Explanation: name is an attribute of the file object.
4. Which of the following is not a valid attribute of a file object (fp)?
a) fp.name
b) fp.closed
c) fp.mode
d) fp.size
Answer: d
Explanation: fp.size has not been implemented.
5. How do you close a file object (fp)?
a) close(fp)
b) fclose(fp)
c) fp.close()
d) fp.__close__()
Answer: c
Explanation: close() is a method of the file object.
6. How do you get the current position within the file?
a) fp.seek()
b) fp.tell()
c) fp.loc
d) fp.pos
Answer: b
Explanation: It gives the current position as an offset from the start of file.
7. How do you rename a file?
a) fp.name = ‘new_name.txt’
b) os.rename(existing_name, new_name)
c) os.rename(fp, new_name)
d) os.set_name(existing_name, new_name)
Answer: b
Explanation: os.rename() is used to rename files.
8. How do you delete a file?
a) del(fp)
b) fp.delete()
c) os.remove(‘file’)
d) os.delete(‘file’)
Answer: c
Explanation: os.remove() is used to delete files.
9. How do you change the file position to an offset value from the start?
a) fp.seek(offset, 0)
b) fp.seek(offset, 1)
c) fp.seek(offset, 2)
d) none of the mentioned
Answer: a
Explanation: 0 indicates that the offset is with respect to the start.
10. What happens if no arguments are passed to the seek function?
a) file position is set to the start of file
b) file position is set to the end of file
c) file position remains unchanged
d) error
Answer: d
Explanation: seek() takes at least one argument.
To practice all written questions on Python, .
This set of Tough Python Interview Questions & Answers focuses on “Mapping Functions”.
1. What will be the output of the following Python code?
x = ['ab', 'cd']
print(len(list(map(list, x))))))
a) 2
b) 4
c) error
d) none of the mentioned
Answer: c
Explanation: SyntaxError, unbalanced parenthesis.
2. What will be the output of the following Python code?
x = ['ab', 'cd']
print(list(map(list, x)))
a) [‘a’, ‘b’, ‘c’, ‘d’]
b) [[‘ab’], [‘cd’]]
c) [[‘a’, ‘b’], [‘c’, ‘d’]]
d) none of the mentioned
Answer: c
Explanation: Each element of x is converted into a list.
3. What will be the output of the following Python code?
x = [12, 34]
print(len(list(map(len, x))))
a) 2
b) 1
c) error
d) none of the mentioned
Answer: c
Explanation: TypeError, int has no len().
4. What will be the output of the following Python code?
x = [12, 34]
print(len(list(map(int, x))))
a) 2
b) 1
c) error
d) none of the mentioned
Answer: a
Explanation: list(map()) returns a list of two items in this example.
5. What will be the output of the following Python code?
x = [12, 34]
print(len(''.join(list(map(int, x)))))
a) 4
b) 2
c) error
d) none of the mentioned
Answer: c
Explanation: Cannot perform join on a list of ints.
6. What will be the output of the following Python code?
x = [12, 34]
print(len(''.join(list(map(str, x)))))
a) 4
b) 5
c) 6
d) error
Answer: a
Explanation: Each number is mapped into a string of length 2.
7. What will be the output of the following Python code?
x = [12, 34]
print(len(' '.join(list(map(int, x)))))
a) 4
b) 5
c) 6
d) error
Answer: d
Explanation: TypeError. Execute in shell to verify.
8. What will be the output of the following Python code?
x = [12.1, 34.0]
print(len(' '.join(list(map(str, x)))))
a) 6
b) 8
c) 9
d) error
Answer: c
Explanation: The floating point numbers are converted to strings and joined with a space between them.
9. What will be the output of the following Python code?
x = [12.1, 34.0]
print(' '.join(list(map(str, x))))
a) 12 1 34 0
b) 12.1 34
c) 121 340
d) 12.1 34.0
Answer: d
Explanation: str(ab.c) is ‘ab.c’.
10. What will be the output of the following Python code?
x = [[0], [1]]
print(len(' '.join(list(map(str, x)))))
a) 2
b) 3
c) 7
d) 8
Answer: c
Explanation: map() is applied to the elements of the outer loop.
To practice all tough interview questions on Python, .
This set of Tough Python Questions & Answers focuses on “While and For Loops”.
1. What will be the output of the following Python code?
x = 'abcd'
for i in x:
print(i)
x.upper()
a) a B C D
b) a b c d
c) A B C D
d) error
Answer: b
Explanation: Changes do not happen in-place, rather a new instance of the string is returned.
2. What will be the output of the following Python code?
x = 'abcd'
for i in x:
print(i.upper())
a) a b c d
b) A B C D
c) a B C D
d) error
Answer: b
Explanation: The instance of the string returned by upper() is being printed.
3. What will be the output of the following Python code?
x = 'abcd'
for i in range(x):
print(i)
a) a b c d
b) 0 1 2 3
c) error
d) none of the mentioned
Answer: c
Explanation: range(str) is not allowed.
4. What will be the output of the following Python code?
x = 'abcd'
for i in range(len(x)):
print(i)
a) a b c d
b) 0 1 2 3
c) error
d) 1 2 3 4
Answer: b
Explanation: i takes values 0, 1, 2 and 3.
5. What will be the output of the following Python code?
x = 'abcd'
for i in range(len(x)):
print(i.upper())
a) a b c d
b) 0 1 2 3
c) error
d) 1 2 3 4
Answer: c
Explanation: Objects of type int have no attribute upper().
6. What will be the output of the following Python code snippet?
x = 'abcd'
for i in range(len(x)):
i.upper()
print (x)
a) a b c d
b) 0 1 2 3
c) error
d) none of the mentioned
Answer: c
Explanation: Objects of type int have no attribute upper().
7. What will be the output of the following Python code snippet?
x = 'abcd'
for i in range(len(x)):
x[i].upper()
print (x)
a) abcd
b) ABCD
c) error
d) none of the mentioned
Answer: a
Explanation: Changes do not happen in-place, rather a new instance of the string is returned.
8. What will be the output of the following Python code snippet?
x = 'abcd'
for i in range(len(x)):
i[x].upper()
print (x)
a) abcd
b) ABCD
c) error
d) none of the mentioned
Answer: c
Explanation: Objects of type int aren’t subscriptable. However, if the statement was x[i], an error would not have been thrown.
9. What will be the output of the following Python code snippet?
x = 'abcd'
for i in range(len(x)):
x = 'a'
print(x)
a) a
b) abcd abcd abcd
c) a a a a
d) none of the mentioned
Answer: c
Explanation: range() is computed only at the time of entering the loop.
10. What will be the output of the following Python code snippet?
x = 'abcd'
for i in range(len(x)):
print(x)
x = 'a'
a) a
b) abcd abcd abcd abcd
c) a a a a
d) none of the mentioned
Answer: d
Explanation: abcd a a a is the output as x is modified only after ‘abcd’ has been printed once.
To practice all tough questions on Python, .
This set of Tricky Python Questions & Answers focuses on “Argument Parsing”.
1. What will be the output of the following Python code?
def foo(k):
k = [1]
q = [0]
foo(q)
print(q)
a) [0]
b) [1]
c) [1, 0]
d) [0, 1]
Answer: a
Explanation: A new list object is created in the function and the reference is lost. This can be checked by comparing the id of k
before and after k = [1].
2. How are variable length arguments specified in the function heading?
a) one star followed by a valid identifier
b) one underscore followed by a valid identifier
c) two stars followed by a valid identifier
d) two underscores followed by a valid identifier
Answer: a
Explanation: Refer documentation.
3. Which module in the python standard library parses options received from the command line?
a) getopt
b) os
c) getarg
d) main
Answer: a
Explanation: getopt parses options received from the command line.
4. What is the type of sys.argv?
a) set
b) list
c) tuple
d) string
Answer: b
Explanation: It is a list of elements.
5. What is the value stored in sys.argv[0]?
a) null
b) you cannot access it
c) the program’s name
d) the first argument
Answer: c
Explanation: Refer documentation.
6. How are default arguments specified in the function heading?
a) identifier followed by an equal to sign and the default value
b) identifier followed by the default value within backticks (“)
c) identifier followed by the default value within square brackets ([])
d) identifier
Answer: a
Explanation: Refer documentation.
7. How are required arguments specified in the function heading?
a) identifier followed by an equal to sign and the default value
b) identifier followed by the default value within backticks (“)
c) identifier followed by the default value within square brackets ([])
d) identifier
Answer: d
Explanation: Refer documentation.
8. What will be the output of the following Python code?
def foo(x):
x[0] = ['def']
x[1] = ['abc']
return id(x)
q = ['abc', 'def']
print(id(q) == foo(q))
a) True
b) False
c) None
d) Error
Answer: a
Explanation: The same object is modified in the function.
9. Where are the arguments received from the command line stored?
a) sys.argv
b) os.argv
c) argv
d) none of the mentioned
Answer: a
Explanation: Refer documentation.
10. What will be the output of the following Python code?
def foo(i, x=[]):
x.append(x.append(i))
return x
for i in range(3):
y = foo(i)
print(y)
a) [[[0]], [[[0]], [1]], [[[0]], [[[0]], [1]], [2]]]
b) [[0], [[0], 1], [[0], [[0], 1], 2]]
c) [0, None, 1, None, 2, None]
d) [[[0]], [[[0]], [1]], [[[0]], [[[0]], [1]], [2]]]
Answer: c
Explanation: append() returns None.
To practice all tricky questions on Python, .
Multiple Choice Questions(MCQ‟s)

Subject: Python Programming

Subject Code: KNC402

1|Pa g e
PYTHON PROGRAMING (KNC – 402)

UNIT 1

INTRODUCTION

Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991. Python is an object-oriented programming language created by Guido
Rossum in 1989. It is ideally designed for rapid prototyping of complex applications. It
has interfaces to many OS system calls and libraries and is extensible to C or C++.
Python programming is widely used in Artificial Intelligence, Natural Language
Generation, Neural Networks and other advanced fields of Computer Science. Python had
deep focus on code readability & this class will teach you python from basics.
 Python is Interpreted − Python is processed at runtime by the interpreter. You do
not need to compile your program before executing it. This is similar to PERL and
PHP.
 Python is Interactive − You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.
Python's features include −
 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
 Easy-to-read − Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.
 A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
 Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
 Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
 Databases − Python provides interfaces to all major commercial databases.

2|Pa g e
 GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
 Scalable − Python provides a better structure and support for large programs than
shell scripting.

Python Features

Python's features include −


 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
 Easy-to-read − Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.
 A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
 Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
 Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
 Scalable − Python provides a better structure and support for large programs than
shell scripting.

Type Conversion in Python

Python defines type conversion functions to directly convert one data type to another which
is useful in day to day and competitive programming. This article is aimed at providing the
information about certain conversion functions.
1. int(a,base) : This function converts any data type to integer. „Base‟ specifies
the base in which string is if data type is string.
2. float() : This function is used to convert any data type to a floating point number
3. ord() : This function is used to convert a character to integer.
4. hex() : This function is to convert integer to hexadecimal string.

3|Pa g e
5. oct() : This function is to convert integer to octal string.
6. tuple() : This function is used to convert to a tuple.
7. set() : This function returns the type after converting to set.
8. list() : This function is used to convert any data type to a list type.
9. dict() : This function is used to convert a tuple of order (key,value) into a
dictionary.
10. str() : Used to convert integer into a string.
11. complex(real,imag) : This function converts real numbers to complex(real,imag)
number.

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Python was developed by


A. Guido van Rossum
B. James Gosling
C. Dennis Ritchie
D. Bjarne Stroustrup

2. Python was developed in which year?


A. 1972
B. 1995
C. 1989
D. 1981

3. Python is written in which language?


A. C
B. C++
C. Java
D. None of the above

4. What is the extension of python file?


A. .p
B. .py
C. .python
D. None of the above

5. Python is Object Oriented Programming Language.


A. True
B. False
C. Neither true nor false
D. None of the above

6. Python 3.0 is released in which year?


A. 2000
B. 2008
C. 2011
D. 2016

4|Pa g e
7. Which of the following statements is true?
A. Python is a high level programming language.
B. Python is an interpreted language.
C. Python is an object-oriented language
D. All of the above

8. What is used to define a block of code in Python?


A. Parenthesis
B. Indentation
C. Curly braces
D. None of the above

9. By the use of which character, single line is made comment in Python?


A. *
B. @
C. #
D. !

10. What is a python file with .py extension called?


A. package
B. module
C. directory
D. None of the above

11. Which of the following statements are correct?


(i) Python is a high level programming language.
(ii) Python is an interpreted language.
(iii) Python is a compiled language.
(iv) Python program is compiled before it is interpreted.
A. i, ii
B. i, iv
C. ii, iii
D. ii, iv

12. Which of the following is incorrect variable name in Python?


A. variable_1
B. variable1
C. 1variable
D. _variable

13. Is Python case sensitive when dealing with identifiers?


a) yes
b) no
c) machine dependent
d) none of the mentioned

14. What is the maximum possible length of an identifier?


a) 31 characters
b) 63 characters
c) 79 characters

5|Pa g e
d) none of the mentioned

15. Which of the following is invalid?


a) _a = 1
b) __a = 1
c) __str__ = 1
d) none of the mentioned

16. Which of the following is an invalid variable?


a) my_string_1
b) 1st_string
c) foo
d) _

17. Why are local variable names beginning with an underscore discouraged?
a) they are used to indicate a private variables of a class
b) they confuse the interpreter
c) they are used to indicate global variables
d) they slow down execution

18. Which of the following is not a keyword?


a) eval
b) assert
c) nonlocal
d) pass

19. All keywords in Python are in _________


a) lower case
b) UPPER CASE
c) Capitalized
d) None of the mentioned

20. Which of the following is true for variable names in Python?


a) unlimited length
b) all private members must have leading and trailing underscores
c) underscore and ampersand are the only two special characters allowed
d) none of the mentioned

21. Which of the following is an invalid statement?


a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000

22. Which of the following cannot be a variable?


a) __init__
b) in
c) it
d) on

23. Which of these in not a core data type?


a) Lists
b) Dictionary

6|Pa g e
c) Tuples
d) Class

24. Given a function that does not return any value, What value is thrown by default when
executed in shell.
a) int
b) bool
c) void
d) None

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

>>>str="hello"
>>>str[:2]

a) he
b) lo
c) olleh
d) hello

26. Which of the following will run without errors?


a) round(45.8)
b) round(6352.898,2,5)
c) round()
d) round(7463.123,2,1)

27. What is the return type of function id?


a) int
b) float
c) bool
d) dict

28. In python we do not specify types, it is directly interpreted by the compiler, so consider the
following operation to be performed.

>>>x = 13 ? 2

objective is to make sure x has a integer value, select all that apply (python 3.xx)
a) x = 13 // 2
b) x = int(13 / 2)
c) x = 13 % 2
d) All of the mentioned

29. What error occurs when you execute the following Python code snippet?
apple = mango
a) SyntaxError
b) NameError
c) ValueError
d) TypeError

30. What will be the output of the following Python code snippet?

7|Pa g e
def example(a):
a = a + '2'
a = a*2
return a

>>>example("hello")

a) indentation Error
b) cannot perform mathematical operation on strings
c) hello2
d) hello2hello2

31. What data type is the object below?


L = [1, 23, 'hello', 1]
a) list
b) dictionary
c) array
d) tuple

32. In order to store values in terms of key and value we use what core data type.
a) list
b) tuple
c) class
d) dictionary

33. Which of the following results in a SyntaxError?


a) „”Once upon a time…”, she said.‟
b) “He said, „Yes!'”
c) „3\‟
d) ”‟That‟s okay”‟

34. The following is displayed by a print function call. Select all of the function calls that result
in this output.
1. tom
2. dick
3. harry

a) print('''tom
\ndick
\nharry''')
b) print(”‟tomdickharry”‟)
c) print(„tom\ndick\nharry‟)
d) print('tom
dick
harry')

35. What is the average value of the following Python code snippet?

>>>grade1 = 80
>>>grade2 = 90
>>>average = (grade1 + grade2) / 2

a) 85.0

8|Pa g e
b) 85.1
c) 95.0
d) 95.1

36. Select all options that print.


hello-how-are-you

a) print(„hello‟, „how‟, „are‟, „you‟)


b) print(„hello‟, „how‟, „are‟, „you‟ + „-„ * 4)
c) print(„hello-„ + „how-are-you‟)
d) print(„hello‟ + „-„ + „how‟ + „-„ + „are‟ + „you‟)

37. What is the return value of trunc()?


a) int
b) bool
c) float
d) None

38. How we can convert the given list into the set ?
a) list.set()
b) set.list()
c) set(list)
d) None of the above

39. If we change one data type to another, then it is called


a) Type conversion
b) Type casting
c) Both of the above
d) None of the above

40. What is list data type in Python ?


a) collection of integer number
b) collection of string
c) collection of same data type
d) collection of different data type

41. What is type casting in python ?


a) declaration of data type
b) destroy data type
c) Change data type property
d) None of the above

42. Which of the following can convert the string to float number ?
a) str(float,x)
b) float(str,int)
c) int(float(str))
d) float(str)

43. Which of the following function are used to convert the string into the list ?
a) map()
b) convertor()
c) split()
d) lambda

9|Pa g e
44. Which of the following is not the data type in python ?
a) List
b) Tuple
c) Set
d) Class

45. Which of the following is the data type possible in python?


a) int
b) list
c) dictionary
d) All of the above

46. Which of the following is the example of the type casting ?


a) int(2)
b) str(2)
c) str(list)
d) All of the above

ANSWERS
1.a 2.c 3.a 4.b 5.a 6.b 7.d 8.b 9.c 10.b 11.b 12.c 13.a 14.d 15.d
16.b 17.a (As Python has no concept of private variables, leading underscores are used to indicate
variables that must not be accessed from outside the class.) 18.a (eval can be used as a variable)
19.d 20.a 21b 22.b 23.d 24.d 25.a 26.a 27.a 28.d
29.b 30.a 31.a 32.d 33.c 34.c 35.a 36.c 37.a 38.c
39.c 40.d 41.c 42.d 43.c 44.d 45.d 46.d

Python Operators

1. Arithmetic operators: Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication and division.

OPERATOR DESCRIPTION SYNTAX

+ Addition: adds two operands x+y

- Subtraction: subtracts two x-y


operands

* Multiplication: multiplies two x*y


operands

/ Division (float): divides the first x/y


operand by the second

10 | P a g e
// Division (floor): divides the first x // y
operand by the second

% Modulus: returns the remainder x%y


when first operand is divided by
the second

** Power : Returns first raised to x ** y


power second

2. Relational Operators: Relational operators compares the values. It either


returns True or False according to the condition.

OPERATOR DESCRIPTION SYNTAX

> Greater than: True if left x>y


operand is greater than the right

< Less than: True if left operand is x<y


less than the right

== Equal to: True if both operands x == y


are equal

!= Not equal to - True if operands x != y


are not equal

>= Greater than or equal to: True if x >= y


left operand is greater than or
equal to the right

<= Less than or equal to: True if left x <= y


operand is less than or equal to
the right

3. Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOT operations.

OPERATOR DESCRIPTION SYNTAX

And Logical AND: True if both the x and y


operands are true

Or Logical OR: True if either of the x or y


operands is true

Not Logical NOT: True if operand is not x


false

11 | P a g e
4. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.

OPERATOR DESCRIPTION SYNTAX

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<

5. Assignment operators: Assignment operators are used to assign values to the variables.

OPERATOR DESCRIPTION SYNTAX

= Assign value of right side of x=y+z


expression to left side operand

+= Add AND: Add right side a+=b a=a+b


operand with left side operand
and then assign to left operand

-= Subtract AND: Subtract right a-=b a=a-b


operand from left operand and
then assign to left operand

*= Multiply AND: Multiply right a*=b a=a*b


operand with left operand and
then assign to left operand

/= Divide AND: Divide left a/=b a=a/b


operand with right operand and
then assign to left operand

%= Modulus AND: Takes modulus a%=b a=a%b


using left and right operands and
assign result to left operand

//= Divide(floor) AND: Divide left a//=b a=a//b


operand with right operand and
then assign the value(floor) to
left operand

**= Exponent AND: Calculate a**=b a=a**b


exponent(raise power) value

12 | P a g e
using operands and assign value
to left operand

&= Performs Bitwise AND on a&=b a=a&b


operands and assign value to left
operand

|= Performs Bitwise OR on a|=b a=a|b


operands and assign value to left
operand

^= Performs Bitwise xOR on a^=b a=a^b


operands and assign value to left
operand

>>= Performs Bitwise right shift on a>>=b a=a>>b


operands and assign value to left
operand

<<= Performs Bitwise left shift on a <<= b a= a


operands and assign value to left << b
operand

Special operators: There are some special type of operators like-

Identity operators-
is and is not are the identity operators both are used to check if two values are located on the same part
of the memory. Two variables that are equal does not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical

Membership operators-
in and not in are the membership operators; used to test whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence

# Operator Overloading in Python


Operator Overloading means giving extended meaning beyond their predefined
operational meaning. For example operator + is used to add two integers as well as join
two strings and merge two lists. It is achievable because „+‟ operator is overloaded by int
class and str class. You might have noticed that the same built-in operator or function
shows different behavior for objects of different classes, this is called Operator
Overloading.

How to overload the operators in Python?


Consider that we have two objects which are a physical representation of a class
(user-defined data type) and we have to add two objects with binary „+‟ operator it throws
an error, because compiler don‟t know how to add two objects. So we define a method for
an operator and that process is called operator overloading. We can overload all existing

13 | P a g e
operators but we can‟t create a new operator. To perform operator overloading, Python
provides some special function or magic function that is automatically invoked when it is
associated with that particular operator. For example, when we use + operator, the magic
method __add__ is automatically invoked in which the operation for + operator is
defined.

Any All in Python

Any and All are two built ins provided in python used for successive And/Or.

 Any
Returns true if any of the items is True. It returns False if empty or all are false. Any
can be thought of as a sequence of OR operations on the provided iterables.
It short circuit the execution i.e. stop the execution as soon as the result is known.
Syntax : any(list of iterables).

 All
Returns true if all of the items are True (or if the iterable is empty). All can be
thought of as a sequence of AND operations on the provided iterables. It also short
circuit the execution i.e. stop the execution as soon as the result is known.
Syntax : all(list of iterables).

Python Operators Precedence


The following table lists all operators from highest precedence to lowest.

Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method


names for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'td>

^| Bitwise exclusive `OR' and regular `OR'

14 | P a g e
<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators

Operator precedence affects how an expression is evaluated.


For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first multiplies 3*2 and then adds into 7.

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which is the correct operator for power(xy)?


a) X^y
b) X**y
c) X^^y
d) None of the mentioned

2. Which one of these is floor division?


a) /
b) //
c) %
d) None of the mentioned

3. What is the order of precedence in python?


i) Parentheses
ii) Exponential
iii) Multiplication
iv) Division
v) Addition
vi) Subtraction
a) i,ii,iii,iv,v,vi
b) ii,i,iii,iv,v,vi
c) ii,i,iv,iii,v,vi
d) i,ii,iii,iv,vi,v

4. What is the answer to this expression, 22 % 3 is?


a) 7
b) 1

15 | P a g e
c) 0
d) 5

5. Mathematical operations can be performed on a string.


a) True
b) False

6. Operators with the same precedence are evaluated in which manner?


a) Left to Right
b) Right to Left
c) Can‟t say
d) None of the mentioned

7. What is the output of this expression, 3*1**3?


a) 27
b) 9
c) 3
d) 1

8. Which one of the following has the same precedence level?


a) Addition and Subtraction
b) Multiplication, Division and Addition
c) Multiplication, Division, Addition and Subtraction
d) Addition and Multiplication

9. The expression Int(x) implies that the variable x is converted to integer.


a) True
b) False

10. Which one of the following has the highest precedence in the expression?
a) Exponential
b) Addition
c) Multiplication
d) Parentheses

11. What is the output of print 0.1 + 0.2 == 0.3?


a) True
b) False
c) Machine dependent
d) Error

12. Which of the following is not a complex number?


a) k = 2 + 3j
b) k = complex(2, 3)
c) k = 2 + 3l
d) k = 2 + 3J

13. What is the type of inf?


a) Boolean
b) Integer
c) Float
d) Complex

14. What does ~4 evaluate to?

16 | P a g e
a) -5
b) -4
c) -3
d) +3

15. What does ~~~~~~5 evaluate to?


a) +5
b) -11
c) +11
d) -5

16. Which of the following is incorrect?


a) x = 0b101
b) x = 0x4f5
c) x = 19023
d) x = 03964

17. What is the result of cmp(3, 1)?


a) 1
b) 0
c) True
d) False

18. Which of the following is incorrect?


a) float(„inf‟)
b) float(„nan‟)
c) float(‟56‟+‟78‟)
d) float(‟12+34′)

19. What is the result of round(0.5) – round(-0.5)?


a) 1.0
b) 2.0
c) 0.0
d) Value depends on Python version

20. What does 3 ^ 4 evaluate to?


a) 81
b) 12
c) 0.75
d) 7

21. What will be the output of the following Python code snippet if x=1?
x<<2
a) 8
b) 1
c) 2
d) 4

22. What will be the output of the following Python expression?


bin(29)
a) „0b10111‟
b) „0b11101‟

17 | P a g e
c) „0b11111‟
d) „0b11011‟

23. What will be the value of x in the following Python expression, if the result of
that expression is 2?
x>>2
a) 8
b) 4
c) 2
d) 1

24. What will be the output of the following Python expression if x=15 and y=12?
x&y
a) b1101
b) 0b1101
c) 12
d) 1101

25. Which of the following represents the bitwise XOR operator?


a) &
b) ^
c) |
d) !

26. Bitwise _________ gives 1 if either of the bits is 1 and 0 when both of the bits are
1.
a) OR
b) AND
c) XOR
d) NOT

27. What will be the output of the following Python expression?


4^12
a) 2
b) 4
c) 8
d) 12

28. What will be the output of the following Python code if a=10 and b =20?
a=10
b=20
a=a^b
b=a^b
a=a^bprint(a,b)
a) 10 20
b) 10 10

18 | P a g e
c) 20 10
d) 20 20

29. What will be the output of the following Python expression?


~100?
a) 101
b) -101
c) 100
d) -100

30. The value of the expressions 4/(3*(2-1)) and 4/3*(2-1) is the same.
a) True
b) False

31. What will be the value of the following Python expression?


4+3%5
a) 4
b) 7
c) 2
d) 0

32. Evaluate the expression given below if A = 16 and B = 15.


A % B // A
a) 0.0
b) 0
c) 1.0
d) 1

33. Which of the following operators has its associativity from right to left?
a) +
b) //
c) %
d) **

34. What will be the value of x in the following Python expression?


x = int(43.55+2/2)
a) 43
b) 44
c) 22
d) 23

35. What is the value of the following expression?


2+4.00, 2**4.0
a) (6.0, 16.0)
b) (6.00, 16.00)
c) (6, 16)

19 | P a g e
d) (6.00, 16.0)

36. Which of the following is the truncation division operator?


a) /
b) %
c) //
d) |

37. What are the values of the following Python expressions?


2**(3**2)
(2**3)**2
2**3**2
a) 64, 512, 64
b) 64, 64, 64
c) 512, 512, 512
d) 512, 64, 512

38. What is the value of the following expression?


8/4/2, 8/(4/2)
a) (1.0, 4.0)
b) (1.0, 1.0)
c) (4.0. 1.0)
d) (4.0, 4.0)

39. What is the value of the following expression?


float(22//3+3/3)
a) 8
b) 8.0
c) 8.3
d) 8.33

40. What will be the output of the following Python expression?


print(4.00/(2.0+2.0))
a) Error
b) 1.0
c) 1.00
d) 1

41. What will be the value of X in the following Python expression?


X = 2+9*((3*12)-8)/10
a) 30.0
b) 30.8
c) 28.4
d) 27.2

42. Which of the following expressions involves coercion when evaluated in Python?

20 | P a g e
a) 4.7 – 1.5
b) 7.9 * 6.3
c) 1.7 % 2
d) 3.4 + 4.6

43. What will be the output of the following Python expression?


24//6%3, 24//4//2
a) (1,3)
b) (0,3)
c) (1,0)
d) (3,1)

44. Which among the following list of operators has the highest precedence?
+, -, **, %, /, <<, >>, |
a) <<, >>
b) **
c) |
d) %

45. What will be the value of the following Python expression?


float(4+int(2.39)%2)
a) 5.0
b) 5
c) 4.0
d) 4

46. Which of the following expressions is an example of type conversion?


a) 4.0 + float(3)
b) 5.3 + 6.3
c) 5.0 + 3
d) 3 + 7

47. Which of the following expressions results in an error?


a) float(„10‟)
b) int(„10‟)
c) float(‟10.8‟)
d) int(‟10.8‟)

48. What will be the value of the following Python expression?


4+2**5//10
a) 3
b) 7
c) 77
d) 0

49. The expression 2**2**3 is evaluates as: (2**2)**3.

21 | P a g e
a) True
b) False

ANSWERS:
1.b 2.b 3.a 4.b 5.b 6.a 7.c 8.a 9.a 10.d 11.b 12.c
13.c 14.a 15.a 16.d 17.a 18.d 19.d 20.d 21.d 22.b
23.a 24.c 25.b 26.c 27.c 28.c 29.b 30.a 31.b 32.b
33.d 34.b 35.a 36.c 37.d 38.a 39.b 40.b 41.d 42.c
43.a 44.b 45.c 46.a 47.d 48.b 49.b

UNIT II

CONDITIONALS
If else statements

Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b

22 | P a g e
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

Example

If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

ELSE

The else keyword catches anything which isn't caught by the preceding conditions.

Example

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

ELIF - The elif keyword is pythons way of saying "if the previous conditions were not
true, then try this condition.

Example
a=33
b=33
if b>a:
print("bisreaterthana")
elif a==b:
print("a and b are equal")

23 | P a g e
 MULTIPLE CHOICE QUESTIONS ANSWERS

1. In Python, a decision can be made by using if else statement.


a. True b. False

2. Checking multiple conditions in Python requires elif statements.


a. True b. False

3. If the condition is evaluated to true, the statement(s) of if block will be


executed, otherwise the statement(s) in else block(if else is specified) will be
executed.
a. True b. False

4. What kind of statement is IF statement?


a. Concurrent b. Sequential
c. Assignment d. Selected assignment

5. Which one of the following is a valid Python if statement :

a. if (a => 22) b. if(a>=2)


c. if a>=2 : d. if a >= 22
6. What keyword would you use to add an alternative condition to an if
statement?
a. Else if b. Elseif
c. Elif d. None of the above

7. Can we write if/else into one line in python?

a. Yes
b. No
c. if/else not used in python
d. None of the above

8. In a Python program, a control structure:

a. Defines program-specific data structures


b. Directs the order of execution of the statements in the program
c. Dictates what happens before the program starts and after it terminates
d. None of the above
9. What will be output of this expression:
„p‟ + „q‟ if „12‟.isdigit() else „r‟ + „s‟

24 | P a g e
a. pq
b. rs
c. pqrs
d. pq12

10. Which statement will check if a is equal to b?

a. if a = b:
b. if a == b:
c. if a === c:
d. if a == b
11. What will be the output of given Python code?
str1="hello"
c=0
for x in str1:
if(x!="l"):
c=c+1
else:
pass print(c)
a. 2
b. 0
c. 4
d. 3
12. What does the following code print to the console?
if 5 > 10:
print("fan")
elif 8 != 9:
print("glass")
else:
print("cream")
a. Cream
B. Glass
c. Fan
d. No output

13. What does the following code print to the console?


name = "maria"
if name == "melissa":
print("usa")
elif name == "mary":
print("ireland")
else:
print("colombia")

25 | P a g e
a. usa b. ireland
c.colombia d. None of the above

14. What does the following code print to the console?


if "cat" == "dog":
print("prrrr")
else:
print("ruff")
a. ruff b. ruf
c. prrrr d. prr

15. What does the following code print to the console?


hair_color = "blue"
if 3 > 2:
if hair_color == "black":
print("You rock!")
else:
print("Boring")
a. blue b. black
c. You rock! d. Boring
16. What does the following code print to the console?
if True:
print(101)
else:
print(202)
a. true b. false
c. 101 d. 202

17. What does the following code print to the console?


if False:
print("Nissan")
elif True:
print("Ford")
elif True:
print("BMW")
else:

26 | P a g e
print("Audi")
a. Nissan b. Ford
c. BMW d. Audi

18. What does the following code print to the console?


if 1:
print("1 is truthy!")
else:
print("???")
a. 1 is truthy! b. ???
c. Invalid d. None of the above

19. What does the following code print to the console?


if 0:
print("huh?")
else:
print("0 is falsy!")
a. o b. Huh
c. 0 is falsy! d. None of the above

20. What does the following code print to the console?


if 88 > 100:
print("cardio")
a. 88 b. 100
b. cardio d. Nothing is printed..

1.a 2.a 3.a 4.b 5.c 6.c 7.a (Yes, we can write if/else in one
line. For eg i = 5 if a > 7 else 0. So, option A is correct.) 8.b 9.a ( If condition
is true so pq will be the output. So, option A is correct.) 10.b 11.d 12.b
13.c 14.a 15.d 16.c 17.b (The first elif that is True will be
executed when multiple elif statements are True.) 18.a (1 does not equal True, but it's
considered True in a boolean context. Values that are considered True in a boolean
context are called "truthy" and values that are considered False in a boolean context are
called "falsy".) 19. c 20. d

27 | P a g e
# PYTHON LOOPS

Python has two primitive loop commands:

 while loops
 for loops

The while Loop

With the while loop we can execute a set of statements as long as a condition is true.

Example

Print i as long as i is less than 6:

i=1
while i < 6:
print(i)
i += 1

The while loop requires relevant variables to be ready, in this example we need to define
an indexing variable, i, which we set to 1.

 Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string).

This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set
etc.

Example

Print each fruit in a fruit list:

28 | P a g e
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

 MULTIPLE CHOICE QUESTIONS ANSWERS

1.Which of the following is the loop in python ?

A. For
B. while
C. do while
D.1 and 2

2. for loop in python are work on


A. range
B. iteration
C. Both of the above
D. None of the above

3. For loop in python is


A. Entry control loop
B. Exit control loop
C. Simple loop
D. None of the above

4. for i in range(-3), how many times this loop will run ?


A. 0
B. 1
C. Infinite
D. Error

5. for i in [1,2,3]:, how many times a loop run ?


A. 0
B. 1
C. 2
D. 3
6. How many times it will print the statement ?, for i in range(100): print(i)
A. 101
B. 99
C. 100
D. 0

7. What is the final value of the i after this, for i in range(3): pass
A. 1
B. 2
C. 3
D. 0

8. What is the value of i after the for loop ?, for i in range(4):break

29 | P a g e
A. 1
B. 2
C. 3
D. 0

9. What is the output of the following?


x = 'abcd'
for i in x:
print(i.upper())
A. a b c d
B. A B C D
C. a B C D
D. error

10. What is the output of the following?


x = 'abcd'
for i in range(len(x)):
x[i].upper()
print (x)
A. abcd
B. ABCD
C. error
D. none of the mentioned

11. What is the output of the following?


d = {0: 'a', 1: 'b', 2: 'c'}
for x in d.values():
print(x)
A. 0 1 2
B. a b c
C. 0 a 1 b 2 c
D. none of the mentioned

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


x = ['ab', 'cd']for i in x: x.append(i.upper())print(x)
A. [„AB‟,‟CD‟]
B. [„ab‟,‟cd‟,‟AB‟,‟CD‟]
C. [„ab‟,‟cd‟]
D. None of the mentioned

13. What will be the output of the following Python code snippet?
x = 'abcd'
for i in range(len(x)):
x = 'a'
print(x)
A. a
B. abcd abcd abcd
C. a a a a
D. None of the mentioned

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

30 | P a g e
x = 'abcd'
for i in range(len(x)):
print(x)
x = 'a'
A. a
B. abcd abcd abcd abcd
C. a a a a
D. None of the mentioned

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


x = 123
for i in x:
print(i)
A. 1 2 3
B. 123
C. error
D. None of the mentioned

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


for i in range(2.0):
print(i)
A. 0.0 1.0
B. 0 1
C. error
D. None of the mentioned

17. What will be the output of the following Python code snippet?
for i in [1, 2, 3, 4][::-1]:
print (i)

A. 1234
B. 4321
C. error
D. none of the mentioned

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


for i in range(int(2.0)):
print(i)

A. 0.0 1.0
B. 0 1
C. error
D. none of the mentioned

19. What will be the output of the following Python code snippet?
x=2
for i in range(x):
x += 1
print (x)

31 | P a g e
A. 01234
B. 01
C. 3 4
D. 0 1 2 3

20. What will be the output of the following Python code snippet?
x=2
for i in range(x):
x -= 2
print (x)

A. 01234
B. 0 -2
C. 30
D. Error

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


for i in range(10):
if i == 5:
break
else:
print(i)
else:
print("Here")

A. 0 1 2 3 4 Here
B. 0 1 2 3 4 5 Here
C. 0 1 2 3 4
D. 0 1 2 3 4 5

ANSWERS :
1. D 2. C 3. A 4. A 5. D 6. C 7. B 8. D 9. B 10.
A 11. B 12.D ( The loop does not terminate as new elements are being added to the list in
each iteration.) 13.C ( range() is computed only at the time of entering the loop. ) 14.D
15.C (Objects of type int are not iterable.) 16. C ( Object of type float cannot be
interpreted as an integer.) 17.B 18.B 19.C 20.B 21.C

# While Loops
In Python, While Loops is used to execute a block of statements repeatedly until a given
condition is satisfied. And when the condition becomes false, the line immediately after the
loop in the program is executed. While loop falls under the category of indefinite
iteration. Indefinite iteration means that the number of times the loop is executed isn‟t
specified explicitly in advance.

32 | P a g e
Syntax
while expression:
Statement(s)

Example:
# Python program to illustrate while loop
count = 0
while (count < 3):
count = count + 1
print("Hello")

print()

# checks if list still contains any element


a = [1, 2, 3, 4]
while a:
print(a.pop())

Output:
Hello
Hello
Hello
1
2
3
4

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. In which of the following loop in python, we can check the condition ?


A. for loop
B. while loop
C. do while loop
D. None of the above

2. It is possible to create a loop using goto statement in python ?


A. Yes
B. No
C. Sometimes
D. None of the above

3. To break the infinite loop , which keyword we use ?


A. continue
B. break
C. exit
D. None of the above

33 | P a g e
4. While(0), how many times a loop run ?
A. 0
B. 1
C. 3
D. infinite

5. while(1==3):, how many times a loop run ?


A. 0
B. 1
C. 3
D. infinite

6. What is the output of the following?


i=2
while True:
if i%3 == 0:
break
print(i)
i += 2
A. 2 4 6 8 10 …
B. 2 4
C. 2 3
D. error

7. What is the output of the following?


x = "abcdef"
i = "i"
while i in x:
print(i, end=" ")

A. no output
B. i i i i i i …
C. a b c d e f
D. abcdef

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


i=1
while True:
if i%0O7 == 0:
break
print(i)
i += 1

A. 123456
B. 1234567
C. error
D. none of the mentioned

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


True = False
while True:
print(True)

34 | P a g e
break

A. True
B. False
C. None
D. none of the mentioned

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


i=0
while i < 5:
print(i)
i += 1
if i == 3:
Break
else:
print(0)

A. 0120
B. 012
C. None
D. none of the mentioned

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


x = "abcdef"
while i in x:
print(i, end=" ")

A. a b c d e f
B. Abcdef
C. i i i i i i...
D. Error

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


x = "abcdef" i = "a"
while i in x:
x = x[:-1]
print(i, end = " ")

A. a a a a a a
B. a a a a
C. i i i i i i
D. None of the mentioned

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


i=1
while True: if i%3 == 0: break print(i) i+=1

A. 1 2
B. 1 2 3
C. Error

35 | P a g e
D. None of the mentioned

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


i=1
while True: if i%O.7 == 0: break print(i) i += 1

A. 1 2 3 4 5 6
B. 1 2 3 4 5 6 7
C. Error
D. None of the mentioned

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


i = 5while True: if i%O.11 == 0: break print(i) i += 1

A. 5 6 7 8 9 10
B. 5 6 7 8
C. 5 6
D. Error

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


i=5
while True: if i%O.9 == 0: break print(i) i += 1
A. 5 6 7 8
B. 5 6 7 8 9
C. 5 6 7 8 9 10 11 12 13 14 15....
D. Error

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


i=1
while True: if i%2 == 0: break print(i) i += 2

A. 1
B. 1 2
C. 1 2 3 4 5 6 ....
D. 1 3 5 7 9 11 ....

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


i=2
while True:
if i%3 == 0:
break
print(i)
i += 2

A. 2 4 6 8 10 ....
B. 2 4
C. 2 3
D. Error

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


i = 1while False:
if i%2 == 0:
break

36 | P a g e
print(i)
i += 2

A. 1
B. 1 3 5 7 ...
C. 1 2 3 4 ....
D. none of the mentioned

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


True = False
while True:
print(True)
Break

A. true
B. false
C. error
D. none of the mentioned

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


i=0
while i < 5:
print(i)
i += 1
if i == 3:
Break
else:
print(0)

A. 0 1 2 0
B. 0 1 2
C. error
D. none of the mentioned

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


i=0
while i < 3:
print(i)
i += 1
else:
print(0)

A. 0 1 2 3 0
B. 0 1 2 0
C. 0 1 2
D. error

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


x = "abcdef"
i = "a"
while i in x:
x = x[1:]

37 | P a g e
print(i, end = " ")

A. a a a a a a
B. a
C. no output
D. error

ANSWERS :

1. B 2.B 3.B 4.A 5.A 6.B 7.A 8.A 9.D(SyntaxError, True


is a keyword and it‟s value cannot be changed.) 10.B 11.D 12.A 13.C 14.A
15.B 16.D 17.D 18.B 19.D 20.D 21.B 22.B 23.B

UNIT 3

A function is a block of organized, reusable code that is used to perform a single, related action. Functions
provide better modularity for your application and a high degree of code reusing.
Python gives many built-in functions like print(), etc. but you can also create your own functions. These
functions are called user-defined functions.

Defining a Function
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
 Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.

38 | P a g e
 The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Syntax:

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to inform them in the
same order that they were defined.
 Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis.

Example
Def my_function():
print("Hello from a function")
my_function()xample »

Function Arguments

You can call a function by using the following types of formal arguments −

 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

 Required arguments

39 | P a g e
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.

To call the function printme(), you definitely need to pass one argument, otherwise it
gives a syntax error.

 Keyword arguments

Keyword arguments are related to the function calls. When you use keyword arguments in
a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.

 Default arguments

A default argument is an argument that assumes a default value if a value is not provided
in the function call for that argument.

 Variable-length arguments

You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in
the function definition, unlike required and default arguments.

# Scope of Variables

All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python −

 Global variables
 Local variables

 Global vs. Local variables

Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into
scope. Following is a simple example −

40 | P a g e
total = 0; # This is global variable.# Function definition is heredef sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );print "Outside the function global total : ", total
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of the following functions is a built-in function in python?


A. seed()
B. sqrt()
C. factorial()
D. print()

2. What will be the output of the following Python expression?


round(4.576)

A. 4.5
B. 5
C. 4
D. 4.6

3. The function pow(x,y,z) is evaluated as:

A. (x**y)**z
B. (x**y)/z
C. (x**y)%z
D. (x**y)*z

4. What will be the output of the following Python function?


all([2,4,0,6])

A. Error
B. True
C. False
D. 0

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


any([2>8, 4>2, 1>2])

41 | P a g e
A. Error
B. True
C. False
D. 4>2

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


import math
abs(math.sqrt(25))

A. Error
B. -5
C. 5
D. 5.0

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


sum(2,4,6)sum([1,2,3])

A. Error,6
B. 12, Error
C. 12,6
D. Error, Error

8. What will be the output of the following Python function?


min(max(False,-3,-4), 2,7)

A. 2
B. False
C. -3
D. -4

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


chr(„97‟)chr(97)

A. a Error
B. „a‟ Error
C. Error a
D. Error Error

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


complex(1+2j)

A. Error
B. 1
C. 2j
D. 1+2j

11. The function divmod(a,b), where both „a‟ and „b‟ are integers is evaluated as:
A. (a%b,a//b)
B. (a//b,a%b)
C. (a//b,a*b)
D. (a/b,a%b)

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

42 | P a g e
list(enumerate([2, 3]))

A. Error
B. [(1,2),(2,3)]
C. [(0,2),(1,3)]
D. [(2,3)]

13. Which of the following functions does not necessarily accept only iterables as arguments?

A. enumerate()
B. all()
C. chr()
D. max()

14. Which of the following functions accepts only integers as arguments?

A. ord()
B. min()
C. chr()
D. any()

15. Which of the following functions will not result in an error when no arguments are passed
to it?

A. min()
B. divmod()
C. all()
D. float()

16. What will be the output of the following Python function?


hex(15)

A. f
B. OxF
C. OXf
D. Oxf

17. What will be the output of the following Python function?


len(["hello",2, 4, 6])

A. 4
B. 3
C. Error
D. 6

18. Which of the following is the use of function in python?

A. functions are reusable pieces of programs


B. functions don‟t provide better modularity for your application
C. you can‟t also create your own functions
D. all of the mentioned

19. Which keyword is used for function?

43 | P a g e
A. Fun
B. Define
C. Def
D. Function

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

def sayHello():
print('Hello World!')

sayHello()
sayHello()

A. Hello World! Hello World!


B. 'Hello World!' 'Hello World!'
C. Hello Hello
D. None of the mentioned

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


def printMax(a, b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
printMax(3, 4)

A. 3
B. 4
C. 4 is maximum
D. None of the mentioned

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


x = 50
def func(x):
print('x is', x)
x=2
print('Changed local x to', x)
func(x)
print('x is now', x)

A. x is now 50
B. x is now 2
C. x is now 100
D. None of the mentioned

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

def say(message, times = 1):


print(message * times)

44 | P a g e
say('Hello')
say('World', 5)

A. Hello WorldWorldWorldWorldWorld
B. Hello World 5
C. Hello World,World,World,World,World
D. Hello HelloHelloHelloHelloHello

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

def func(a, b=5, c=10):


print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c = 24)
func(c = 50, a = 100)

A. a is 7 and b is 3 and c is 10 a is 25 and b is 5 and c is 24 a is 5 and b is 100 and c is 50


B. a is 3 and b is 7 and c is 10 a is 5 and b is 25 and c is 24 a is 50 and b is 100 and c is 5
C. a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50
D. None of the mentioned

25. Which of the following is a feature of DocString?


A. Provide a convenient way of associating documentation with Python modules, functions, c
classes,and methods
B. All functions should have a docstring
C. Docstrings can be accessed by the __doc__ attribute on objects
D. All of the mentioned

26. Which are the advantages of functions in python?


A. Reducing duplication of code
B. Decomposing complex problems into simpler pieces
C. Improving clarity of the code
D. All of the mentioned

27. What are the two main types of functions?


A. Custom function
B. Built-in function & User defined function
C. User function
D. System function

28. Where is function defined?


A. Module
B. Class
C. Another function
D. All of the mentioned

29. What is called when a function is defined inside a class?


A. Module
B. Class
C. Another function
D. Method

45 | P a g e
30. Which of the following is the use of id() function in python?
A. Id returns the identity of the object
B. Every object doesn‟t have a unique id
C. All of the mentioned
D. None of the mentioned

31. Which of the following refers to mathematical function?


A. sqrt
B. rhombus
C. add
D. Rhombus

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

def cube(x):

return x * x * x

x = cube(3)
print x

A. 9
B. 3
C. 27
D. 30

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

def C2F(c):

return c * 9/5 + 32

print C2F(100)

print C2F(0)

A. 212
32
B. 314
24
C. 567
98
D. None of the mentioned

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

def power(x, y=2):


r=1
for i in range(y):
r=r*x
return r
print power(3)

46 | P a g e
print power(3, 3)

A. 212
32
B. 9
27
C. 567
98
D. None of the mentioned.

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


def foo(k):
k[0] = 1
q = [0]
foo(q)print(q)
A. [0]
B. [1]
C. [1, 0]
D. [0, 1]

36. How are keyword arguments specified in the function heading?


A. one-star followed by a valid identifier
B. one underscore followed by a valid identifier
C. two stars followed by a valid identifier
D. two underscores followed by a valid identifier

37. How many keyword arguments can be passed to a function in a single function call?
A. zero
B. one
C. zero or more
D. one or more

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


def foo(fname, val):
print(fname(val))
foo(max, [1, 2, 3])
foo(min, [1, 2, 3])
A. 3 1
B. 1 3
C. error
D. none of the mentioned

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


def foo():
return total + 1
total = 0print(foo())
A. 0
B. 1
C. error
D. none of the mentioned

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


def foo():

47 | P a g e
total += 1
return total
total = 0print(foo())
A. 0
B. 1
C. error
D. none of the mentioned

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


def foo(k):
k = [1]
q = [0]
foo(q)print(q)
A. [0]
B. [1]
C. [1, 0]
D. [0, 1]

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


def f1():
x=15
print(x)
x=12
f1()
A. Error
B. 12
C. 15
D. 1512

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


def f1():
x=100
print(x)
x=+1
f1()
A. Error
B. 100
C. 101
D. 99

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


def san(x):
print(x+1)
x=-2
x=4
san(12)
A. 13
B. 10
C. 2
D. 5

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


def f1():

48 | P a g e
global x
x+=1
print(x)
x=12print("x")
A. Error
B. 13
C. 13
x
D. X

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


def f1(x):
global x
x+=1
print(x)
f1(15)print("hello")
A. error
B. hello
C. 16
D. 16
hello

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


x=12def f1(a,b=x):
print(a,b)
x=15
f1(4)
A. Error
B. 12 4
C. 4 12
D. 4 15

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


def f1(a,b=[]):
b.append(a)
return bprint(f1(2,[3,4]))
A. [3,2,4]
B. [2,3,4]
C. Error
D. [3,4,2]

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


def f(p, q, r):
global s
p = 10
q = 20
r = 30
s = 40
print(p,q,r,s)
p,q,r,s = 1,2,3,4
f(5,10,15)
A. 1 2 3 4
B. 5 10 15 4

49 | P a g e
C. 10 20 30 40
D. 5 10 15 40

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


def f(x):
print("outer")
def f1(a):
print("inner")
print(a,x)
f(3)
f1(1)
A. outer
error
B. inner
error
C. outer
inner
D. error

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


x = 5 def f1():
global x
x = 4def f2(a,b):
global x
return a+b+x
f1()
total = f2(1,2)print(total)
A. Error
B. 7
C. 8
D. 15

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


x=100def f1():
global x
x=90def f2():
global x
x=80print(x)
A. 100
B. 90
C. 80
D. Error

53. Read the following Python code carefully and point out the global variables?
y, z = 1, 2def f():
global x
x = y+z
A. x
B. y and z
C. x, y and z
D. Neither x, nor y, nor z

50 | P a g e
54. Which of the following data structures is returned by the functions globals() and locals()?
A. list
B. set
C. dictionary
D. tuple

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


x=1def cg():
global x
x=x+1
cg()
x
A. 2
B. 1
C. 0
D. Error

56. What happens if a local variable exists with the same name as the global variable you want to
access?
A. Error
B. The local variable is shadowed.
C. Undefined behavior.
D. The global variable is shadowed.

ANSWERS :

1.D 2.B 3.A 4.C 5.B 6.D 7.A 8.B 9.C 10.D
11.B 12.C 13.C 14.C 15.D 16.D 17.A 18.A
19.C 20.A 21.C 22.A 23.A 24.C 25.D 26.D
27.B 28.D 29.D 30.A 31.A 32.C 33.A 34.B 35.B
36.C 37.C 38.A 39.B 40.C 41.A 42.C 43.B 44.A 45.D
46.A 47.C 48.D 49.C 50.A 51.B 52.A 53.C 54.C 55.A
56.D

STRINGS

Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as
simple as assigning a value to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"

51 | P a g e
Accessing Values in Strings
Python does not support a character type; these are treated as strings of length one, thus also
considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain your
substring. For example −

var1 = 'Hello World!'


var2 = "Python Programming"
print "var1[0]: ", var1[0]print "var2[1:5]: ", var2[1:5]

When the above code is executed, it produces the following result −

var1[0]: H
var2[1:5]: ytho

 Python String Concatenation


In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have
a character data type, a single character is simply a string with a length of 1. Square brackets [] can be
used to access elements of the string.
String Concatenation is the technique of combining two strings. String Concatenation can be done
using many ways.

Using + Operator
It‟s very easy to use + operator for string concatenation. This operator can be used to add multiple
strings together. However, the arguments must be a string.
Example

var1 = "Hello "


var2 = "World"

# + Operator is used to combine strings


var3 = var1 + var2
print(var3)
Output:
Hello World
(Here, the variable var1 stores the string “Hello ” and variable var2 stores the string “World”. The +
Operator combines the string that is stored in the var1 and var2 and stores in another variable var3).

 Accessing characters in Python


In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing
allows negative address references to access characters from the back of the String, e.g. -1 refers to the
last character, -2 refers to the second last character and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be
passed as an index, float or other types will cause a TypeError.

 String Slicing
To access a range of characters in the String, method of slicing is used. Slicing in a String is done by
using a Slicing operator (colon).
# Python Program to
# demonstrate String slicing

52 | P a g e
# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing 3rd to 12th character


print("\nSlicing characters from 3-12: ")
print(String1[3:12])

# Printing characters between


# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])
Output:
Initial String:
GeeksForGeeks

Slicing characters from 3-12:


ksForGeek

Slicing characters between 3rd and 2nd last character:


ksForGee

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. What will be the output of the following Python statement?


"a"+"bc"
a)a
b)bc
c)bca
d) abc
Answer: d

2. What will be the output of the following Python statement?


"abcd"[2:]
a)a
b)ab
c)cd
d) dc
Answer: c
3. The output of executing string.ascii_letters can also be achieved by:
a) string.ascii_lowercase_string.digits
b) string.ascii_lowercase+string.ascii_upercase
c) string.letters
d) string.lowercase_string.upercase
Answer: b

53 | P a g e
4. What will be the output of the following Python code?
>>> str1 = 'hello'
>>> str2 = ','
>>> str3 = 'world'
>>> str1[-1:]

a) olleh
b) hello
c) h
d) o
Answer: d
5. What arithmetic operators cannot be used with strings?
a)+
b)*
c) –
d) All of the mentioned
Answer: c
6. What will be the output of the following Python code?
>>>print (r"\nhello")
a) a new line and hello
b) \nhello
c) the letter r and then hello
d) error
Answer: b
7. What will be the output of the following Python statement?
>>>print('new' 'line')
a) Error
b) Output equivalent to print „new\nline‟
c) newline
d) new line
Answer: c
8. What will be the output of the following Python code?
>>>str1="helloworld"
>>>str1[::-1]
a) dlrowolleh
b) hello
c) world
d) helloworld
Answer: a
9. print(0xA + 0xB + 0xC):
a) 0xA0xB0xC
b) Error
c) 0x22
d) 33
Answer: d
10. What will be the output of the following Python code?
>>>example = "snow world"
>>>print("%s" % example[4:7])
a) wo
b) world
c) sn
d) rl

54 | P a g e
Answer: a
11. What will be the output of the following Python code?
>>>example = "snow world"
>>>example[3] = 's'
>>>print example
a) snow
b) snow world
c) Error
d) snos world
Answer: c

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


>>>max("what are you")
a) error
b) u
c) t
d) y
Answer: d
13. Given a string example=”hello” what is the output of example.count(„l‟)?
a)2
b)1
c) None
d) 0
Answer: a
14. What will be the output of the following Python code?
>>>example = "helle"
>>>example.find("e")
a) Error
b) -1
c) 1
d) 0
Answer: c
15. What will be the output of the following Python code?
>>>example = "helle"
>>>example.rfind("e")
a) -1
b) 4
c) 3
d) 1
Answer: b
16. What will be the output of the following Python code?
>>example="helloworld"
>>example[::-1].startswith("d")
a) dlrowolleh
b) True
c) -1
d) None
Answer: b
17. To concatenate two strings to a third what statements are applicable?
a)s3=s1s2
b)s3=s1.add(s2)
c)s3=s1.__add__(s2)
d) s3 = s1 * s2

55 | P a g e
Answer: c
Explanation: __add__ is another method that can be used for concatenation.
18. Which of the following statement prints hello\example\test.txt?
a)print(“hello\example\test.txt”)
b)print(“hello\\example\\test.txt”)
c)print(“hello\”example\”test.txt”)
d) print(“hello”\example”\test.txt”)
Answer: b
Explanation: \is used to indicate that the next \ is not an escape sequence.
19. Suppose s is “\t\tWorld\n”, what is s.strip()?
a)\t\tWorld\n
b)\t\tWorld\n
c)\t\tWORLD\n
d) World
Answer: d
20. The format function, when applied on a string returns ___________
a) Error
b) int
c) bool
d) str
Answer: d
21. What will be the output of the “hello” +1+2+3?
a) hello123
b) hello
c) Error
d) hello6
Answer: c
22. What will be the output of the following Python code?
>>>print("D", end = ' ')
>>>print("C", end = ' ')
>>>print("B", end = ' ')
>>>print("A", end = ' ')
a) DCBA
b) A,B,C,D
c) DCBA
d) D, C, B, A will be displayed on four lines
Answer: c
23. What will be displayed by print(ord(„b‟) – ord(„a‟))?
a)0
b)1
c)-1
d) 2
Answer: b
Explanation: ASCII value of b is one more than a. Hence the output of this code is 98-97, which is
equal to 1.
24. Say s=”hello” what will be the return value of type(s)?
a) int
b) bool
c) str
d) String
Answer: c
25. What is “Hello”.replace(“l”, “e”)?
a) Heeeo

56 | P a g e
b) Heelo
c) Heleo
d) None
26. To retrieve the character at index 3 from string s=”Hello” what command do we execute
(multiple answers allowed)?
a) s[]
b) s.getitem(3)
c) s.__getitem__(3)
d) s.getItem(3)
27. To return the length of string s what command do we execute?
a) s.__len__()
b) len(s)
c) size(s)
d) s.size()
28. Suppose i is 5 and j is 4, i + j is same as ________
a) i.__add(j)
b) i.__add__(j)
c) i.__Add(j)
d) i.__ADD(j)

29. What function do you use to read a string?


a) input(“Enter a string”)
b) eval(input(“Enter a string”))
c) enter(“Enter a string”)
d) eval(enter(“Enter a string”))

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


print("abc DEF".capitalize())
a) abc def
b) ABC DEF
c) Abc def
d) Abc Def

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


print("xyyzxyzxzxyy".count('yy'))
a) 2
b) 0
c) error
d) none of the mentioned

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


print("xyyzxyzxzxyy".count('yy', 2))
a) 2
b) 0
c) 1
d) none of the mentioned
Explanation: Counts the number of times the substring „yy‟ is present in the given string, starting from
position 2.
33. What will be the output of the following Python code?
print("xyyzxyzxzxyy".endswith("xyy"))
a) 1
b) True

57 | P a g e
c) 3
d) 2
34. What will be the output of the following Python code?
print("abcdef".find("cd"))
a) True
b) 2
c) 3
d) None of the mentioned

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


print("Hello {0} and {1}".format('foo', 'bin'))
a) Hello foo and bin
b) Hello {0} and {1} foo bin
c) Error
d) Hello 0 and 1
36. What will be the output of the following Python code?
print("Hello {name1} and {name2}".format(name1='foo', name2='bin'))
a) Hello foo and bin
b) Hello {name1} and {name2}
c) Error
d) Hello and

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


print('ab12'.isalnum())
a) True
b) False
c) None
d) Error

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


print('a B'.isalpha())
a) True
b) False
c) None
d) Error
Explanation: Space is not a letter.
39. What will be the output of the following Python code snippet?
print('0xa'.isdigit())
a) True
b) False
c) None
d) Error

40. What will be the output of the following Python code snippet?
print('for'.isidentifier())
a) True
b) False
c) None
d) Error

41. What will be the output of the following Python code snippet?
print('abc'.islower())
a) True

58 | P a g e
b) False
c) None
d) Error

42. What will be the output of the following Python code snippet?
print('11'.isnumeric())
a) True
b) False
c) None
d) Error

43. What will be the output of the following Python code snippet?
print('HelloWorld'.istitle())
a) True
b) False
c) None
d) Error

44. What will be the output of the following Python code snippet?
print('abcdef12'.replace('cd', '12'))
a) ab12ef12
b) abcdef12
c) ab12efcd
d) none of the mentioned

45. What will be the output of the following Python code snippet?
print('Ab!2'.swapcase())
a) AB!@
b) ab12
c) aB!2
d) aB1@

ANSWERS :

1.d 2.c 3.b 4.d 5.c 6.b 7.c 8.a 9.d 10.a 11.c 12.d 13.a
14.c 15.b 16.b 17.c 18.b 19.d 20.d 21.c 22.c 23.b
24.c 25.a 26.c 27.a 28.b 29.a 30.c 31.a 32.c 33.b
34.b 35.a 36.a 37.a 38.b 39.b 40.a 41.a 42.a 43.b
44.a 45.c

TUPLES

A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just
like lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.

59 | P a g e
Creating a tuple is as simple as putting different comma-separated values. Optionally you
can put these comma-separated values between parentheses also. For example −

tup1 = ('physics', 'chemistry', 1997, 2000)


tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"

The empty tuple is written as two parentheses containing nothing −


tup1 = ()

To write a tuple containing a single value you have to include a comma, even though
there is only one value −
tup1 = (50,)

 Accessing Values in Tuples

To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −

tup1 = ('physics', 'chemistry', 1997, 2000)


tup2 = (1, 2, 3, 4, 5, 6, 7 );print "tup1[0]: ", tup1[0];print "tup2[1:5]: ", tup2[1:5]

Output:
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

 Updating Tuples

Tuples are immutable which means you cannot update or change the values of tuple
elements. You are able to take portions of existing tuples to create new tuples as the
following example demonstrates −

tup1 = (12, 34.56)


tup2 = ('abc', 'xyz')
# Following action is not valid for tuples# tup1[0] = 100
# So let's create a new tuple as follows
tup3 = tup1 + tup2;print tup3

Output:
(12, 34.56, 'abc', 'xyz')

 Delete Tuple Elements



Removing individual tuple elements is not possible. There is, of course, nothing wrong

60 | P a g e
with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example

tup = ('physics', 'chemistry', 1997, 2000)


print tup
del tup
print "After deleting tup : "
print tup

Basic Tuples Operations

Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string.

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

 Indexing, Slicing, and Matrixes

Because tuples are sequences, indexing and slicing work the same way for tuples as they
do for strings. Assuming following input −
L = ('spam', 'Spam', 'SPAM!')

Python Expression Results Description

L[2] 'SPAM!' Offsets start at zero

L[-2] 'Spam' Negative: count from the right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

 MULTIPLE CHOICE QUESTIONS ANSWERS

61 | P a g e
1. Which of the following is a Python tuple?
a) [1, 2, 3]
b) (1, 2, 3)
c) {1, 2, 3}
d) {}

2.Suppose t = (1, 2, 4, 3), which of the following is incorrect?


a) print(t[3])
b) t[3] = 45
c) print(max(t))
d) print(len(t))

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


>>>t=(1,2,4,3)
>>>t[1:3]
a)(1,2)
b)(1,2,4)
c)(2,4)
d) (2, 4, 3)

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


t=(1,2,4,3)
t[1:-1]
a)(1,2)
b)(1,2,4)
c)(2,4)
d) (2, 4, 3)

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


t = (1, 2, 4, 3, 8, 9)
[t[i] for i in range(0, len(t), 2)]
a)[2,3,9]
b)[1,2,4,3,8,9]
c)[1,4,8]
d) (1, 4, 8)

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


d = {"john":40, "peter":45}
d["john"]
a)40
b)45
c)“john”
d) “peter”

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

62 | P a g e
t = (1, 2)
2*t
a)(1,2,1,2)
b)[1,2,1,2]
c)(1,1,2,2)
d) [1, 1, 2, 2]

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


t1 = (1, 2, 4, 3)
t2 = (1, 2, 3, 4)
t1 < t2
a)True
b)False
c)Error
d) None

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


my_tuple = (1, 2, 3, 4)
my_tuple.append( (5, 6, 7) )
print len(my_tuple)
a)1
b)2
c)5
d) Error

10. What is the data type of (1)?a)Tuple


b)Integer
c)List
d) Both tuple and integer

11. If a=(1,2,3,4), a[1:-1] is _________


a)Error, tuple slicing doesn‟t exist
b)[2,3]
c)(2,3,4)
d) (2,3)

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


a=(1,2,(4,5))
b=(1,2,(3,4))
a<b
a) False
b) True
c) Error, < operator is not valid for tuples
d) Error, < operator is valid for tuples but not if there are sub-tuples

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

63 | P a g e
a=("Check")*3
a
a)(„Check‟,‟Check‟,‟Check‟)
b)* Operator not valid for tuples
c)(„CheckCheckCheck‟)
d) Syntax error

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


a=(1,2,3,4)
del(a[2])
a)Now,a=(1,2,4)
b)Now,a=(1,3,4)
c)Now,a=(3,4)
d) Error as tuple is immutable

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


a=(2,3,4)
sum(a,3)
a) Too many arguments for sum() method
b) The method sum() doesn‟t exist for tuples
c)12
d) 9

16. Is the following Python code valid?


a=(1,2,3,4)
del a
a)No because tuple is immutable
b)Yes, first element in the tuple is deleted
c)Yes, the entire tuple is deleted
d) No, invalid syntax for del method

17. What type of data is: a=[(1,1),(2,4),(3,9)]?


a) Array of tuples
b) List of tuples
c) Tuples of lists
d) Invalid type

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


a=(0,1,2,3,4)
b=slice(0,2)
a[b]
a)Invalid syntax for slicing
b)[0,2]
c)(0,1)
d) (0,2)

64 | P a g e
19. Is the following Python code valid?
a=(1,2,3)
b=('A','B','C')
c=tuple(zip(a,b))
a)Yes, c will be ((1, „A‟), (2, „B‟), (3, „C‟))
b)Yes, c will be ((1,2,3),(„A‟,‟B‟,‟C‟))
c)No because tuples are immutable
d) No because the syntax for zip function isn‟t valid

20. Is the following Python code valid?


a,b,c=1,2,3
a,b,c
a)Yes,[1,2,3] is printed
b)No,invalid syntax
c)Yes,(1,2,3) is printed
d) 1 is printed

21. Is the following Python code valid?


a,b=1,2,3
a)Yes, this is an example of tuple unpacking. a=1 and b=2
b) Yes, this is an example of tuple unpacking. a=(1,2) and b=3
c) No, too many values to unpack
d) Yes, this is an example of tuple unpacking. a=1 and b=(2,3)

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


a=(1,2)
b=(3,4)
c=a+b
c
a)(4,6)
b)(1,2,3,4)
c)Error as tuples are immutable
d) None

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


a,b=6,7
a,b=b,a
a,b
a)(6,7)
b)Invalid syntax
c)(7,6)
d) Nothing is printed

24. Is the following Python code valid?


a=2,3,4,5

65 | P a g e
a
a)Yes, 2 is printed
b)Yes, [2,3,4,5] is printed
c)No, too many values to unpack
d) Yes, (2,3,4,5) is printed

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


a=(2,3,1,5)
a.sort()
a
a)(1,2,3,5)
b)(2,3,1,5)
c)None
d) Error, tuple has no attribute sort

26. Is the following Python code valid?


a=(1,2,3)
b=a.update(4,)
a)Yes, a=(1,2,3,4) and b=(1,2,3,4)
b)Yes, a=(1,2,3) and b=(1,2,3,4)
c)No because tuples are immutable
d) No because wrong syntax for update() method

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


a=[(2,4),(1,2),(3,9)]
a.sort()
a
a)[(1, 2), (2, 4), (3, 9)]
b)[(2,4),(1,2),(3,9)]
c)Error because tuples are immutable
d) Error, tuple has no sort attribute

1.b 2.b 3.c 4.c 5.c 6.a 7.a 8.b 9.d(Tuples are immutable and
don‟t have an append method. An exception is thrown in this case.) 10.b 11.d
12.a 13.c 14.d 15.c 16.c 17.b 18.c 19.a 20.c(A tuple
needn‟t be enclosed in parenthesis.) 21.c (For unpacking to happen, the number of
values of the right hand side must be equal to the number of variables on the left hand
side.) 22.b 23.c 24.d 25.d (A tuple is immutable thus it doesn‟t have
a sort attribute.) 26.c (Tuple doesn‟t have any update() attribute because it is
immutable.) 27.a (A list of tuples is a list itself. Hence items of a list can be
sorted.)

66 | P a g e
LIST

The list is a most versatile datatype available in Python which can be written as a list of
comma-separated values (items) between square brackets. Important thing about a list is that items in a
list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square brackets.

For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

 Accessing Values in Lists


To access values in lists, use the square brackets for slicing along with the index or indices to obtain
value available at that index. For example −

ist1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5, 6, 7 ];print "list1[0]: ", list1[0]print "list2[1:5]: ", list2[1:5]

When the above code is executed, it produces the following result −


list1[0]: physics
list2[1:5]: [2, 3, 4, 5]

 Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of the
assignment operator, and you can add to elements in a list with the append() method. For example

list = ['physics', 'chemistry', 1997, 2000];


print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]

OUTPUT
Value available at index 2 :
1997
New value available at index 2 :

67 | P a g e
2001

 Delete List Elements


To remove a list element, you can use either the del statement if you know exactly which element(s)
you are deleting or the remove() method if you do not know. For example −

list1 = ['physics', 'chemistry', 1997, 2000];


print list1
del list1[2]
print "After deleting value at index 2 : "
print list1

When the above code is executed, it produces following result −

['physics', 'chemistry', 1997, 2000]


After deleting value at index 2 :
['physics', 'chemistry', 2000]

 Basic List Operations


Lists respond to the + and * operators much like strings; they mean concatenation and repetition here
too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.
Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration

 Indexing, Slicing, and Matrixes


Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.
Assuming following input −
L = ['spam', 'Spam', 'SPAM!']
Python Expression Results Description

L[2] SPAM! Offsets start at zero

L[-2] Spam Negative: count from the right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

 Built-in List Functions & Methods

68 | P a g e
Python includes the following list functions −
Sr.No. Function with Description

1 cmp(list1, list2)
Compares elements of both lists.

2 len(list)
Gives the total length of the list.

3 max(list)
Returns item from the list with max value.

4 min(list)
Returns item from the list with min value.

5 list(seq)
Converts a tuple into list.

Python includes following list methods


Sr.No. Methods with Description

1 list.append(obj)
Appends object obj to list

2 list.count(obj)
Returns count of how many times obj occurs in list

3 list.extend(seq)
Appends the contents of seq to list

4 list.index(obj)
Returns the lowest index in list that obj appears

5 list.insert(index, obj)
Inserts object obj into list at offset index

6 list.pop(obj=list[-1])
Removes and returns last object or obj from list

7 list.remove(obj)
Removes object obj from list

8 list.reverse()
Reverses objects of list in place

9 list.sort([func])
Sorts objects of list, use compare func if given

69 | P a g e
 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of the following commands will create a list?


a)list1=list()
b)list1=[]
c)list1=list([1,2,3])
d) all of the mentioned

2. What is the output when we execute list(“hello”)?


a) [„h‟, „e‟, „l‟, „l‟, „o‟]
b) [„hello‟]
c) [„llo‟]
d) [„olleh‟]

3. Suppose listExample is [„h‟,‟e‟,‟l‟,‟l‟,‟o‟], what is len(listExample)?


a) 5
b) 4
c) None
d) Error

4. Suppose list1 is [2445,133,12454,123], what is max(list1)?


a) 2445
b) 133
c) 12454
d) 123

5. Suppose list1 is [3, 5, 25, 1, 3], what is min(list1)?


a) 3
b) 5
c) 25
d) 1

6. Suppose list1 is [1, 5, 9], what is sum(list1)?


a) 1
b) 9
c) 15
d) Error

7. To shuffle the list(say list1) what function do we use?


a) list1.shuffle()
b) shuffle(list1)
c) random.shuffle(list1)
d) random.shuffleList(list1)

8. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of the following is correct syntax for slicing
operation?
a) print(list1[0])
b) print(list1[:2])
c) print(list1[:-2])
d) all of the mentioned

9. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1]?


a) Error

70 | P a g e
b) None
c) 25
d) 2

10. Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1]?
a) [2, 33, 222, 14]
b) Error
c) 25
d) [25, 14, 222, 33, 2]

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


>>>names = ['Amir', 'Bear', 'Charlton', 'Daman']
>>>print(names[-1][-1])
A
b) Daman
c) Error
d) n

12. Suppose list1 is [1, 3, 2], What is list1 * 2?


a) [2, 6, 4]
b) [1, 3, 2, 1, 3]
c) [1, 3, 2, 1, 3, 2]
d) [1, 3, 2, 3, 2, 1]

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


>>>list1 = [11, 2, 23]
>>>list2 = [11, 2, 2]
>>>list1 < list2 is
True
b) False
c) Error
d) None

14. To add a new element to a list we use which command?


a) list1.add(5)
b) list1.append(5)
c) list1.addLast(5)
d) list1.addEnd(5)

15. To insert 5 to the third position in list1, we use which command?


a) list1.insert(3, 5)
b) list1.insert(2, 5)
c) list1.add(3, 5)
d) list1.append(3, 5)

16. To remove string “hello” from list1, we use which command?


a) list1.remove(“hello”)
b) list1.remove(hello)
c) list1.removeAll(“hello”)
d) list1.removeOne(“hello”)

17. Suppose list1 is [3, 4, 5, 20, 5], what is list1.index(5)?


a) 0

71 | P a g e
b) 1
c) 4
d) 2

18. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1.count(5)?


a) 0
b) 4
c) 1
d) 2

19. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.reverse()?
a) [3, 4, 5, 20, 5, 25, 1, 3]
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [25, 20, 5, 5, 4, 3, 3, 1]
d) [3, 1, 25, 5, 20, 5, 4, 3]

20. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.extend([34,
5])?
a) [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
b) [1, 3, 3, 4, 5, 5, 20, 25, 34, 5]
c) [25, 20, 5, 5, 4, 3, 3, 1, 34, 5]
d) [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]

21. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.pop(1)?
a) [3, 4, 5, 20, 5, 25, 1, 3]
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [3, 5, 20, 5, 25, 1, 3]
d) [1, 3, 4, 5, 20, 5, 25]
22. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.pop()?
a) [3, 4, 5, 20, 5, 25, 1]
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [3, 5, 20, 5, 25, 1, 3]
d) [1, 3, 4, 5, 20, 5, 25]

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


>>>"Welcome to Python".split()
a) [“Welcome”, “to”, “Python”]
b) (“Welcome”, “to”, “Python”)
c) {“Welcome”, “to”, “Python”}
d) “Welcome”, “to”, “Python”

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


>>>list("a#b#c#d".split('#'))
a) [„a‟, „b‟, „c‟, „d‟]
b) [„a b c d‟]
c) [„a#b#c#d‟]
d) [„abcd‟]

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


myList = [1, 5, 5, 5, 5, 1]
max = myList[0]
indexOfMax = 0
for i in range(1, len(myList)):

72 | P a g e
if myList[i] > max:
max = myList[i]
indexOfMax = i
print(indexOfMax)
a) 1
b) 2
c) 3
d) 4

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


>>>list1 = [1, 3]
>>>list2 = list1
>>>list1[0] = 4
>>>print(list2)
[1, 3]
b) [4, 3]
c) [1, 4]
d) [1, 3, 4]

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


names1 = ['Amir', 'Bala', 'Chales']
if 'amir' in names1:
print(1)
else:
print(2)
a) None
b) 1
c) 2
d) Error

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


numbers = [1, 2, 3, 4]
numbers.append([5,6,7,8])
print(len(numbers))
a) 4
b) 5
c) 8
d) 12

29. which of the following the “in” operator can be used to check if an item is in it?
a) Lists
b) Dictionary
c) Set
d) All of the mentioned

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


list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
print(len(list1 + list2))
a) 2
b) 4
c) 5
d) 8

73 | P a g e
31. What will be the output of the following Python code?
matrix = [[1, 2, 3, 4],
[4, 5, 6, 7],
[8, 9, 10, 11],
[12, 13, 14, 15]]
for i in range(0, 4):
print(matrix[i][1], end = " ")
a) 1 2 3 4
b) 4 5 6 7
c) 1 3 8 12
d) 2 5 9 13

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


data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
print(data[1][0][0])
a) 1
b) 2
c) 4
d) 5

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


points = [[1, 2], [3, 1.5], [0.5, 0.5]]
points.sort()
print(points)
[[1, 2], [3, 1.5], [0.5, 0.5]]
b) [[3, 1.5], [1, 2], [0.5, 0.5]]
c) [[0.5, 0.5], [1, 2], [3, 1.5]]
d) [[0.5, 0.5], [3, 1.5], [1, 2]]

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


a=[[]]*3
a[1].append(7)
print(a)
a) Syntax error
b) [[7], [7], [7]]
c) [[7], [], []]
d) [[],7, [], []]

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


b=[2,3,4,5]
a=list(filter(lambda x:x%2,b))
print(a)
a) [2,4]
b) [ ]
c) [3,5]
d) Invalid arguments for filter function

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


lst=[3,4,6,1,2]
lst[1:2]=[7,8]
print(lst)
a) [3, 7, 8, 6, 1, 2]

74 | P a g e
b) Syntax error
c) [3,[7,8],6,1,2]
d) [3,4,6,7,8]

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


a=[1,2,3]
b=a.append(4)print(a)
print(b)
a)[1,2,3,4]
[1,2,3,4]
b)[1, 2, 3, 4]
None
c)Syntax error
d)[1,2,3]
[1,2,3,4]

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


a=[13,56,17]
a.append([87])
a.extend([45,67])
print(a)
a) [13, 56, 17, [87], 45, 67]
b) [13, 56, 17, 87, 45, 67]
c) [13, 56, 17, 87,[ 45, 67]]
d) [13, 56, 17, [87], [45, 67]]

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


lst=[[1,2],[3,4]]
print(sum(lst,[]))
a) [[3],[7]]
b) [1,2,3,4]
c) Error
d) [10]

ANSWERS :

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

LIST COMPREHENSIVE

List comprehensions are used for creating new lists from other iterables.
As list comprehensions return lists, they consist of brackets containing the expression, which is
executed for each element along with the for loop to iterate over each element.

This is the basic syntax:

new_list = [expression for_loop_one_or_more conditions]

75 | P a g e
Example:

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]

list_using_comp = [var for var in input_list if var % 2 == 0]

print("Output List using list comprehensions:",


list_using_comp)

Output:
Output List using list comprehensions: [2, 4, 4, 6]

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Suppose list1 = [0.5 * x for x in range(0, 4)], list1 is:


a) [0, 1, 2, 3]
b) [0, 1, 2, 3, 4]
c) [0.0, 0.5, 1.0, 1.5]
d) [0.0, 0.5, 1.0, 1.5, 2.0]

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


>>>m = [[x, x + 1, x + 2] for x in range(0, 3)]
a) [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b) [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
c) [1, 2, 3, 4, 5, 6, 7, 8, 9]
d) [0, 1, 2, 1, 2, 3, 2, 3, 4]

3. How many elements are in m?


m = [[x, y] for x in range(0, 4) for y in range(0, 4)]
a) 8
b) 12
c) 16
d) 32

4. What will be the output of the following Python code snippet?


k = [print(i) for i in my_string if i not in "aeiou"]
a) prints all the vowels in my_string
b) prints all the consonants in my_string
c) prints all characters of my_string that aren‟t vowels
d) prints only on executing print(k)

5. What is the output of print(k) in the following Python code snippet?

k = [print(i) for i in my_string if i not in "aeiou"]

76 | P a g e
print(k)
a) all characters of my_string that aren‟t vowels
b) a list of Nones
c) list of Trues
d) list of Falses

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

my_string = "hello world"


k = [(i.upper(), len(i)) for i in my_string]
print(k)
a) [(„HELLO‟, 5), („WORLD‟, 5)]
b) [(„H‟, 1), („E‟, 1), („L‟, 1), („L‟, 1), („O‟, 1), („ „, 1), („W‟, 1), („O‟, 1), („R‟, 1), („L‟, 1),
(„D‟, 1)]
c) [(„HELLO WORLD‟, 11)]
d) none of the mentioned

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

x = [i**+1 for i in range(3)]; print(x);


a) [0, 1, 2]
b) [1, 2, 5]
c) error, **+ is not a valid operator
d) error, „;‟ is not allowed

8. What will be the output of the following Python code snippet?

print([i.lower() for i in "HELLO"])


a) [„h‟, „e‟, „l‟, „l‟, „o‟]
b) „hello‟
c) [„hello‟]
d) hello

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

print([if i%2==0: i; else: i+1; for i in range(4)])


a) [0, 2, 2, 4]
b) [1, 1, 3, 3]
c) error
d) none of the mentioned

77 | P a g e
10. Which of the following is the same as list(map(lambda x: x**-1, [1, 2, 3]))?
a) [x**-1 for x in [(1, 2, 3)]]
b) [1/x for x in [(1, 2, 3)]]
c) [1/x for x in (1, 2, 3)]
d) error

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

l1=[1,2,3]
l2=[4,5,6]
[x*y for x in l1 for y in l2]
a) [4, 8, 12, 5, 10, 15, 6, 12, 18]
b) [4, 10, 18]
c) [4, 5, 6, 8, 10, 12, 12, 15, 18]
d) [18, 12, 6, 15, 10, 5, 12, 8, 4]

12. Write the list comprehension to pick out only negative integers from a
given list „l‟.
a) [x<0 in l]
b) [x for x<0 in l]
c) [x in l for x<0]
d) [x for x in l if x<0]

13. Write a list comprehension for number and its cube for l=[1, 2, 3, 4, 5, 6, 7, 8, 9].
a) [x**3 for x in l]
b) [x^3 for x in l]
c) [x**3 in l]
d) [x^3 in l]

14. Read the information given below carefully and write a list comprehension such
that the output is: [„e‟, „o‟]

w="hello"
v=('a', 'e', 'i', 'o', 'u')
a) [x for w in v if x in v]
b) [x for x in w if x in v]
c) [x for x in v if w in v]
d) [x for v in w for x in w]

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

t=32.00

78 | P a g e
[round((x-32)*5/9) for x in t]
a) [0]
b) 0
c) [0.00]
d) Error

16. Write a list comprehension for producing a list of numbers between 1 and 1000
that are divisible by 3.
a) [x in range(1, 1000) if x%3==0]
b) [x for x in range(1000) if x%3==0]
c) [x%3 for x in range(1, 1000)]
d) [x%3=0 for x in range(1, 1000)]

17. Write a list comprehension to produce the list: [1, 2, 4, 8, 16……212].


a) [(2**x) for x in range(0, 13)]
b) [(x**2) for x in range(1, 13)]
c) [(2**x) for x in range(1, 13)]
d) [(x**2) for x in range(0, 13)]

18. What will be the output of the following Python list comprehension?

[j for i in range(2,8) for j in range(i*2, 50, i)]


a) A list of prime numbers up to 50
b) A list of numbers divisible by 2, up to 50
c) A list of non prime numbers, up to 50
d) Error

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

l=["good", "oh!", "excellent!", "#450"]


[n for n in l if n.isalpha() or n.isdigit()]
a) [„good‟, „oh‟, „excellent‟, „450‟ ]
b) [„good‟]
c) [„good‟, „#450‟]
d) [„oh!‟, „excellent!‟, „#450‟]

20. Write a list comprehension equivalent for the Python code shown below.

for i in range(1, 101):


if int(i*0.5)==i*0.5:
print(i)

79 | P a g e
a) [i for i in range(1, 100) if int(i*0.5)==(i*0.5)]
b) [i for i in range(1, 101) if int(i*0.5)==(i*0.5)]
c) [i for i in range(1, 101) if int(i*0.5)=(i*0.5)]
d) [i for i in range(1, 100) if int(i*0.5)=(i*0.5)]

1.c 2.b 3.c 4.c 5.b 6.b 7.a 8.a 9.c 10.c 11.c 12.d 13.a
14.b 15.d 16.b 17.a 18.c 19.b 20.b

SETS

A set is a collection which is unordered and unindexed. In Python sets are written with
curly brackets.

Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)

 Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has no
index.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set,
by using the in keyword.

Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

 Change Items
Once a set is created, you cannot change its items, but you can add new items.

 Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.

Example
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

80 | P a g e
print(thisset)

Example

Add multiple items to a set, using the update() method:


thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)

 Remove Item

To remove an item in a set, use the remove(), or the discard() method.


Example
Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}


thisset.remove("banana")
print(thisset)

Note: If the item to remove does not exist, remove() will raise an error.

Example
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)

Note: If the item to remove does not exist, discard() will NOT raise an error.

You can also use the pop(), method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so you will not know what item that gets removed.

The return value of the pop() method is the removed item.

Example
Remove the last item by using the pop() method:
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)

 Set Methods

Python has a set of built-in methods that you can use on sets.

Method Description

81 | P a g e
add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or more sets

difference_update() Removes the items in this set that are also included in another, specified set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and another

union() Return a set containing the union of sets

update() Update the set with the union of this set and others

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of these about a set is not true?


a) Mutable data type
b) Allows duplicate values
c) Data type with unordered values
d) Immutable data type

2. Which of the following is not the correct syntax for creating a set?
a) set([[1,2],[3,4]])
b) set([1,2,2,3,4])
c) set((1,2,3,4))
d) {1,2,3,4}

82 | P a g e
3. What will be the output of the following Python code?
nums = set([1,1,2,3,3,3,4,4])
print(len(nums))
a) 7
b) Error, invalid syntax for formation of set
c) 4
d) 8

4. Which of the following statements is used to create an empty set?


a) {}
b) set()
c) []
d) ( )

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


a={5,4}
b={1,2,4,5}
a<b
a) {1,2}
b) True
c) False
d) Invalid operation
a<b returns True if a is a proper subset of b.

6. If a={5,6,7,8}, which of the following statements is false?


a) print(len(a))
b) print(min(a))
c) a.remove(5)
d) a[2]=45
7. If a={5,6,7}, what happens when a.add(5) is executed?
a) a={5,5,6,7}
b) a={5,6,7}
c) Error as there is no add function for set data type
d) Error as 5 already exists in the set

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


a={4,5,6}
b={2,8,6}
a+b
a) {4,5,6,2,8}
b) {4,5,6,2,8,6}
c) Error as unsupported operand type for sets
d) Error as the duplicate item 6 is present in both sets

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


a={4,5,6}
b={2,8,6}
a-b
a) {4,5}
b) {6}
c) Error as unsupported operand type for set data type
d) Error as the duplicate item 6 is present in both sets

83 | P a g e
10. What will be the output of the following Python code?
a={5,6,7,8}
b={7,8,10,11}
a^b
a) {5,6,7,8,10,11}
b) {7,8}
c) Error as unsupported operand type of set data type
d) {5,6,10,11}
^ operator returns a set of elements in set A or set B, but not in both (symmetric difference).

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


s={5,6}
s*3
a) Error as unsupported operand type for set data type
b) {5,6,5,6,5,6}
c) {5,6}
d) Error as multiplication creates duplicate elements which isn‟t allowed
The multiplication operator isn‟t valid for the set data type.

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


a={3,4,5}
b={5,6,7}
a|b
a) Invalidoperation
b) {3,4,5,6,7}
c) {5}
d) {3,4,6,7}

13. Is the following Python code valid?


a={3,4,{7,5}}
print(a[2][0])
a) Yes, 7 is printed
b) Error, elements of a set can‟t be printed
c) Error, subsets aren‟t allowed
d) Yes, {7,5} is printed

14. Which of these about a frozenset is not true?


a)Mutable data type
b)Allows duplicate values
c)Data type with unordered values
d) Immutable data type

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


a={3,4,5}
a.update([1,2,3])
a
a) Error, no method called update for set data type
b) {1, 2, 3, 4, 5}
c) Error, list can‟t be added to set
d) Error, duplicate item present in list

84 | P a g e
16. What will be the output of the following Python code?
>>> a={1,2,3}
>>> a.intersection_update({2,3,4,5})
>>> a
a) {2,3}
b) Error, duplicate item present in list
c) Error, no method called intersection_update for set data type
d) {1,4,5}

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


>>> a={1,2,3}
>>> b=a
>>> b.remove(3)
>>> a
a) {1,2,3}
b) Error, copying of sets isn‟t allowed
c) {1,2}
d) Error, invalid syntax for remove

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


>>> a={1,2,3}
>>> b=a.add(4)
>>> b
a) 0
b) {1,2,3,4}
c) {1,2,3}
d) Nothing is printed

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


>>> a={5,6,7}
>>> sum(a,5)
a) 5
b) 23
c) 18
d) Invalid syntax for sum method, too many arguments

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


>>> a={1,2,3}
>>> {x*2 for x in a|{4,5}}
a) {2,4,6}
b) Error, set comprehensions aren‟t allowed
c) {8,2,10,4,6}
d) {8,10}
Set comprehensions are allowed

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


>>> a={5,6,7,8}
>>> b={7,8,9,10}
>>> len(a+b)
a) 8
b) Error, unsupported operand „+‟ for sets
c) 6
d) Nothing is displayed

85 | P a g e
22. What will be the output of the following Python code?
a={1,2,3}
b={1,2,3}
c=a.issubset(b)
print(c)
a) True
b) Error, no method called issubset() exists
c) Syntax error for issubset() method
d) False

23. Is the following Python code valid?


a={1,2,3}
b={1,2,3,4}
c=a.issuperset(b)
print(c)
a) False
b) True
c) Syntax error for issuperset() method
d) Error, no method called issuperset()

24.Set makes use of __________


Dictionary makes use of ____________
a) keys, keys
b) key values, keys
c) keys, key values
d) key values, key values

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


s={2, 5, 6, 6, 7}
s
a) {2,5,7}
b) {2,5,6,7}
c) {2,5,6,6,7}
d) Error

26. Which of the following functions cannot be used on heterogeneous sets?


a) pop
b) remove
c) update
d) sum

27. Which of the following functions will return the symmetric difference between two sets, x
and y?
a) x|y
b) x^y
c) x&y
d) x – y

28. What will be the output of the following Python code snippet?
z=set('abc$de')
'a' in z
a) True

86 | P a g e
b) False
c) Nooutput
d) Error

29. What will be the output of the following Python code snippet?
s=set([1, 2, 3])
s.union([4, 5])
s|([4, 5])
a) {1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
b) Error
{1, 2, 3, 4, 5}
c) {1, 2, 3, 4, 5}
Error
d) Error
Error
30. What will be the output of the following Python code snippet?
for x in set('pqr'):
print(x*2)
a) pp
qq
rr
b) pqr
pqr
c) ppqqrr
d) pqrpqr

31. What will be the output of the following Python code snippet?
{a**2 for a in range(4)}
a) {1,4,9,16}
b) {0,1,4,9,16}
c) Error
d) {0, 1, 4, 9}

32. The ____________ function removes the first element of a set and the last element of a list.
a) remove
b) pop
c) discard
d) dispose

33. The difference between the functions discard and remove is that:
a) Discard removes the last element of the set whereas remove removes the first element of the set
b) Discard throws an error if the specified element is not present in the set whereas remove does
not throw an error in case of absence of the specified element
c) Remove removes the last element of the set whereas discard removes the first element of the
set
d) Remove throws an error if the specified element is not present in the set whereas discard does
not throw an error in case of absence of the specified element

34. If we have two sets, s1 and s2, and we want to check if all the elements of s1 are present in s2
or not, we can use the function:
a) s2.issubset(s1)
b) s2.issuperset(s1)

87 | P a g e
c) s1.issuperset(s2)
d) s1.isset(s2)

35. What will be the output of the following Python code, if s1= {1, 2, 3}?
s1.issubset(s1)
a) True
b) Error
c) Nooutput
d) False

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

DICTIONARY

A dictionary is a collection which is unordered, changeable and indexed. In Python


dictionaries are written with curly brackets, and they have keys and values.

Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

 Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:

Example
Get the value of the "model" key:
x = thisdict["model"]

There is also a method called get() that will give you the same result :

Example
Get the value of the "model" key:
x = thisdict.get("model")

88 | P a g e
 Change Values

You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword:

Example

Check if "model" is present in the dictionary:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

 Adding Items

Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

 Removing Items

There are several methods to remove items from a dictionary:

Example
The pop() method removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

89 | P a g e
thisdict.pop("model")
print(thisdict)

Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is
removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)

Example

The del keyword can also delete the dictionary completely:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.

 Dictionary Methods

Python has a set of built-in methods that you can use on dictionaries

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

update() Updates the dictionary with the specified key-value pairs

90 | P a g e
values() Returns a list of all the values in the dictionary

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of the following statements create a dictionary?


a) d={}
b) d={“john”:40,“peter”:45}
c) d={40:”john”,45:”peter”}
d) All of the mentioned

2. What will be the output of the following Python code snippet?


d = {"john":40, "peter":45}
a) “john”,40,45,and“peter”
b) “john”and“peter”
c) 40and45
d) d = (40:”john”, 45:”peter”)

3. What will be the output of the following Python code snippet?


d = {"john":40, "peter":45}
"john" in d
a) True
b) False
c) None
d) Error

4. What will be the output of the following Python code snippet?


d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 == d2
a) True
b) False
c) None
d) Error

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


d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 > d2
a) True
b) False
c) Error
d) None

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


d = {"john":40, "peter":45}
d["john"]
a) 40
b) 45
c) “john”

91 | P a g e
d) “peter”

7. Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command do we
use?
a) d.delete(“john”:40)
b) d.delete(“john”)
c) del d[“john”]
d) del d(“john”:40)

8. Suppose d = {“john”:40, “peter”:45}. To obtain the number of entries in dictionary which


command do we use?
a) d.size()
b) len(d)
c) size(d)
d) d.len()

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


d = {"john":40, "peter":45}
print(list(d.keys()))
a) [“john”,“peter”]
b) [“john”:40,“peter”:45]
c) (“john”,“peter”)
d) (“john”:40, “peter”:45)

10. Suppose d = {“john”:40, “peter”:45}, what happens when we try to retrieve a value using
the expression d[“susan”]?
a) Since “susan” is not a value in the set, Python raises a KeyError exception
b) It is executed fine and no exception is raised, and it returns None
c) Since “susan” is not a key in the set, Python raises a KeyError exception
d) Since “susan” is not a key in the set, Python raises a syntax error

11. Which of these about a dictionary is false?


a) The values of a dictionary can be accessed using keys
b) The keys of a dictionary can be accessed using values
c) Dictionaries aren‟t ordered
d) Dictionaries are mutable

12. Which of the following is not a declaration of the dictionary?


a) {1:„A‟,2:„B‟}
b) dict([[1,”A”],[2,”B”]])
c) {1,”A”,2”B”}
d) { }

13. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
for i,j in a.items():
print(i,j,end=" ")
a) 1A2B3C
b) 123

92 | P a g e
c) ABC
d) 1:”A” 2:”B” 3:”C”

14. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
print(a.get(1,4))
a) 1
b) A
c) 4
d) Invalid syntax for get method

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


a={1:"A",2:"B",3:"C"}
b={4:"D",5:"E"}
a.update(b)
print(a)
a) {1:„A‟,2:„B‟,3:„C‟}
b) Method update() doesn‟t exist for dictionaries
c) {1:„A‟,2:„B‟,3:„C‟,4:„D‟,5:„E‟}
d) {4: „D‟, 5: „E‟}

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


a={1:"A",2:"B",3:"C"}
b=a.copy()
b[2]="D"
print(a)
a) Error, copy() method doesn‟t exist for dictionaries
b) {1:„A‟,2:„B‟,3:„C‟}
c) {1:„A‟,2:„D‟,3:„C‟}
d) “None” is printed

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


a={1:"A",2:"B",3:"C"}
a.clear()
print(a)
a) None
b) {None:None,None:None,None:None}
c) {1:None,2:None,3:None}
d) { }

18. Which of the following isn‟t true about dictionary keys?


a) More than one key isn‟t allowed
b) Keys must be immutable
c) Keys must be integers
d) When duplicate keys encountered, the last assignment wins

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


a={1:5,2:3,3:4}
a.pop(3)
print(a)
a) {1:5}
b) {1:5,2:3}

93 | P a g e
c) Error, syntax error for pop() method
d) {1: 5, 3: 4}

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


a={1:5,2:3,3:4}
print(a.pop(4,9))
a) 9
b) 3
c) Too many arguments for pop() method
d) 4

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


a={1:"A",2:"B",3:"C"}
for i in a:
print(i,end=" ")
a) 123
b) „A‟„B‟„C‟
c) 1„A‟2„B‟3„C‟
d) Error, it should be: for i in a.items():

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


>>> a={1:"A",2:"B",3:"C"}
>>> a.items()
a) Syntax error
b) dict_items([(„A‟),(„B‟),(„C‟)])
c) dict_items([(1,2,3)])
d) dict_items([(1, „A‟), (2, „B‟), (3, „C‟)])

23. Which of the statements about dictionary values if false?


a) More than one key can have the same value
b) The values of the dictionary can be accessed as dict[key]
c) Values of a dictionary must be unique
d) Values of a dictionary can be a mixture of letters and numbers

24. What will be the output of the following Python code snippet?
>>> a={1:"A",2:"B",3:"C"}
>>> del a
a) method del doesn‟t exist for the dictionary
b) del deletes the values in the dictionary
c) del deletes the entire dictionary
d) del deletes the keys in the dictionary

25. If a is a dictionary with some key-value pairs, what does a.popitem() do?
a) Removes an arbitrary element
b) Removes all the key-value pairs
c) Removes the key-value pair for the key given as an argument
d) Invalid method for dictionary

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


>>> a={'B':5,'A':9,'C':7}

94 | P a g e
>>> sorted(a)
a) [„A‟,‟B‟,‟C‟]
b) [„B‟,‟C‟,‟A‟]
c) [5,7,9]
d) [9,5,7]
27. What will be the output of the following Python code?
>>> a={i: i*i for i in range(6)}
>>> a
a) Dictionary comprehension doesn‟t exist
b) {0:0,1:1,2:4,3:9,4:16,5:25,6:36}
c) {0:0,1:1,4:4,9:9,16:16,25:25}
d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

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


>>> a={}
>>> a.fromkeys([1,2,3],"check")
a) Syntax error
b) {1:”check”,2:”check”,3:”check”}
c) “check”
d) {1:None,2:None,3:None}

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


>>> b={}
>>> all(b)
a) {}
b) False
c) True
d) An exception is thrown

30. If b is a dictionary, what does any(b) do?


a) Returns True if any key of the dictionary is true
b) Returns False if dictionary is empty
c) Returns True if all keys of the dictionary are true
d) Method any() doesn‟t exist for dictionary

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


>>> a={"a":1,"b":2,"c":3}
>>> b=dict(zip(a.values(),a.keys()))
>>> b
a) {„a‟:1,„b‟:2,„c‟:3}
b) An exception is thrown
c) {„a‟:„b‟:„c‟:}
d) {1: „a‟, 2: „b‟, 3: „c‟}

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


>>> a=dict()
>>> a[1]
a) An exception is thrown since the dictionary is empty
b) „„
c) 1
d) 0

95 | P a g e
ANSWERS :

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

# PYTHON LAMBDA
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:

Example
A lambda function that adds 10 to the number passed in as an argument, and print the result:
x = lambda a : a + 10
print(x(5))

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Lambda is a function in python?


A. True
B. False
C. Lambda is a function in python but user can not use it.
D. None of the above

2. What is the output of the following program?


z = lambda x : x * x
print(z(6))
A. 6
B. 36
C. 0
D. Error

1.a2.b3.4.5.

UNIT 4

96 | P a g e
FILE HANDLING

File handling is an important part of any web application.


Python has several functions for creating, reading, updating, and deleting files.

 File Handling

The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:


"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)

Syntax

To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
The code above is the same as:
f = open("demofile.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.

 Open a File

To open the file, use the built-in open() function.


The open() function returns a file object, which has a read() method for reading the content of the file:

Example
f = open("demofile.txt", "r")
print(f.read())

 Close Files

It is a good practice to always close the file when you are done with it.

Example
Close the file when you are finish with it:

f = open("demofile.txt", "r")
print(f.readline())
f.close()

97 | P a g e
 Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content

Example
Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

 Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist

Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")

 Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. To open a file c:\scores.txt for reading, we use _____________


a) infile = open(“c:\scores.txt”, “r”)
b) infile = open(“c:\\scores.txt”, “r”)
c) infile = open(file = “c:\scores.txt”, “r”)
d) infile = open(file = “c:\\scores.txt”, “r”)

2. To open a file c:\scores.txt for writing, we use ____________


a) outfile = open(“c:\scores.txt”, “w”)
b) outfile = open(“c:\\scores.txt”, “w”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\\scores.txt”, “w”)

98 | P a g e
3. To open a file c:\scores.txt for appending data, we use ____________
a) outfile = open(“c:\\scores.txt”, “a”)
b) outfile = open(“c:\\scores.txt”, “rw”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\\scores.txt”, “w”)

4. Which of the following statements are true?


a) When you open a file for reading, if the file does not exist, an error occurs
b) When you open a file for writing, if the file does not exist, a new file is created
c) When you open a file for writing, if the file exists, the existing file is overwritten with the new file
d) All of the mentioned

5. To read two characters from a file object infile, we use ____________


a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

6. To read the entire remaining contents of the file as a string from a file object infile, we use
____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

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

f = None
for i in range (5):
with open("data.txt", "w") as f:
if i > 2:
break

print(f.closed)

a) True
b) False
c) None
d) Error

8. To read the next line of the file from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

9. To read the remaining lines of the file from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

99 | P a g e
10. The readlines() method returns ____________
a) str
b) a list of lines
c) a list of single characters
d) a list of integers

11. Which are the two built-in functions to read a line of text from standard input, which by default
comes from the keyboard?
a) Raw_input & Input
b) Input & Scan
c) Scan & Scanner
d) Scanner

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

str = raw_input("Enter your input: ");

print "Received input is : ", str

a) Enter your input: Hello Python


Received input is : Hello Python
b) Enter your input: Hello Python
Received input is : Hello
c) Enter your input: Hello Python
Received input is : Python
d) None of the mentioned

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

str = input("Enter your input: ");

print "Received input is : ", str

a) Enter your input: [x*5 for x in range(2,10,2)]


Received input is : [x*5 for x in range(2,10,2)]
b) Enter your input: [x*5 for x in range(2,10,2)]
Received input is : [10, 30, 20, 40]
c) Enter your input: [x*5 for x in range(2,10,2)]
Received input is : [10, 10, 30, 40]
d) None of the mentioned

14. Which one of the following is not attributes of file?

a) closed
b) softspace
c) rename
d) mode

15. What is the use of tell() method in python?


a) tells you the current position within the file
b) tells you the end position within the file
c) tells you the file is opened or not
d) none of the mentioned

100 | P a g e
16. What is the current syntax of rename() a file?

a) rename(current_file_name, new_file_name)
b) rename(new_file_name, current_file_name,)
c) rename(()(current_file_name, new_file_name))
d) none of the mentioned

17. What is the current syntax of remove() a file?


a) remove(file_name)
b) remove(new_file_name, current_file_name,)
c) remove(() , file_name))
d) none of the mentioned

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

fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines

# This is 1st line

# This is 2nd line

# This is 3rd line

# This is 4th line

# This is 5th line

for index in range(5):


line = fo.next()
print "Line No %d - %s" % (index, line)

# Close opened file


fo.close()

a) Compilation Error
b) Syntax Error
c) Displays Output
d) None of the mentioned

19. What is the use of seek() method in files?


a) sets the file‟s current position at the offset
b) sets the file‟s previous position at the offset
c) sets the file‟s current position within the file
d) none of the mentioned

20. What is the use of truncate() method in file?


a) truncates the file size
b) deletes the content of the file
c) deletes the file size
d) none of the mentioned.

101 | P a g e
21. Which is/are the basic I/O connections in file?
a) Standard Input
b) Standard Output
c) Standard Errors
d) All of the mentioned

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

import sys
sys.stdout.write(' Hello\n')
sys.stdout.write('Python\n')

a) Compilation Error
b) Runtime Error
c) Hello Python
d) Hello
Python

23. Which of the following mode will refer to binary data?


a) r
b) w
c) +
d) b

24. What is the pickling?


a) It is used for object serialization
b) It is used for object deserialization
c) None of the mentioned
d) All of the mentioned

25. What is unpickling?


a) It is used for object serialization
b) It is used for object deserialization
c) None of the mentioned
d) All of the mentioned

26. What is the correct syntax of open() function?


a) file = open(file_name [, access_mode][, buffering])
b) file object = open(file_name [, access_mode][, buffering])
c) file object = open(file_name)
d) none of the mentioned.

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

fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
fo.flush()
fo.close()

a) Compilation Error
b) Runtime Error
c) No Output

102 | P a g e
d) Flushes the file when closing them

28. Correct syntax of file.writelines() is?


a) file.writelines(sequence)
b) fileObject.writelines()
c) fileObject.writelines(sequence)
d) none of the mentioned

29. Correct syntax of file.readlines() is?


a) fileObject.readlines( sizehint );
b) fileObject.readlines();
c) fileObject.readlines(sequence)
d) none of the mentioned.

30. In file handling, what does this terms means “r, a”?
a) read, append
b) append, read
c) write, append
d) none of the mentioned

31. What is the use of “w” in file handling?


a) Read
b) Write
c) Append
d) None of the mentioned

32. What is the use of “a” in file handling?


a) Read
b) Write
c) Append
d) None of the mentioned

33. Which function is used to read all the characters?


a) Read()
b) Readcharacters()
c) Readall()
d) Readchar()

34. Which function is used to read single line from file?


a) Readline()
b) Readlines()
c) Readstatement()
d) Readfullline()

35. Which function is used to write all the characters?


a) write()
b) writecharacters()
c) writeall()
d) writechar()

36. Which function is used to write a list of string in a file?


a) writeline()
b) writelines()

103 | P a g e
c) writestatement()
d) writefullline()

37. Which function is used to close a file in python?


a) Close()
b) Stop()
c) End()
d) Closefile()

38. Is it possible to create a text file in python?


a) Yes
b) No
c) Machine dependent
d) All of the mentioned

39. Which of the following are the modes of both writing and reading in binary format in file?
a) wb+
b) w
c) wb
d) w+

40. Which of the following is not a valid mode to open a file?


a) ab
b) rw
c) r+
d) w+

41. What is the difference between r+ and w+ modes?


a) no difference
b) in r+ the pointer is initially placed at the beginning of the file and the pointer is at the end for w+
c) in w+ the pointer is initially placed at the beginning of the file and the pointer is at the end for r+
d) depends on the operating system

42. How do you get the name of a file from a file object (fp)?
a) fp.name
b) fp.file(name)
c) self.__name__(fp)
d) fp.__name__()

43. Which of the following is not a valid attribute of a file object (fp)?
a) fp.name
b) fp.closed
c) fp.mode
d) fp.size

44. How do you close a file object (fp)?


a) close(fp)
b) fclose(fp)
c) fp.close()
d) fp.__close__()

45. How do you get the current position within the file?
a) fp.seek()

104 | P a g e
b) fp.tell()
c) fp.loc
d) fp.pos

46. How do you rename a file?


a) fp.name = „new_name.txt‟
b) os.rename(existing_name, new_name)
c) os.rename(fp, new_name)
d) os.set_name(existing_name, new_name)

47. How do you delete a file?


a) del(fp)
b) fp.delete()
c) os.remove(„file‟)
d) os.delete(„file‟)

48. How do you change the file position to an offset value from the start?
a) fp.seek(offset, 0)
b) fp.seek(offset, 1)
c) fp.seek(offset, 2)
d) none of the mentioned

49. What happens if no arguments are passed to the seek function?


a) file position is set to the start of file
b) file position is set to the end of file
c) file position remains unchanged
d) error

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

EXCEPTION AND ASSERTION

The try block lets you test a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the try- and except
blocks.

Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.

These exceptions can be handled using the try statement:

105 | P a g e
Example
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. How many except statements can a 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:
# Do somethingexcept:
# Do somethingfinally:
# Do something
a) no, there is no such thing as finally
b) no, finally cannot be used with except
c) no, finally must come before except
d) yes

4. Is the following Python code valid?


try:
# Do somethingexcept:
# Do somethingelse:
# Do something
a) no, there is no such thing as else
b) no, else cannot be used with except
c) no, else must come before except
d) yes

5. Can one block of except statements handle multiple exception?


a) yes, like except TypeError, SyntaxError [,…]
b) yes, like except [TypeError, SyntaxError]
c) no
d) none of the mentioned

106 | P a g e
6. 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

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


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

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


def foo():
try:
print(1)
finally:
print(2)
foo()
a) 1 2
b) 1
c) 2
d) none of the mentioned

9. What happens when „1‟ == 1 is executed?


a) we get a True
b) we get a False
c) an TypeError occurs
d) a ValueError occurs

10. The following Python code will result in an error if the input value is entered as -5.
assert False, 'Spanish'
a) True
b) False

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


x=10
y=8assert x>y, 'X too small'
a) Assertion Error
b) 10 8
c) No output
d) 108

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


#generatordef f(x):
yield x+1
g=f(8)print(next(g))

107 | P a g e
a) 8
b) 9
c) 7
d) Error

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


def a():
try:
f(x, 4)
finally:
print('after f')
print('after f?')
a()
a) No output
b) after f?
c) error
d) after f

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


def f(x):
for i in range(5):
yield i
g=f(8)print(list(g))
a) [0, 1, 2, 3, 4]
b) [1, 2, 3, 4, 5, 6, 7, 8]
c) [1, 2, 3, 4, 5]
d) [0, 1, 2, 3, 4, 5, 6, 7]
Explanation: The output of the code shown above is a list containing whole numbers in the range (5).
Hence the output of this code is: [0, 1, 2, 3, 4].

15. The error displayed in the following Python code is?


import itertools
l1=(1, 2, 3)
l2=[4, 5, 6]
l=itertools.chain(l1, l2)print(next(l1))
a) „list‟ object is not iterator
b) „tuple‟ object is not iterator
c) „list‟ object is iterator
d) „tuple‟ object is iterator

16. Which of the following is not an exception handling keyword in Python?


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

17. What happens if the file is not found in the following Python code?
a=Falsewhile not a:
try:
f_n = input("Enter file name")
i_f = open(f_n, 'r')
except:
print("Input file not found")

108 | P a g e
a) No error
b) Assertion error
c) Input output error
d) Name error

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


lst = [1, 2, 3]
lst[3]
a) NameError
b) ValueError
c) IndexError
d) TypeError
19. What will be the output of the following Python code?
t[5]
a) IndexError
b) NameError
c) TypeError
d) ValeError

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

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


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

22. What will be the output of the following Python code if the input entered is 6?
valid = Falsewhile not valid:
try:
n=int(input("Enter a number"))
while n%2==0:
print("Bye")
valid = True
except ValueError:
print("Invalid")
a) Bye (printed once)
b) No output
c) Invalid (printed once)
d) Bye (printed infinite number of times)

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

109 | P a g e
d) Syntax, Semantic

24. Which of the following statements is true?


a) The standard exceptions are automatically imported into Python programs
b) All raised standard exceptions must be handled in Python
c) When there is a deviation from the rules of a programming language, a semantic error is thrown
d) If any exception is thrown in try block, else block is executed

25. Which of the following is not a standard exception in Python?


a) NameError
b) IOError
c) AssignmentError
d) ValueError

26. Syntax errors are also known as parsing errors.


a) True
b) False

27. An exception is ____________


a) an object
b) a special function
c) a standard module
d) a module

28. _______________________ exceptions are raised as a result of an error in opening a


particular file.
a) ValueError
b) TypeError
c) ImportError
d) IOError

29. Which of the following blocks will be executed whether an exception is thrown or not?
a) except
b) else
c) finally
d) assert

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

MODULES

Consider a module to be the same as a code library.


A file containing a set of functions you want to include in your application.

 Create a Module

110 | P a g e
To create a module just save the code you want in a file with the file extension .py:

Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)

Use a Module
Now we can use the module we just created, by using the import statement:

Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")

Note: When using a function from a module, use the syntax: module_name.function_name.

Variables in Module
The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):

Example
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example

Import the module named mymodule, and access the person1 dictionary:

import mymodule
a = mymodule.person1["age"]
print(a)

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of these definitions correctly describes a module?


a) Denoted by triple quotes for providing the specification of certain program elements
b) Design and implementation of specific functionality to be incorporated into a program
c) Defines the specification of how it is to be used
d) Any program that reuses code

2. Which of the following is not an advantage of using modules?


a) Provides a means of reuse of program code
b) Provides a means of dividing up tasks
c) Provides a means of reducing the size of the program
d) Provides a means of testing individual parts of the program

111 | P a g e
3. Program code making use of a given module is called a ______ of the module.
a) Client
b) Docstring
c) Interface
d) Modularity

4. ______ is a string literal denoted by triple quotes for providing the specifications of certain
program elements.
a) Interface
b) Modularity
c) Client
d) Docstring

5. Which of the following is true about top-down design process?


a) The details of a program design are addressed before the overall design
b) Only the details of the program are addressed
c) The overall design of the program is addressed before the details
d) Only the design of the program is addressed

6. In top-down design every module is broken into same number of submodules.


a) True
b) False

7. All modular designs are because of a top-down design process.


a) True
b) False

8. Which of the following isn‟t true about main modules?


a) When a python file is directly executed, it is considered main module of a program
b) Main modules may import any number of modules
c) Special name given to main modules is: __main__
d) Other main modules can import main modules
.
9. Which of the following is not a valid namespace?
a) Global namespace
b) Public namespace
c) Built-in namespace
d) Local namespace

10. Which of the following is false about “import modulename” form of import?
a) The namespace of imported module becomes part of importing module
b) This form of import prevents name clash
c) The namespace of imported module becomes available to importing module
d) The identifiers in module are accessed as: modulename.identifier

11. Which of the following is false about “from-import” form of import?


a) The syntax is: from modulename import identifier
b) This form of import prevents name clash
c) The namespace of imported module becomes part of importing module
d) The identifiers in module are accessed directly as: identifier

12. Which of the statements about modules is false?


a) In the “from-import” form of import, identifiers beginning with two underscores are private and

112 | P a g e
aren‟t imported
b) dir() built-in function monitors the items in the namespace of the main module
c) In the “from-import” form of import, all identifiers regardless of whether they are private or public
are imported
d) When a module is loaded, a compiled version of the module with file extension .pyc is
automatically produced

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


from math import factorialprint(math.factorial(5))
a) 120
b) Nothing is printed
c) Error, method factorial doesn‟t exist in math module
d) Error, the statement should be: print(factorial(5))

14. What is the order of namespaces in which Python looks for an identifier?
a) Python first searches the global namespace, then the local namespace and finally the built-in
namespace
b) Python first searches the local namespace, then the global namespace and finally the built-in
namespace
c) Python first searches the built-in namespace, then the global namespace and finally the local
namespace
d) Python first searches the built-in namespace, then the local namespace and finally the global
namespace

1.b 2.c 3.a 4.d 5.c 6.b 7.b 8.d 9.b 10.a 11.b 12.c
13.d 14.b

CLASSES

Python is an object oriented programming language.


Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.

 Create a Class
To create a class, use the keyword class:

Example
Create a class named MyClass, with a property named x:
class MyClass:
x=5

113 | P a g e
 Create Object
Now we can use the class named MyClass to create objects:

Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)

 The __init__() Function


The examples above are classes and objects in their simplest form, and are not really useful in real life
applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being
initiated.
Use the __init__() function to assign values to object properties, or other operations that are necessary
to do when the object is being created:

Example
Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

 Object Methods

Objects can also contain methods. Methods in objects are functions that belong to the object.
Let us create a method in the Person class:

Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

 MULTIPLE CHOICE QUESTIONS ANSWERS

114 | P a g e
1. _____ represents an entity in the real world with its identity and behaviour.
a) A method
b) An object
c) A class
d) An operator

2. _____ is used to create an object.


a) class
b) constructor
c) User-defined functions
d) In-built functions

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


class test:
def __init__(self,a="Hello World"):
self.a=a

def display(self):
print(self.a)
obj=test()
obj.display()
a) The program has an error because constructor can‟t have default arguments
b) Nothing is displayed
c) “Hello World” is displayed
d) The program has an error display function doesn‟t have parameters

4. What is setattr() used for?


a) To access the attribute of the object
b) To set an attribute
c) To check if an attribute exists or not
d) To delete an attribute

5. What is getattr() used for?


a) To access the attribute of the object
b) To delete an attribute
c) To check if an attribute exists or not
d) To set an attribute

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


class change:
def __init__(self, x, y, z):
self.a = x + y + z

x = change(1,2,3)
y = getattr(x, 'a')setattr(x, 'a', y+1)print(x.a)
a) 6
b) 7
c) Error
d) 0

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

115 | P a g e
class test:
def __init__(self,a):
self.a=a

def display(self):
print(self.a)
obj=test()
obj.display()
a) Runs normally, doesn‟t display anything
b) Displays 0, which is the automatic default value
c) Error as one argument is required while creating the object
d) Error as display function requires additional argument

8. Is the following Python code correct?


>>> class A:
def __init__(self,b):
self.b=b
def display(self):
print(self.b)>>> obj=A("Hello")>>> del obj
a) True
b) False

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


class test:
def __init__(self):
self.variable = 'Old'
self.Change(self.variable)
def Change(self, var):
var = 'New'
obj=test()print(obj.variable)
a) Error because function change can‟t be called in the __init__ function
b) „New‟ is printed
c) „Old‟ is printed
d) Nothing is printed

10. What is Instantiation in terms of OOP terminology?


a) Deleting an instance of class
b) Modifying an instance of class
c) Copying an instance of class
d) Creating an instance of class

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


class fruits:
def __init__(self, price):
self.price = price
obj=fruits(50)

obj.quantity=10
obj.bags=2
print(obj.quantity+len(obj.__dict__))
a) 12
b) 52
c) 13

116 | P a g e
d) 60

12. The assignment of more than one function to a particular operator is _______
a) Operator over-assignment
b) Operator overriding
c) Operator overloading
d) Operator instance

13. Which of the following is not a class method?


a) Non-static
b) Static
c) Bounded
d) Unbounded

14. Which of the following Python code creates an empty class?


a)
class A:
return
b)
class A:
pass
c)
class A:
d) It is not possible to create an empty class

15. What are the methods which begin and end with two underscore characters called?
a) Special methods
b) In-built methods
c) User-defined methods
d) Additional methods

16. Special methods need to be explicitly called during object creation.


a) True
b) False

17. Is the following Python code valid?


class B(object):
def first(self):
print("First method called")
def second():
print("Second method called")
ob = B()
B.first(ob)
a) It isn‟t as the object declaration isn‟t right
b) It isn‟t as there isn‟t any __init__ method for initializing class members
c) Yes, this method of calling is called unbounded method call
d) Yes, this method of calling is called bounded method call

18. What is hasattr(obj,name) used for?


a) To access the attribute of the object
b) To delete an attribute
c) To check if an attribute exists or not
d) To set an attribute

117 | P a g e
19. What is delattr(obj,name) used for?
a) To print deleted attribute
b) To delete an attribute
c) To check if an attribute is deleted or not
d) To set an attribute

20. __del__ method is used to destroy instances of a class.


a) True
b) False

21. What does print(Test.__name__) display (assuming Test is the name of the class)?
a) ()
b) Exception is thrown
c) Test
d) __main__

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


class stud:
def __init__(self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print("Roll no : ", self.roll_no, ", Grade: ", self.grade)
stud1 = stud(34, „S‟)
stud1.age=7print(hasattr(stud1, 'age'))
a) Error as age isn‟t defined
b) True
c) False
d) 7

ANSWERS :

1.b 2.b 3.c 4.b 5.a 6.b 7.c 8.a 9.c 10.d 11.c 12.c
13.a 14.b 15.a 16.b 17.c 18.c 19.b 20.a 21.c 22.a

INHERITANCE

Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.

 Create a Parent Class


Any class can be a parent class, so the syntax is the same as creating any other class:

Example
Create a class named Person, with firstname and lastname properties, and a printname method:
class Person:

118 | P a g e
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person("John", "Doe")
x.printname()

 Create a Child Class


To create a class that inherits the functionality from another class, send the parent class as a parameter
when creating the child class:

Example
Create a class named Student, which will inherit the properties and methods from the Person class:
class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties or methods to the class.

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of the following best describes inheritance?


a) Ability of a class to derive members of another class as a part of its own definition
b) Means of bundling instance variables and methods in order to restrict access to certain class
members
c) Focuses on variables and passing of variables to functions
d) Allows for implementation of elegant software that is well designed and easily modified

2. Which of the following statements is wrong about inheritance?


a) Protected members of a class can be inherited
b) The inheriting class is called a subclass
c) Private members of a class can be inherited and accessed
d) Inheritance is one of the features of OOP

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


class Demo:
def __new__(self):
self.__init__(self)
print("Demo's __new__() invoked")
def __init__(self):
print("Demo's __init__() invoked")class Derived_Demo(Demo):
def __new__(self):
print("Derived_Demo's __new__() invoked")
def __init__(self):
print("Derived_Demo's __init__() invoked")def main():

119 | P a g e
obj1 = Derived_Demo()
obj2 = Demo()
main()
a) Derived_Demo‟s __init__() invoked
Derived_Demo's __new__() invoked
Demo's __init__() invoked
Demo's __new__() invoked
b) Derived_Demo's __new__() invoked
Demo's __init__() invoked
Demo's __new__() invoked
c) Derived_Demo's __new__() invoked
Demo's __new__() invoked
d) Derived_Demo‟s __init__() invoked
Demo's __init__() invoked

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


class Test:
def __init__(self):
self.x = 0class Derived_Test(Test):
def __init__(self):
self.y = 1def main():
b = Derived_Test()
print(b.x,b.y)
main()
a) 0 1
b) 0 0
c) Error because class B inherits A but variable x isn‟t inherited
d) Error because when object is created, argument must be passed like Derived_Test(1)

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


class A():
def disp(self):
print("A disp()")class B(A):
pass
obj = B()
obj.disp()
a) Invalid syntax for inheritance
b) Error because when object is created, argument must be passed
c) Nothing is printed
d) A disp()

6. All subclasses are a subtype in object-oriented programming.


a) True
b) False

7. When defining a subclass in Python that is meant to serve as a subtype, the subtype Python
keyword is used.
a) True
b) False

8. Suppose B is a subclass of A, to invoke the __init__ method in A from B, what is the line of
code you should write?

120 | P a g e
a) A.__init__(self)
b) B.__init__(self)
c) A.__init__(B)
d) B.__init__(A)

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


class Test:
def __init__(self):
self.x = 0class Derived_Test(Test):
def __init__(self):
Test.__init__(self)
self.y = 1def main():
b = Derived_Test()
print(b.x,b.y)
main()
a) Error because class B inherits A but variable x isn‟t inherited
b) 0 0
c) 0 1
d) Error, the syntax of the invoking method is wrong

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


class A:
def __init__(self, x= 1):
self.x = xclass der(A):
def __init__(self,y = 2):
super().__init__()
self.y = ydef main():
obj = der()
print(obj.x, obj.y)
main()
a) Error, the syntax of the invoking method is wrong
b) The program runs fine but nothing is printed
c) 1 0
d) 1 2

11. What does built-in function type do in context of classes?


a) Determines the object name of any value
b) Determines the class name of any value
c) Determines class description of any value
d) Determines the file name of any value

12. Which of the following is not a type of inheritance?


a) Double-level
b) Multi-level
c) Single-level
d) Multiple

13. What does built-in function help do in context of classes?


a) Determines the object name of any value
b) Determines the class identifiers of any value
c) Determines class description of any built-in type
d) Determines class description of any user-defined built-in type

121 | P a g e
14. What will be the output of the following Python code?
class A:
def one(self):
return self.two()

def two(self):
return 'A'
class B(A):
def two(self):
return 'B'
obj1=A()
obj2=B()print(obj1.two(),obj2.two())
a) A A
b) A B
c) B B
d) An exception is thrown

15. What type of inheritance is illustrated in the following Python code?


class A():
passclass B():
passclass C(A,B):
pass
a) Multi-level inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Single-level inheritance

16. What type of inheritance is illustrated in the following Python code?


class A():
passclass B(A):
passclass C(B):
pass
a) Multi-level inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Single-level inheritance

17. What does single-level inheritance mean?


a) A subclass derives from a class which in turn derives from another class
b) A single superclass inherits from multiple subclasses
c) A single subclass derives from a single superclass
d) Multiple base classes inherit a single derived class

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


class A:
def __init__(self):
self.__i = 1
self.j = 5

def display(self):
print(self.__i, self.j)class B(A):
def __init__(self):
super().__init__()

122 | P a g e
self.__i = 2
self.j = 7
c = B()
c.display()
a) 2 7
b) 1 5
c) 1 7
d) 2 5

19. Which of the following statements isn‟t true?


a) A non-private method in a superclass can be overridden
b) A derived class is a subset of superclass
c) The value of a private variable in the superclass can be changed in the subclass
d) When invoking the constructor from a subclass, the constructor of superclass is automatically
invoked

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


>>> class A:
pass>>> class B(A):
pass>>> obj=B()>>> isinstance(obj,A)
a) True
b) False
c) Wrong syntax for isinstance() method
d) Invalid method for classes

21. Which of the following statements is true?


a) The __new__() method automatically invokes the __init__ method
b) The __init__ method is defined in the object class
c) The __eq(other) method is defined in the object class
d) The __repr__() method is defined in the object class

22. Method issubclass() checks if a class is a subclass of another class.


a) True
b) False

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


class A:
def __init__(self):
self.__x = 1class B(A):
def display(self):
print(self.__x)def main():
obj = B()
obj.display()
main()
a) 1
b) 0
c) Error, invalid syntax for object declaration
d) Error, private class member can‟t be accessed in a subclass

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


class A:
def __init__(self):
self._x = 5 class B(A):

123 | P a g e
def display(self):
print(self._x)def main():
obj = B()
obj.display()
main()
a) Error, invalid syntax for object declaration
b) Nothing is printed
c) 5
d) Error, private class member can‟t be accessed in a subclass

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


class A:
def __init__(self,x=3):
self._x = x class B(A):
def __init__(self):
super().__init__(5)
def display(self):
print(self._x)def main():
obj = B()
obj.display()

main()
a) 5
b) Error, class member x has two values
c) 3
d) Error, protected class member can‟t be accessed in a subclass
View Answer
26. What will be the output of the following Python code?
class A:
def test1(self):
print(" test of A called ")class B(A):
def test(self):
print(" test of B called ")class C(A):
def test(self):
print(" test of C called ")class D(B,C):
def test2(self):
print(" test of D called ")
obj=D()
obj.test()
a)
test of B called
test of C called
b)
test of C called
test of B called
c) test of B called
d) Error, both the classes from which D derives has same method test()

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


class A:
def test(self):
print("test of A called")class B(A):
def test(self):

124 | P a g e
print("test of B called")
super().test() class C(A):
def test(self):
print("test of C called")
super().test()class D(B,C):
def test2(self):
print("test of D called")
obj=D()
obj.test()

a) test of B called
test of C called
test of A called
b) test of C called
test of B called
c) test of B called
test of C called
d) Error, all the three classes from which D derives has same method test()

1.a 2.c 3.b 4.c 5.d 6.b 7.b 8.a 9.c 10.d 11.b 12.a 13.c 14.b
15.b 16.a 17.c 18.c 19.c 20.a 21.c 22.a 23.d 24.c 25.a 26.c
27.a

UNIT V

# Iterators
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of
the methods __iter__() and __next__().

 Create an Iterator

To create an object/class as an iterator you have to implement the


methods __iter__() and __next__() to your object.
All classes have a function called __init__(), which allows you to do some initializing when the object
is being created.
The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the
iterator object itself.

125 | P a g e
The __next__() method also allows you to do operations, and must return the next item in the
sequence.

Example

Create an iterator that returns numbers, starting with 1, and each sequence will increase by one
(returning 1,2,3,4,5 etc.):
class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

# Recursion

Python also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a function


calls itself. This has the benefit of meaning that you can loop through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory or
processor power. However, when written correctly recursion can be a very efficient and
mathematically-elegant approach to programming.

In this example, tri_recursion() is a function that we have defined to call itself ("recurse").
We use the k variable as the data, which decrements (-1) every time we recurse. The
recursion ends when the condition is not greater than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works, best way to
find out is by testing and modifying it.

Example

126 | P a g e
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

 Recursive Fibonacci

A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....

The first two terms are 0 and 1. All other terms are obtained by adding the preceding two
terms.This means to say the nth term is the sum of (n-1)th and (n-2)th term.

# Function for nth Fibonacci number

def Fibonacci(n):
if n<0:
print("Incorrect input")
# First Fibonacci number is 0
elif n==1:
return 0
# Second Fibonacci number is 1
elif n==2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)

# Driver Program

print(Fibonacci(9))

Output:
21

 Tower of Hanoi
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The
objective of the puzzle is to move the entire stack to another rod, obeying the following
simple rules:

1) Only one disk can be moved at a time.


2) Each move consists of taking the upper disk from one of the stacks and placing it on
top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
Note: Transferring the top n-1 disks from source rod to Auxilliary rod can again be

127 | P a g e
thought of as a fresh problem and can be solved in the same manner.

def TowerOfHanoi(n , source, destination, auxilliary):


if n==1:
print "Move disk 1 from source",source,"to destination",destination
return
TowerOfHanoi(n-1, source, auxilliary, destination)
print "Move disk",n,"from source",source,"to destination",destination
TowerOfHanoi(n-1, auxilliary, destination, source)

# Driver code
n=4
TowerOfHanoi(n,'A','B','C')
# A, C, B are the name of rods

Output:

Move disk 1 from rod A to rod B


Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which is the most appropriate definition for recursion?


a) A function that calls itself
b) A function execution instance that calls another execution instance of the same function
c) A class method that calls another class method
d) An in-built method that is automatically called

2. Only problems that are recursively defined can be solved using recursion.
a)True
b) False

3. Which of these is false about recursion?


a) Recursive function can be replaced by a non-recursive function
b) Recursive functions usually take more memory space than non-recursive function

128 | P a g e
c) Recursive functions run faster than non-recursive function
d) Recursion makes programs easier to understand

4. Fill in the line of the following Python code for calculating the factorial of a number.
def fact(num):
if num == 0:
return 1
else:
return _____________________
a) num*fact(num-1)
b) (num-1)*(num-2)
c) num*(num-1)
d) fact(num)*fact(num-1)

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


def test(i,j):
if(i==0):
return j
else:
return test(i-1,i+j)
print(test(4,7))

a) 13
b) 7
c) Infinite loop
d) 17

6. What is tail recursion?


a) A recursive function that has two base cases
b) A function where the recursive functions leads to an infinite loop
c) A recursive function where the function doesn‟t return anything and just prints the values
d) A function where the recursive call is the last thing executed by the function

7. Which of the following statements is false about recursion?


a) Every recursive function must have a base case
b) Infinite recursion can occur if the base case isn‟t properly mentioned
c) A recursive function makes the code easier to understand
d) Every recursive function must have a return value

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


def fun(n):
if (n > 100):
return n - 5
return fun(fun(n+11));
print(fun(45))

a) 50
b) 100
c) 74
d) Infinite loop

9. Recursion and iteration are the same programming approach.


a)True

129 | P a g e
b) False

10. What happens if the base condition isn‟t defined in recursive programs?
a) Program gets into an infinite loop
b) Program runs once
c) Program runs n number of times where n is the argument given to the function
d) An exception is thrown

11. Which of these is not true about recursion?


a) Making the code look clean
b) A complex task can be broken into sub-problems
c) Recursive calls take up less memory
d) Sequence generation is easier than a nested iteration

12. Which of these is not true about recursion?


a) It‟s easier to code some real-world problems using recursion than non-recursive equivalent
b) Recursive functions are easy to debug
c) Recursive calls take up a lot of memory
d) Programs using recursion take longer time than their non-recursive equivalent

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


def a(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return a(n-1)+a(n-2)
for i in range(0,4):
print(a(i),end=" ")

a) 0 1 2 3
b) An exception is thrown
c) 0 1 1 2 3
d) 0 1 1 2

14. Suppose the first fibonnaci number is 0 and the second is 1. What is the sixth
fibonnaci number?
a) 5
b) 6
c) 7
d) 8

15. Which of the following is not a fibonnaci number?


a) 8
b) 21
c) 55
d) 14

130 | P a g e
16. Which of the following option is wrong?
a) Fibonacci number can be calculated by using Dynamic programming
b) Fibonacci number can be calculated by using Recursion method
c) Fibonacci number can be calculated by using Iteration method
d) No method is defined to calculate Fibonacci number.

17. Which of the following recurrence relations can be used to find the nth fibonacci
number?
a) F(n) = F(n) + F(n – 1)
b) F(n) = F(n) + F(n + 1)
c) F(n) = F(n – 1)
d) F(n) = F(n – 1) + F(n – 2)

18. How many times will the function fibo() be called when the following code is executed?
int fibo(int n){
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);}int main(){
int n = 5;
int ans = fibo(n);
printf("%d",ans);
return 0;}
a) 5
b) 6
c) 8
d) 9\
19. What is the output of the following code?
int fibo(int n){
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);}int main(){
int n = 10;
int ans = fibo(n);
printf("%d",ans);
return 0;}
a) 21
b) 34
c) 55
d) 13

20. What is the output of the following code?


int fibo(int n){
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);}int main(){

131 | P a g e
int n = 5;
int ans = fibo(n);
printf("%d",ans);
return 0;}
a) 1
b) 2
c) 3
d) 5

21. What is the objective of tower of hanoi puzzle?


a) To move all disks to some other rod by following rules
b) To divide the disks equally among the three rods by following rules
c) To move all disks to some other rod in random order
d) To divide the disks equally among three rods in random order

22. Which of the following is NOT a rule of tower of hanoi puzzle?


a) No disk should be placed over a smaller disk
b) Disk can only be moved if it is the uppermost disk of the stack
c) No disk should be placed over a larger disk
d) Only one disk can be moved at a time

23. The time complexity of the solution tower of hanoi problem using recursion is _________
a) O(n2)
b) O(2n)
c) O(n log n)
d) O(n)

24. Recurrence equation formed for the tower of hanoi problem is given by _________
a) T(n) = 2T(n-1)+n
b) T(n) = 2T(n/2)+c
c) T(n) = 2T(n-1)+c
d) T(n) = 2T(n/2)+n

25. Minimum number of moves required to solve a tower of hanoi problem with n disks is
__________
a) 2n
b) 2n-1
c) n2
d) n2-1

26. Space complexity of recursive solution of tower of hanoi puzzle is ________


a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)

27. Recursive solution of tower of hanoi problem is an example of which of the


following algorithm?
a) Dynamic programming

132 | P a g e
b) Backtracking
c) Greedy algorithm
d) Divide and conquer

28. Tower of hanoi problem can be solved iteratively.


a) True
b) False

29. Minimum time required to solve tower of hanoi puzzle with 4 disks assuming one
move takes 2 seconds, will be __________
a) 15 seconds
b) 30 seconds
c) 16 seconds
d) 32 seconds

ANSWERS :

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

# Searching

Searching is a very basic necessity when you store data in different data structures. The
simplest appraoch is to go across every element in the data structure and match it with the
value you are searching for. This is known as Linear search. It is inefficient and rarely
used, but creating a program for it gives an idea about how we can implement some
advanced search algorithms.

1. Sequential Search: In this, the list or array is traversed sequentially and every element is checked.
For example: Linear Search.
2. Interval Search: These algorithms are specifically designed for searching in sorted data-structures.
These type of searching algorithms are much more efficient than Linear Search as they repeatedly
target the center of the search structure and divide the search space in half. For Example: Binary
Search.

 Linear Search

Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[].
Examples :
Input : arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 110;
Output : 6
Element x is present at index 6

133 | P a g e
Input : arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 175;
Output : -1
Element x is not present in arr[].

A simple approach is to do linear search, i.e

 Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
 If x matches with an element, return the index.
 If x doesn‟t match with any of elements, return -1.

def search(arr, n, x):

for i in range (0, n):


if (arr[i] == x):
return i;
return -1;

# Driver Code
arr = [ 2, 3, 4, 10, 40 ];
x = 10;
n = len(arr);
result = search(arr, n, x)
if(result == -1):
print("Element is not present in array")
else:
print("Element is present at index", result);

Output:
Element is present at index 3

The time complexity of above algorithm is O(n).


Linear search is rarely used practically because other search algorithms such as the binary search
algorithm and hash tables allow significantly faster searching comparison to Linear search.

 Binary Search
Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].
A simple approach is to do linear search.The time complexity of above algorithm is O(n). Another
approach to perform the same task is using Binary Search.

Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an
interval covering the whole array. If the value of the search key is less than the item in the middle of
the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly
check until the value is found or the interval is empty.

The idea of binary search is to use the information that the array is sorted and reduce the time
complexity to O(Log n).

134 | P a g e
We basically ignore half of the elements just after one comparison.

1. Compare x with the middle element.


2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half subarray after the mid
element. So we recur for right half.
4. Else (x is smaller) recur for the left half.

def binarySearch (arr, l, r, x):

# Check base case


if r >= l:

mid = l + (r - l) // 2

# If element is present at the middle itself


if arr[mid] == x:
return mid

# If element is smaller than mid, then it


# can only be present in left subarray
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)

# Else the element can only be present


# in right subarray
else:
return binarySearch(arr, mid + 1, r, x)

else:
# Element is not present in the array
return -1

# Driver Code
arr = [ 2, 3, 4, 10, 40 ]
x = 10

# Function call
result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:
print ("Element is present at index % d" % result)
else:
print ("Element is not present in array")

Output :
Element is present at index 3

 MULTIPLE CHOICE QUESTIONS ANSWERS

135 | P a g e
1. Where is linear searching used?
a) When the list has only a few elements
b) When performing a single search in an unordered list
c) Used all the time
d) When the list has only a few elements and When performing a single search in an unordered list.

2. What is the best case for linear search?


a) O(nlogn)
b) O(logn)
c) O(n)
d) O(1)

3. What is the worst case for linear search?


a) O(nlogn)
b) O(logn)
c) O(n)
d) O(1)

4. What is the best case and worst case complexity of ordered linear search?
a) O(nlogn), O(logn)
b) O(logn), O(nlogn)
c) O(n), O(1)
d) O(1), O(n)

5. Which of the following is a disadvantage of linear search?


a) Requires more space
b) Greater time complexities compared to other searching algorithms
c) Not easy to understand
d) Not easy to implement
6. Is there any difference in the speed of execution between linear serach(recursive)
vs linear search(lterative)?
a) Both execute at same speed
b) Linear search(recursive) is faster
c) Linear search(Iterative) is faster
d) Cant be said

7. Is the space consumed by the linear search(recursive) and linear search(iterative)


same?
a) No, recursive algorithm consumes more space
b) No, recursive algorithm consumes less space
c) Yes
d) Nothing can be said

8. What is the worst case runtime of linear search(recursive) algorithm?


a) O(n)
b) O(logn)
c) O(n2)

136 | P a g e
d) O(nx)

9. Linear search(recursive) algorithm used in _____________


a) When the size of the dataset is low
b) When the size of the dataset is large
c) When the dataset is unordered
d) Never used

10. The array is as follows: 1,2,3,6,8,10. At what time the element 6 is found? (By
using linear search(recursive) algorithm)
a) 4th call
b) 3rd call
c) 6th call
d) 5th call

11. The array is as follows: 1,2,3,6,8,10. Given that the number 17 is to be searched.
At which call it tells that there‟s no such element? (By using linear search(recursive)
algorithm)
a) 7th call
b) 9th call
c) 17th call
d) The function calls itself infinite number of times

12. What is the best case runtime of linear search(recursive) algorithm on an


ordered set of elements?
a) O(1)
b) O(n)
c) O(logn)
d) O(nx)

13. Can linear search recursive algorithm and binary search recursive algorithm be
performed on an unordered list?
a) Binary search can‟t be used
b) Linear search can‟t be used
c) Both cannot be used
d) Both can be used

14. What is the recurrence relation for the linear search recursive algorithm?
a) T(n-2)+c
b) 2T(n-1)+c
c) T(n-1)+c
d) T(n+1)+c

15. What is the advantage of recursive approach than an iterative approach?


a) Consumes less memory
b) Less code and easy to implement

137 | P a g e
c) Consumes more memory
d) More code has to be written

16. Given an input arr = {2,5,7,99,899}; key = 899; What is the level of recursion?
a) 5
b) 2
c) 3
d) 4

17. Given an array arr = {45,77,89,90,94,99,100} and key = 99; what are the mid
values(corresponding array elements) in the first and second levels of recursion?
a) 90 and 99
b) 90 and 94
c) 89 and 99
d) 89 and 94

18. What is the worst case complexity of binary search using recursion?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

19. What is the average case time complexity of binary search using recursion?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

20. Which of the following is not an application of binary search?


a) To find the lower/upper bound in an ordered sequence
b) Union of intervals
c) Debugging
d) To search in unordered list.

21. Binary Search can be categorized into which of the following?


a) Brute Force technique
b) Divide and conquer
c) Greedy algorithm
d) Dynamic programming

22. Given an array arr = {5,6,77,88,99} and key = 88; How many iterations are done
until the element is found?
a) 1
b) 3
c) 4
d) 2

138 | P a g e
23. Given an array arr = {45,77,89,90,94,99,100} and key = 100; What are the mid
values(corresponding array elements) generated in the first and second iterations?
a) 90 and 99
b) 90 and 100
c) 89 and 94
d) 94 and 99

24. What is the time complexity of binary search with iteration?


a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

ANSWERS :

1.d 2.d 3.c 4.d 5.b 6.c 7.a 8.a 9.a 10.a 11.a 12.a 13.a 14.c
15.b 16.c 17.a 18.b 19.b 20.d 21.b 22.d 23.a 24.b

# Sorting
Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way
to arrange data in a particular order. Most common orders are in numerical or
lexicographical order.
The importance of sorting lies in the fact that data searching can be optimized to a very
high level, if data is stored in a sorted manner. Sorting is also used to represent data in
more readable formats.

 Selection Sort

In selection sort we start by finding the minimum value in a given list and move it to a
sorted list. Then we repeat the process for each of the remaining elements in the unsorted
list. The next element entering the sorted list is compared with the existing elements and
placed at its correct position. So at the end all the elements from the unsorted list are
sorted.

def selection_sort(input_list):

for idx in range(len(input_list)):

min_idx = idx
for j in range( idx +1, len(input_list)):
if input_list[min_idx] > input_list[j]:

139 | P a g e
min_idx = j# Swap the minimum value with the compared value

input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx]

l = [19,2,31,45,30,11,121,27]
selection_sort(l)print(l)

When the above code is executed, it produces the following result −


[2, 11, 19, 27, 30, 31, 45, 121]

 Merge sort

Merge sort first divides the array into equal halves and then combines them in a sorted manner.

def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list# Find the middle point and devide it
middle = len(unsorted_list) // 2
left_list = unsorted_list[:middle]
right_list = unsorted_list[middle:]

left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return list(merge(left_list, right_list))
# Merge the sorted halves
def merge(left_half,right_half):

res = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
res.append(left_half[0])
left_half.remove(left_half[0])
else:
res.append(right_half[0])
right_half.remove(right_half[0])
if len(left_half) == 0:
res = res + right_half
else:
res = res + left_half
return res

unsorted_list = [64, 34, 25, 12, 22, 11, 90]


print(merge_sort(unsorted_list))

When the above code is executed, it produces the following result −

[11, 12, 22, 25, 34, 64, 90]

140 | P a g e
 MULTIPLE CHOICE QUESTIONS ANSWERS

1.What is an in-place sorting algorithm?


a) It needs O(1) or O(logn) memory to create auxiliary locations
b) The input is already sorted and in-place
c) It requires additional storage
d) It requires additional space

2. In the following scenarios, when will you use selection sort?


a) The input is already sorted
b) A large file has to be sorted
c) Large values need to be sorted with small keys
d) Small values need to be sorted with large keys

3. What is the worst case complexity of selection sort?


a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

4. What is the advantage of selection sort over other sorting techniques?


a) It requires no additional storage space
b) It is scalable
c) It works best for inputs which are already sorted
d) It is faster than any other sorting technique

5. What is the average case complexity of selection sort?


a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

6. What is the disadvantage of selection sort?


a) It requires auxiliary memory
b) It is not scalable
c) It can be used for small keys
d) It takes linear time to sort the elements

7. The given array is arr = {3,4,5,2,1}. The number of iterations in bubble sort and
selection sort respectively are,
a) 5 and 4
b) 4 and 5
c) 2 and 4
d) 2 and 5

141 | P a g e
8. The given array is arr = {1,2,3,4,5}. (bubble sort is implemented with a flag
variable)The number of iterations in selection sort and bubble sort respectively are,
a) 5 and 4
b) 1 and 4
c) 0 and 4
d) 4 and 1

9. What is the best case complexity of selection sort?


a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

10. Merge sort uses which of the following technique to implement sorting?
a) backtracking
b) greedy algorithm
c) divide and conquer
d) dynamic programming

11. What is the average case time complexity of merge sort?


a) O(n log n)
b) O(n2)
c) O(n2 聽 log n)
d) O(n log n2)
12. What is the auxiliary space complexity of merge sort?
a) O(1)
b) O(log n)
c) O(n)
d) O(n log n)

13. Merge sort can be implemented using O(1) auxiliary space.


a) true
b) false

14. What is the worst case time complexity of merge sort?


a) O(n log n)
b) O(n2)
c) O(n2log n)
d) O(n log n2)

15. Which of the following method is used for sorting in merge sort?
a) merging
b) partitioning
c) selection
d) exchanging

142 | P a g e
16. What will be the best case time complexity of merge sort?
a) O(n log n)
b) O(n2)
c) O(n2 log n)
d) O(n log n2)

17. Which of the following is not a variant of merge sort?


a) in-place merge sort
b) bottom up merge sort
c) top down merge sort
d) linear merge sort

18. Choose the incorrect statement about merge sort from the following?
a) it is a comparison based sort
b) it is an adaptive algorithm
c) it is not an in place algorithm
d) it is stable algorithm

19. Which of the following is not in place sorting algorithm?


a) merge sort
b) quick sort
c) heap sort
d) insertion sort

20. Which of the following is not a stable sorting algorithm?


a) Quick sort
b) Cocktail sort
c) Bubble sort
d) Merge sort

21. Which of the following stable sorting algorithm takes the least time when applied
to an almost sorted array?
a) Quick sort
b) Insertion sort
c) Selection sort
d) Merge sort

22. Merge sort is preferred for arrays over linked lists.


a) true
b) false

23. Which of the following sorting algorithm makes use of merge sort?
a) tim sort
b) intro sort
c) bogo sort

143 | P a g e
d) quick sort

24. Which of the following sorting algorithm does not use recursion?
a) quick sort
b) merge sort
c) heap sort
d) bottom up merge sort

ANSWERS :
1.a 2.c 3.d 4.a 5.d 6.b 7.a 8.d 9.d 10.c
11.a 12.c 13.a 14.a 15.a 16.a 17.a 18.b 19.a
20.a 21.d 22.b 23.a 24.d

 MULTIPLE CHOICE QUESTIONS ANSWERS

144 | P a g e
145 | P a g e
AKTU RKC TECHNO FAMILY
ALL NOTES DOWNLOAD BY TELEGRAM CHANNEL

FIRST YEAR STUDENT NOTES

DOWNLOAD ▶

AKTU ( B.TECH) STUDENT NOTES

DOWNLOAD ▶

AKTU DISCUSSION GROUP

JOIN▶

AKTU LATEST UPDATE

Subscribe ▶

Thanks for join AKTU RKC TECHNO FAMILY.


Don't have Telegram yet? Try it now!

ONLINE AKTU STUDENT


DISCUSSION GROUP (3k
pdf notes)❤
4 866 members, 573 online

📚FIRST YEAR ALL NOTES

@ rst_year_aktu_student_gp

📚Aktu all branch| sem notes …

VIEW IN TELEGRAM

If you have Telegram, you can view and join


ONLINE AKTU STUDENT DISCUSSION GROUP (3k
pdf notes)❤ right away.
KNC 402 – Python Programming
Unit 1
MCQ
Topics
✓ Introduction
✓ Basics

1. Is Python case sensitive when dealing with identifiers?


a) yes
b) no
c) machine dependent
d) none of the mentioned
2. What is the maximum possible length of an identifier?
a) 31 characters
b) 63 characters
c) 79 characters
d) none of the mentioned
3. Which of the following is invalid?
a) _a = 1
b) __a = 1
c) __str__ = 1
d) none of the mentioned
4. Which of the following is an invalid variable?
a) my_string_1
b) 1st_string
c) foo
d) _
5. Which of the following is an invalid statement?
a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000
6. What statement is correct for explicit type conversion in python?
a. The data type is manually changed by the user as per their requirement.
b. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base
in which string is if the data type is a string.
c. float(): This function is used to convert any data type to a floating-point number.
d. All of the above.
7. Which of the below statement is incorrect?
a. ord() : This function is used to convert a character to integer.
b. hex() : This function is to convert integer to hexadecimal string.
c. oct() : This function is to convert integer to octal string.
d. None of the above
8. Tick the correct output of below program: -
# Python code to demonstrate Type conversion using tuple(), set(), list()
# Initializing string
s = 'geeks'
# Printing string converting to tuple
c = tuple(s)
print ("After converting string to tuple: “, end="")
print (c)
# Printing string converting to set
c = set(s)
print ("After converting string to set: “, end="")
print (c)
# Printing string converting to list
c = list(s)
print ("After converting string to list: “, end="")
print (c)
a. After converting string to tuple: ('g', 'e', 'e', 'k', 's')
After converting string to set: {'k', 'e', 's', 'g'}
After converting string to list: ['g', 'e', 'e', 'k', 's']
b. After converting string to tuple: ('g', 'e')
After converting string to set: {'k', 'e'}
After converting string to list: ['g', 'e']
c. After converting string to tuple: {'g', 'e'}
After converting string to set: {'k', 'e'}
After converting string to list: ['g', 'e']
d. After converting string to tuple: ('g', 'e', 'e', 'k', 's')
After converting string to set: {'k', 'e', 's', 'g'}
After converting string to list: {'g', 'e', 'e', 'k', 's'}

9. chr(number) : : This function converts number to its corresponding ASCII


character. Tick the correct output of below program: -
# Convert ASCII value to characters
a = chr(76)
b = chr(77)
print(a)
print(b)
a. L
M
b. l
m
c. m
l
d. M
L
10. What is the output of below code?
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
x=x+y
print(x)
print("x is of type:",type(x))

a.
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
x is of type: <class 'float'>
b.
x is of type: <class 'float'>
y is of type: <class 'float'>
20.6
x is of type: <class 'float'>
c. x is of type: <class 'float'>
y is of type: <class 'int'>
20.6
x is of type: <class 'float'>
d. None of the above
11. 1. Which is the correct operator for power(xy)?
a) X^y
b) X**y
c) X^^y
d) None of the mentioned
12. Which one of these is floor division?
a) /
b) //
c) %
d) None of the mentioned
13. What is the order of precedence in python?
i) Parentheses
ii) Exponential
iii) Multiplication
iv) Division
v) Addition
vi) Subtraction
a) i,ii,iii,iv,v,vi
b) ii,i,iii,iv,v,vi
c) ii,i,iv,iii,v,vi
d) i,ii,iii,iv,vi,v
14. What is the answer to this expression, 22 % 3 is?
a) 7
b) 1
c) 0
d) 5
15. 10. What is the value of the following expression?
float(22//3+3/3)
a)8
b)8.0
c)8.3
d) 8.33
16. What is the value of the following expression?
2+4.00, 2**4.0
a)(6.0,16.0)
b)(6.00,16.00)
c)(6,16)
d) (6.00, 16.0)
17. What will be the value of X in the following Python expression?
X = 2+9*((3*12)-8)/10
a)30.0
b)30.8
c)28.4
d) 27.2

18. What will be the output of the following Python expression if x=15 and y=12?
x&y
a)b1101
b)0b1101
c)12
d) 1101

19. What will be the output of the following Python code snippet if x=1?
x<<2
a)8
b)1
c)2
d) 4

20. What will be the output of the following Python code snippet?
not(3>4)
not(1&1)
a) True
True
b) True
False
c) False
False
d) None of the above

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


class Truth:
pass
x=Truth()
bool(x)
a) True
b) False
c) All of the above
d) None of the above

22 Which of the following Boolean expressions is not logically equivalent to the other three?
a) not(-6<0 or-6>10)
b) -6>=0 and -6<=10
c) not(-6<10 or-6==10)
d) not(-6>10 or-6==10)

23. What will be the output of the following Python code snippet?
not(10<20) and not(10>30)
a)True
b) False
c) Error
d) No output
24. What will be the output of the following Python code?
1. >>>str="hello"
2. >>>str[:2]
3. >>>
a)he
b)lo
c)olleh
d) hello

25. What error occurs when you execute the following Python code snippet?
apple = mango
a)SyntaxError
b)NameError
c)ValueError
d) TypeError

26. What will be the output of the following Python code snippet?
1. def example(a):
2. a = a + '2'
3. a = a*2
4. return a
5. >>>example("hello")
a) indentation Error
b) cannot perform mathematical operation on strings
c)hello2
d) hello2hello2

27. What is the average value of the following Python code snippet?
1. >>>grade1 = 80
2. >>>grade2 = 90
3. >>>average = (grade1 + grade2) / 2
a)85.0
b)85.1
c)95.0
d) 95.1

28. Select all options that print.


hello-how-are-you
a)print(‘hello’, ‘how’, ‘are’, ‘you’)
b)print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4)
c)print(‘hello-‘ + ‘how-are-you’)
d) print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ + ‘you’)

29. Which of the following expressions can be used to multiply a given number ‘a’ by 4?
a)a<<2
b)a<<4
c)a>>2
d) a>>4

30. What will be the output of the following Python code if a=10 and b =20?
a=10
b=20
a=a^b
b=a^b
a=a^b
print(a,b)
a) 10 20
b) 10 10
c) 20 10
d) 20 20
KNC 402 – Python Programming
Unit 2
MCQ
Topics
✓ Conditional
✓ Loops

1. What will never be printed as output regardless of the value of x in the following piece of
python code -
if x < 5 :
print('Less than 5')
elif x >= 2 :
print('5 or more')
else :
print('any range')
a) Less than 5
b) 5 or more
c) any range
d) None of the above
2- What will never be printed as output regardless of the value of x in the following piece of
python code –
if x < 5 :
print('Less than 5')
elif x < 25 :
print('Less than 25')
elif x < 15 :
print(‘Less than 15’)
else :
print('any range')
a) Less than 5
b) Less than 25
c) any range
d) Less than 15
3. What is the output of following python code –
a = True
b = False
c = False
if not a or b:
print('a')
elif not a or not b and c:#false or True and false
print('b')
elif not a or b or not b and a: #False or False or True
print('c')
else:
print('d')
1) a
2) b
3) c
4) d
4. What will be the output of the following program on execution?
if False:
print ("inside if block")
elif True:
print ("inside elif block")
else:
print ("inside else block")

A. inside if block
B. inside elif block
C. inside else block
D. Error
5. What will be the result of following Python code snippet after execution?
a=0
b=1
if (a and b):
print("hi")
elif(not(a)):
print("hello")
elif(b):
print("hi world")
else:
print("hello world")
A. hello world
B. hi
C. hi world
D. hello
6. Which of the following are in correct order with respect to conditional statements in Python?
(i) if
(ii) else
(iii) elif

A. i, iii, ii
B. ii, iii ,i
C. iii, ii, i
D. ii, i, iii
7. What will be the output of the following Python code?
x = ['ab', 'cd']
for i in x:
i.upper()
print(x)
a) [‘ab’, ‘cd’]
b) [‘AB’, ‘CD’]
c) [None, None]
d) none of the mentioned
8. What will be the output of the following Python code?
x = ['ab', 'cd']
for i in x:
x.append(i.upper())
print(x)
a) [‘AB’, ‘CD’]
b) [‘ab’, ‘cd’, ‘AB’, ‘CD’]
c) [‘ab’, ‘cd’]
d) none of the mentioned
9. What will be the output of the following Python code?
i=1
while True:
if i%3 == 0:
break
print(i)
i+=1
a) 1 2
b) 1 2 3
c) error
d) none of the mentioned
10. What will be the output of the following Python code?
i=1
while True:
if i%0O7 == 0:
break
print(i)
i += 1
a) 1 2 3 4 5 6
b) 1 2 3 4 5 6 7
c) error
d) none of the mentioned
11. What will be the output of the following Python code?
i=2
while True:
if i%3 == 0:
break
print(i)
i += 2
a) 2 4 6 8 10 …
b) 2 4
c) 2 3
d) error
12. What will be the output of the following Python code?
i=0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print(0)
a) 0 1 2 0
b) 0 1 2
c) error
d) none of the mentioned
13. What will be the output of the following Python code?
x = "abcdef"
while i in x:
print(i, end=" ")
a) a b c d e f
b) abcdef
c) i i i i i i …
d) error
14. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")
a) no output
b) i i i i i i …
c) a a a a a a …
d) a b c d e f
15. What will be the output of the following Python code?
x = 'abcd'
for i in x:
print(i.upper())
a) a b c d
b) A B C D
c) a B C D
d) error
16. What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'}
for i in d:
print(i)
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
17. Which of the following is False regarding loops in Python?
A. Loops are used to perform certain tasks repeatedly.
B. While loop is used when multiple statements are to executed repeatedly until the given
condition becomes False
C. While loop is used when multiple statements are to executed repeatedly until the given
condition becomes True.
D. for loop can be used to iterate through the elements of lists.

18. Which of the following is True regarding loops in Python?


A. Loops should be ended with keyword "end".
B. No loop can be used to iterate through the elements of strings.
C. Keyword "break" can be used to bring control out of the current loop.
D. Keyword "continue" is used to continue with the remaining statements inside the loop.
19. What keyword would you use to add an alternative condition to an if statement?
A. else if
B. elseif
C. elif
D. None of the above
20. What will be the output of given Python code?

str1="hello"
c=0
for x in str1:
if(x!="l"):
c=c+1
else:
pass
print(c)
A. 2
B. 0
C. 4
D. 3
21. What will be the output of the following Python code?
for i in range(0,2,-1):
print("Hello")
A. Hello
B. Hello Hello
C. No Output
D. Error
22. What will be the output of the following code?
x = "abcdef"
i = "i"
while i in x:
print(i, end=" ")
A. a b c d e f
B. abcdef
C. i i i i i.....
D. No Output
23. What will be the output of the following code?
x = 12
for i in x:
print(i)
A. 12
B. 1 2
C. Error
D. None of the above
24. What will be the output of the following Python code?
x = ['ab', 'cd']
for i in x:
i.upper()
print(x)
a) [‘ab’, ‘cd’]
b) [‘AB’, ‘CD’]
c) [None, None]
d) none of the mentioned
25. What will be the output of the following Python code?
i=1
while True:
if i%0O7 == 0:
break
print(i)
i += 1
a) 1 2 3 4 5 6
b) 1 2 3 4 5 6 7
c) error
d) none of the mentioned
26. What will be the output of the following Python code?
x = "abcdef"
while i in x:
print(i, end=" ")
a) a b c d e f
b) abcdef
c) i i i i i i …
d) error
27. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x:
x = x[:-1]
print(i, end = " ")
a) i i i i i i
b) a a a a a a
c) a a a a a
d) none of the mentioned
28. What will be the output of the following Python code?
x = 'abcd'
for i in x:
print(i.upper())
a) a b c d
b) A B C D
c) a B C D
d) error
29. What will be the output of the following Python code snippet?
for i in [1, 2, 3, 4][::-1]:
print (i)
a) 1 2 3 4
b) 4 3 2 1
c) error
d) none of the mentioned
30. What will be the output of the following Python code snippet?
for i in ''.join(reversed(list('abcd'))):
print (i)
a) a b c d
b) d c b a
c) error
d) none of the mentioned
KNC 402 – Python Programming
Unit 3
MCQ

Topics:
✓ Functions
✓ Strings
✓ Sequences
✓ Higher Order Functions

1. Which of the following is the use of function in python?


a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity for your application
c) you can’t also create your own functions
d) All of the mentioned

Answer: a
Explanation: Functions are reusable pieces of programs. They allow you to give a name to a
block of statements, allowing you to run that block using the specified name anywhere in your
program and any number of times.

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

x = 50
def func(x):
print('x is', x)
x=2
print('Changed local x to', x)
func(x)
print('x is now', x)
a)

x is 50
Changed local x to 2
x is now 50
b)

x is 50
Changed local x to 2
x is now 2
c)
x is 50
Changed local x to 2
x is now 100
d) None of the mentioned

Answer: a
Explanation: The first time that we print the value of the name x with the first line in the
function’s body, Python uses the value of the parameter declared in the main block, above the
function definition.
Next, we assign the value 2 to x. The name x is local to our function. So, when we change the
value of x in the function, the x defined in the main block remains unaffected.
With the last print function call, we display the value of x as defined in the main block, thereby
confirming that it is actually unaffected by the local assignment within the previously called
function.

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

def func(a, b=5, c=10):


print('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
func(25, c = 24)
func(c = 50, a = 100)
a)

a is 7 and b is 3 and c is 10
a is 25 and b is 5 and c is 24
a is 5 and b is 100 and c is 50
b)

a is 3 and b is 7 and c is 10
a is 5 and b is 25 and c is 24
a is 50 and b is 100 and c is 5
c)

a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
d) None of the mentioned

Answer: c
Explanation: If you have some functions with many parameters and you want to specify only
some of them, then you can give values for such parameters by naming them – this is called
keyword arguments – we use the name (keyword) instead of the position (which we have been
using all along) to specify the arguments to the function.
The function named func has one parameter without a default argument value, followed by two
parameters with default argument values.
In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the value 7
and c gets the default value of 10.

In the second usage func(25, c=24), the variable a gets the value of 25 due to the position of the
argument. Then, the parameter c gets the value of 24 due to naming i.e. keyword arguments. The
variable b gets the default value of 5.

In the third usage func(c=50, a=100), we use keyword arguments for all specified values. Notice
that we are specifying the value for parameter c before that for a even though a is defined before
c in the function definition.

4. Which are the advantages of functions in python?


a) Reducing duplication of code
b) Decomposing complex problems into simpler pieces
c) Improving clarity of the code
d) All of the mentioned

Answer: d

5. What are the two main types of functions?


a) Custom function
b) Built-in function & User defined function
c) User function
d) System function

Answer: b
Explanation: Built-in functions and user defined ones. The built-in functions are part of the
Python language. Examples are: dir(), len() or abs(). The user defined functions are functions
created with the def keyword.

6. Where is function defined?


a) Module
b) Class
c) Another function
d) All of the mentioned

Answer: d
Explanation: Functions can be defined inside a module, a class or another function.
7. Which of the following is the use of id() function in python?
a) Id returns the identity of the object
b) Every object doesn’t have a unique id
c) All of the mentioned
d) None of the mentioned

Answer: a
Explanation: Each object in Python has a unique id. The id() function returns the object’s id.

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

def sum(*args):
'''Function returns the sum
of all values'''
r=0
for i in args:
r += i
return r
print sum.__doc__
print sum(1, 2, 3)
print sum(1, 2, 3, 4, 5)
a)

6
15
b)

6
100
c)

123
12345
d) None of the mentioned

Answer: a
Explanation: We use the * operator to indicate, that the function will accept arbitrary number of
arguments. The sum() function will return the sum of all arguments. The first string in the
function body is called the function documentation string. It is used to document the function.
The string must be in triple quotes.

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

y=6
z = lambda x: x * y
print z(8)
a) 48
b) 14
c) 64
d) None of the mentioned

Answer: a
Explanation: The lambda keyword creates an anonymous function. The x is a parameter, that is
passed to the lambda function. The parameter is followed by a colon character. The code next to
the colon is the expression that is executed, when the lambda function is called. The lambda
function is assigned to the z variable.
The lambda function is executed. The number 8 is passed to the anonymous function and it
returns 48 as the result. Note that z is not a name for this function. It is only a variable to which
the anonymous function was assigned.

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

min = (lambda x, y: x if x < y else y)


min(101*99, 102*98)
a) 9997
b) 9999
c) 9996
d) None of the mentioned

Answer: c

11. What will be the output of the following Python code snippet?

print('abcdefcdghcd'.split('cd', 2))
a) [‘ab’, ‘ef’, ‘ghcd’]
b) [‘ab’, ‘efcdghcd’]
c) [‘abcdef’, ‘ghcd’]
d) none of the mentioned

Answer: a
Explanation: The string is split into a maximum of maxsplit+1 substrings.

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

print('xyyxyyxyxyxxy'.replace('xy', '12', 0))


a) xyyxyyxyxyxxy
b) 12y12y1212x12
c) 12yxyyxyxyxxy
d) xyyxyyxyxyx12

Answer: a
Explanation: The first 0 occurrences of the given substring are replaced.

13. What will be the output of the following Python code snippet?

print('1.1'.isnumeric())
a) True
b) False
c) None
d) Error

Answer: b
Explanation: The character . is not a numeric character.

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

print("abcdef".find("cd") == "cd" in "abcdef")


a) True
b) False
c) Error
d) None of the mentioned

Answer: b
Explanation: The function find() returns the position of the sunstring in the given string whereas
the in keyword returns a value of Boolean type.

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

print("xyyzxyzxzxyy".count('yy'))
a) 2
b) 0
c) error
d) none of the mentioned

Answer: a
Explanation: Counts the number of times the substring ‘yy’ is present in the given string.

16. If a class defines the __str__(self) method, for an object obj for the class, you can use which
command to invoke the __str__ method.
a) obj.__str__()
b) str(obj)
c) print obj
d) all of the mentioned

Answer: d

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

[ord(ch) for ch in 'abc']


a) [97, 98, 99]
b) [‘97’, ‘98’, ‘99’]
c) [65, 66, 67]
d) Error

Answer: a
Explanation: The list comprehension shown above returns the ASCII value of each alphabet of
the string ‘abc’. Hence the output is: [97, 98, 99]. Had the string been ‘ABC’, the output would
be: [65, 66, 67].

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

t=32.00
[round((x-32)*5/9) for x in t]
a) [0]
b) 0
c) [0.00]
d) Error

Answer: d
Explanation: The value of t in the code shown above is equal to 32.00, which is a floating point
value. ‘Float’ objects are not iterable. Hence the code results in an error.

19.
Write a list comprehension equivalent for the Python code shown below.

for i in range(1, 101):


if int(i*0.5)==i*0.5:
print(i)
a) [i for i in range(1, 100) if int(i*0.5)==(i*0.5)]
b) [i for i in range(1, 101) if int(i*0.5)==(i*0.5)]
c) [i for i in range(1, 101) if int(i*0.5)=(i*0.5)]
d) [i for i in range(1, 100) if int(i*0.5)=(i*0.5)]

Answer: b
Explanation: The code shown above prints the value ‘i’ only if it satisfies the condition:
int(i*0.5) is equal to (i*0.5). Hence the required list comprehension is: [i for i in range(1, 101) if
int(i*0.5)==(i*0.5)].

20.
What is the list comprehension equivalent for: list(map(lambda x:x**-1, [1, 2, 3]))?
a) [1|x for x in [1, 2, 3]]
b) [-1**x for x in [1, 2, 3]]
c) [x**-1 for x in [1, 2, 3]]
d) [x^-1 for x in range(4)]

Answer: c
Explanation: The output of the function list(map(lambda x:x**-1, [1, 2, 3])) is [1.0, 0.5,
0.3333333333333333] and that of the list comprehension [x**-1 for x in [1, 2, 3]] is [1.0, 0.5,
0.3333333333333333]. Hence the answer is: [x**-1 for x in [1, 2, 3]].

21.
Write a list comprehension to produce the list: [1, 2, 4, 8, 16……212].
a) [(2**x) for x in range(0, 13)]
b) [(x**2) for x in range(1, 13)]
c) [(2**x) for x in range(1, 13)]
d) [(x**2) for x in range(0, 13)]

Answer: a
Explanation: The required list comprehension will print the numbers from 1 to 12, each raised to
2. The required answer is thus, [(2**x) for x in range(0, 13)].

22.
What is the list comprehension equivalent for?

{x : x is a whole number less than 20, x is even} (including zero)


a) [x for x in range(1, 20) if (x%2==0)]
b) [x for x in range(0, 20) if (x//2==0)]
c) [x for x in range(1, 20) if (x//2==0)]
d) [x for x in range(0, 20) if (x%2==0)]

Answer: d
Explanation: The required list comprehension will print a whole number, less than 20, provided
that the number is even. Since the output list should contain zero as well, the answer to this
question is: [x for x in range(0, 20) if (x%2==0)].
23.
What will be the output of the following Python list comprehension?

[j for i in range(2,8) for j in range(i*2, 50, i)]


a) A list of prime numbers up to 50
b) A list of numbers divisible by 2, up to 50
c) A list of non prime numbers, up to 50
d) Error

Answer: c
Explanation: The list comprehension shown above returns a list of non-prime numbers up to 50.
The logic behind this is that the square root of 50 is almost equal to 7. Hence all the multiples of
2-7 are not prime in this range.

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

l=["good", "oh!", "excellent!", "#450"]


[n for n in l if n.isalpha() or n.isdigit()]
a) [‘good’, ‘oh’, ‘excellent’, ‘450’ ]
b) [‘good’]
c) [‘good’, ‘#450’]
d) [‘oh!’, ‘excellent!’, ‘#450’]

Answer: b
Explanation: The code shown above returns a new list containing only strings which do not have
any punctuation in them. The only string from the list which does not contain any punctuation is
‘good’. Hence the output of the code shown above is [‘good’].

25.
What is the output of the following piece of code?

a=list((45,)*4)
print((45)*4)
print(a)
a)

180
[(45),(45),(45),(45)]
b)
(45,45,45,45)
[45,45,45,45]
c)

180
[45,45,45,45]
d) Syntax error

Answer: c
Explanation: (45) is an int while (45,) is a tuple of one element. Thus when a tuple is multiplied,
it created references of itself which is later converted to a list.

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

lst=[[1,2],[3,4]]
print(sum(lst,[]))
a) [[3],[7]]
b) [1,2,3,4]
c) Error
d) [10]

Answer: b
Explanation: The above piece of code is used for flattening lists.

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

places = ['Bangalore', 'Mumbai', 'Delhi']


<br class="blank" />places1 = places
places2 = places[:]
<br class="blank" />places1[1]="Pune"
places2[2]="Hyderabad"
print(places)
a) [‘Bangalore’, ‘Pune’, ‘Hyderabad’]
b) [‘Bangalore’, ‘Pune’, ‘Delhi’]
c) [‘Bangalore’, ‘Mumbai’, ‘Delhi’]
d) [‘Bangalore’, ‘Mumbai’, ‘Hyderabad’]

Answer: b
Explanation: places1 is an alias of the list places. Hence, any change made to places1 is reflected
in places. places2 is a copy of the list places. Thus, any change made to places2 isn’t reflected in
places.
28.
What will be the output of the following Python code?

x=[[1],[2]]
print(" ".join(list(map(str,x))))
a) [1] [2]
b) [49] [50]
c) Syntax error
d) [[1]] [[2]]

Answer: a
Explanation: The elements 1 and 2 are first put into separate lists and then combined with a
space in between using the join attribute.

29.

What will be the output of the following Python code?

a= [1, 2, 3, 4, 5]
for i in range(1, 5):
a[i-1] = a[i]
for i in range(0, 5):
print(a[i],end = " ")
a) 5 5 1 2 3
b) 5 1 2 3 4
c) 2 3 4 5 1
d) 2 3 4 5 5

Answer: d
Explanation: The items having indexes from 1 to 4 are shifted forward by one index due to the
first for-loop and the item of index four is printed again because of the second for-loop.

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

a = [1, 5, 7, 9, 9, 1]
<br class="blank" />b=a[0]
<br class="blank" />x= 0
for x in range(1, len(a)):
if a[x] > b:
b = a[x]
b= x
print(b)
a) 5
b) 3
c) 4
d) 0

Answer: c
Explanation: The above piece of code basically prints the index of the largest element in the list

KNC 402 – Python Programming


Unit 4
MCQ

Topics:
✓ OOPS concept
✓ File Handling
✓ Exception and Assertions
✓ Modules
✓ Abstraction

Q1. Which of the following is correct with respect to OOP concept in Python?
A. Objects are real world entities while classes are not real.
B. Classes are real world entities while objects are not real.
C. Both objects and classes are real world entities.
D. Both object and classes are not real.

Ans: A
Explanation: In OOP, classes are basically the blueprint of the objects. They does not have
physical existence.

Q2. How many objects and reference variables are there for the given Python code?

class A:
print("Inside class")
A()
A()
obj=A()

A. 2 and 1
B. 3 and 3
C. 3 and 1
D. 3 and 2
Ans : C
Explanation: obj is the reference variable here and an object will be created each time A() is
called. So there will be 3 objects created.

Q3. What will be the output of below Python code?

class Student:
def __init__(self,name,id):
self.name=name
self.id=id
print(self.id)

std=Student("Simon",1)
std.id=2
print(std.id)

A. 1
1
B. 1
2
C. 2
1
D. 2
2

Ans: B
Explanation: When object with id =1 is created for Student, constructor is invoked and it prints
1. Later, id has been changed to 2, so next print statement prints 2.

Q4. What will be the output of below Python code?


class A():
def __init__(self,count=100):
self.count=count

obj1=A()
obj2=A(102)
print(obj1.count)
print(obj2.count)

A. 100
100
B. 100
102
C. 102
102
D. Error

Ans: B
Explanation: By default,the value of "count" is 100, so obj1.count=100. For second object,
value of "count" is 102, so obj2.count=102.

Q5. Which of the following is correct?


class A:
def __init__(self,name):
self.name=name
a1=A("john")
a2=A("john")
A. id(a1) and id(a2) will have same value.
B. id(a1) and id(a2) will have different values.
C. Two objects with same value of attribute cannot be created.
D. None of the above

Ans: B
Explanation: Although both a1 and a2 have same value of attributes, but these two point to two
different object. Hence, their id will be different.

Q6. In python, what is method inside class?


A. attribute
B. object
C. argument
D. function

Ans: D
Explanation: In OOP of Python, function is known by "method".

Q7. What is true about Inheritance in Python?


A. Inheritance is the capability of one class to derive or inherit the properties from another
class.
B. It represents real-world relationships well.
C. It provides reusability of a code.
D. All of the above

Ans: D
Explanation: All of the above statement are true.

Q8. When a child class inherits from only one parent class, it is called?
A. single inheritance
B. singular inheritance
C. Multiple inheritance
D. Multilevel inheritance

Ans: A
Explanation: Single inheritance: When a child class inherits from only one parent class, it is
called single inheritance.

Q9. Which inheritance is a blend of more than one type of inheritance?


A. Single inheritance
B. Hybrid inheritance
C. Multiple inheritance
D. Multilevel inheritance

Ans: B
Explanation: Hybrid inheritance: This form combines more than one form of inheritance.
Basically, it is a blend of more than one type of inheritance.

Q10. Parent class is the class being inherited from, also called?
A. derived class
B. Child class
C. Hybrid class
D. base class

Ans: D
Explanation: Parent class is the class being inherited from, also called base class.

Q11. The child's __init__() function overrides the inheritance of the parent's __init__() function.
A. TRUE
B. FALSE
C. Can be true or false
D. Can’t say

Ans: A
Explanation: The child's __init__() function overrides the inheritance of the parent's __init__()
function.

Q12. __________function that will make the child class inherit all the methods and properties
from its parent

A. self
B. __init__()
C. super
D. pass
Ans: C
Explanation: Python also has a super() function that will make the child class inherit all the
methods and properties from its parent.

Q. 13 What will be output for the following code?


class A:
def __init__(self, x=1):
self.x = x
class der(A):
def __init__(self,y=2):
super().__init__()
self.y = y
def main():
obj = der()
print(obj.x, obj.y)
main()

A. Error, the syntax of the invoking method is wrong


B. The program runs fine but nothing is printed
C. 1 0
D. 1 2

Ans: D
Explanation: In the above piece of code, the invoking method has been properly implemented
and hence x=1 and y=2.

Q.14 How many except statements can a try-except block have?

A. 0
B. 1
C. more than one
D. more than zero

Ans: D
Explanation: There has to be at least one except statement.

Q.15. Can one block of except statements handle multiple exception?

A. yes, like except TypeError, SyntaxError [,…]


B. yes, like except [TypeError, SyntaxError]
C. No
D. None of the above

Ans: A
Explanation: Each type of exception can be specified directly. There is no need to put it in a list.
Q.16 To open a file c:\scores.txt for reading, we use _____________
A. infile = open(“c:\scores.txt”, “r”)
B. infile = open(“c:\\scores.txt”, “r”)
C. infile = open(file = “c:\scores.txt”, “r”)
D. infile = open(file = “c:\\scores.txt”, “r”)

Ans: B
Explanation: Execute help(open) to get more details.

Q. 17 To open a file c:\scores.txt for appending data, we use ____________


A. outfile = open(“c:\\scores.txt”, “a”)
B. outfile = open(“c:\\scores.txt”, “rw”)
C. outfile = open(file = “c:\scores.txt”, “w”)
D. outfile = open(file = “c:\\scores.txt”, “w”)

Ans: A
Explanation: ‘a’ is used to indicate that data is to be appended.

Q.18. Which of the following statements are true?


A. When you open a file for reading, if the file does not exist, an error occurs
B. When you open a file for writing, if the file does not exist, a new file is created
C. When you open a file for writing, if the file exists, the existing file is overwritten with the new
file
D. All of the mentioned

Ans: D
Explanation: all options are true.

Q.19 To read the entire remaining contents of the file as a string from a file object infile, we use
____________
A. infile.read(2)
B. infile.read()
C. infile.readline()
D. infile.readlines()

Ans: B
Explanation: read function is used to read all the lines in a file.

Q.20. Which of the following is not an advantage of using modules?


A. Provides a means of reuse of program code
B. Provides a means of dividing up tasks
C. Provides a means of reducing the size of the program
D. Provides a means of testing individual parts of the program
Ans: C.
Explanation: The total size of the program remains the same regardless of whether modules are
used or not. Modules simply divide the program.

Q. 21. Which of the following is false about “import modulename” form of import?

A. The namespace of imported module becomes part of importing module


B. This form of import prevents name clash
C. The namespace of imported module becomes available to importing module
D. The identifiers in module are accessed as: modulename.identifier

Ans: A.
Explanation: In the “import modulename” form of import, the namespace of imported module
becomes available to, but not part of, the importing module.

Q. 22. What will be the output of the following Python code?

from math import factorial


print(math.factorial(5))

A. 120
B. Nothing is printed
C. Error, method factorial doesn’t exist in math module
D. Error, the statement should be: print(factorial(5))

Ans: D
Explanation: In the “from-import” form of import, the imported identifiers (in this case
factorial()) aren’t specified along with the module name.

Q.23. What will be the output of the following Python code?

x=10
y=8
assert x>y, 'X too small'
A. Assertion Error
B. 10 8
C. No output
D. X too small

Ans: C.
Explanation: The code shown above results in an error if and only if x<y. However, in the above
case, since x>y, there is no error. Since there is no print statement, hence there is no output.

Q.24 Which of the following best describes polymorphism?


A. Ability of a class to derive members of another class as a part of its own definition
B. Means of bundling instance variables and methods in order to restrict access to certain class
members
C. Focuses on variables and passing of variables to functions
D. Allows for objects of different types and behaviour to be treated as the same general type

Ans: D
Explanation: Polymorphism is a feature of object-oriented programming languages. It allows for
the implementation of elegant software that is well designed and easily modified.

Q.25 Overriding means changing behaviour of methods of derived class methods in the base class.

A. True
B. False

Ans: B.
Explanation: Overriding means if there are two same methods present in the superclass and the
subclass, the contents of the subclass method are executed.

Q.26. What will be the output of the following Python code?

class A:
def __init__(self):
self.multiply(15)
def multiply(self, i):
self.i = 4 * i;
class B(A):
def __init__(self):
super().__init__()
print(self.i)

def multiply(self, i):


self.i = 2 * i;
obj = B()

A. 15
B. 30
C. An exception is thrown
D. 60

Ans: B.
Explanation: The derived class B overrides base class A.

Q.27 What will be the output of the following Python code?


class A:
def one(self):
return self.two()
def two(self):
return 'A'
class B(A):
def two(self):
return 'B'
obj2=B()
print(obj2.two())
A. A
B. An exception is thrown
C. A B
D. B

Ans: D.
Explanation: The derived class method two() overrides the method two() in the base class A.

Q.28 Which of the following statements is true?

A. A non-private method in a superclass can be overridden


B. A subclass method can be overridden by the superclass
C. A private method in a superclass can be overridden
D. Overriding isn’t possible in Python

Ans: A
Explanation: A public method in the base class can be overridden by the same named method in
the subclass.

Q.29 Which of the following is the most suitable definition for encapsulation?
A. Ability of a class to derive members of another class as a part of its own definition
B. Means of bundling instance variables and methods in order to restrict access to certain class
members
C. Focuses on variables and passing of variables to functions
D. Allows for implementation of elegant software that is well designed and easily modified

Ans: B
Explanation: The values assigned by the constructor to the class members is used to create the
object.

Q.30 What type of inheritance is illustrated in the following Python code?


class A():
pass
class B(A):
pass
class C(B):
pass
A. Multi-level inheritance
B. Multiple inheritance
C. Hierarchical inheritance
D. Single-level inheritance

Ans: A
Explanation: In multi-level inheritance, a subclass derives from another class which itself is
derived from another class.

KNC 402 – Python Programming


Unit 5
MCQ

Topics:
✓ Iterators & Recursion: Recursive Fibonacci, Tower of Hanoi
✓ Search: Simple Search and Estimating Search Time, Binary Search and Estimating
Binary Search Time
✓ Sorting & Merging: Selection Sort, Merge List, Merge Sort, Higher Order Sort

1) The worst-case occur in linear search algorithm when …….


A. Item is somewhere in the middle of the array
B. Item is not in the array at all
C. Item is the last element in the array
D. Item is the last element in the array or item is not there at all
ANS- D. Item is the last element in the array

2) If the number of records to be sorted is small, then …… sorting can be efficient.


A. Merge
B. Heap
C. Selection
D. Bubble
ANS- C. Selection

3) The complexity of the sorting algorithm measures the …… as a function of the number n of items
to be sorter.
A. average time
B. running time
C. average-case complexity
D. case-complexity
ANS- B. running time

4) Which of the following is not a limitation of binary search algorithm?


A. must use a sorted array
B. requirement of sorted array is expensive when a lot of insertion and deletions are needed
C. there must be a mechanism to access middle element directly
D. binary search algorithm is not efficient when the data elements more than 1500.
ANS-D. binary search algorithm is not efficient ..

5) The Average case occurs in the linear search algorithm ……….


A. when the item is somewhere in the middle of the array
B. when the item is not the array at all
C. when the item is the last element in the array
D. Item is the last element in the array or item is not there at all
ANS-A. when the item is somewhere in the middle ..

6) Binary search algorithm cannot be applied to …


A. sorted linked list
B. sorted binary trees
C. sorted linear array
D. pointer array
ANS-A. sorted linked list

7) Complexity of linear search algorithm is ………


A. O(n)
B. O(logn)
C. O(n2)
D. O(n logn)
ANS- A. O(n)
8) Sorting algorithm can be characterized as ……
A. Simple algorithm which require the order of n2 comparisons to sort n items.
B. Sophisticated algorithms that require the O(nlog2n) comparisons to sort items.
C. Both of the above
D. None of the above
ANS- C. Both of the above

9) The complexity of bubble sort algorithm is …..


A. O(n)
B. O(logn)
C. O(n2)
D. O(n logn)
ANS- C. O(n2)

10) State True or False for internal sorting algorithms.


i) Internal sorting are applied when the entire collection if data to be sorted is small enough that the
sorting can take place within main memory.
ii) The time required to read or write is considered to be significant in evaluating the performance of
internal sorting.
A. i-True, ii-True
B. i-True, ii-False
C. i-False, ii-True
D. i-False, ii-False
ANS- B. i-True, ii-False

11) The complexity of merge sort algorithm is ……


A. O(n)
B. O(logn)
C. O(n2)
D. O(n logn)
ANS- D. O(n logn)

12) ………. is putting an element in the appropriate place in a sorted list yields a larger sorted order
list.
A. Insertion
B. Extraction
C. Selection
D. Distribution
ANS- A. Insertion

13) …………order is the best possible for array sorting algorithm which sorts n item.
A. O(n logn)
B. O(n2)
C. O(n+logn)
D. O(logn)
ANS- C. O(n+logn)

14) ……… is rearranging pairs of elements which are out of order, until no such pairs remain.
A. Insertion
B. Exchange
C. Selection
D. Distribution
ANS- B. Exchange

15) ………… is the method used by card sorter.


A. Radix sort
B. Insertion
C. Heap
D. Quick
ANS- A. Radix sort

16) Which of the following sorting algorithm is of divide and conquer type?
A. Bubble sort
B. Insertion sort
C. Merge sort
D. Selection sort
ANS- C. Merge sort

17) …….. sorting algorithm is frequently used when n is small where n is total number of elements.
A. Heap
B. Insertion
C. Bubble
D. Quick
ANS- B. Insertion

18) Which of the following sorting algorithm is of priority queue sorting type?
A. Bubble sort
B. Insertion sort
C. Merge sort
D. Selection sort
ANS- D. Selection sort

19) Which of the following is not the required condition for a binary search algorithm?
A. The list must be sorted
B. There should be direct access to the middle element in any sublist
C. There must be a mechanism to delete and/or insert elements in the list.
D. Number values should only be present
ANS- C. There must be a mechanism to delete and/or insert elements in the list.
20) Partition and exchange sort is ……..
A. quick sort
B. tree sort
C. heap sort
D. bubble sort
ANS- A. quick sort

21) Which is the most appropriate definition for recursion?


a) A function that calls itself
b) A function execution instance that calls another execution instance of the same function
c) A class method that calls another class method
d) An in-built method that is automatically called
ANS- b
Explanation: The appropriate definition for a recursive function is a function execution instance that
calls another execution instance of the same function either directly or indirectly.

22)Which of these is false about recursion?


a) Recursive function can be replaced by a non-recursive function
b) Recursive functions usually take more memory space than non-recursive function
c) Recursive functions run faster than non-recursive function
d) Recursion makes programs easier to understand
ANS-c
Explanation: The speed of a program using recursion is slower than the speed of its non-recursive
equivalent.

23) Fill in the line of the following Python code for calculating the factorial of a number.

a) num*fact(num-1)
b) (num-1)*(num-2)
c) num*(num-1)
d) fact(num)*fact(num-1)
ANS- a
Explanation: Suppose n=5 then, 5*4*3*2*1 is returned which is the factorial of 5.

24)What is tail recursion?


a) A recursive function that has two base cases
b) A function where the recursive functions leads to an infinite loop
c) A recursive function where the function doesn’t return anything and just prints the values
d) A function where the recursive call is the last thing executed by the function
ANS- d
Explanation: A recursive function is tail recursive when recursive call is executed by the function in the
last.

25)Observe the following Python code?

a) Both a() and b() aren’t tail recursive


b) Both a() and b() are tail recursive
c) b() is tail recursive but a() isn’t
d) a() is tail recursive but b() isn’t
ANS-c
Explanation: A recursive function is tail recursive when recursive call is executed by the function in the
last.
26) What is the output of the following piece of code?

a. 50
b. 100
c. 74
d. Infinite loop
ANS-b. 100

27) Which of these is not true about recursion?


a) It’s easier to code some real-world problems using recursion than non-recursive equivalent
b) Recursive functions are easy to debug
c) Recursive calls take up a lot of memory
d) Programs using recursion take longer time than their non-recursive equivalent

ANS- b
Explanation: Recursive functions may be hard to debug as the logic behind recursion may be hard to
follow.

28) Only problems that are recursively defined can be solved using recursion.
a) True
b) False

ANS- b
Explanation: There are many other problems can also be solved using recursion.

29) What will be the output of the following Python code?

a) 13
b) 7
c) Infinite loop
d) 17
ANS- d
Explanation: The test(i-1,i+j) part of the function keeps calling the function until the base condition of
the function is satisfied.

30) What happens if the base condition isn’t defined in recursive programs?
a) Program gets into an infinite loop
b) Program runs once
c) Program runs n number of times where n is the argument given to the function
d) An exception is thrown
ANS-a
Explanation: The program will run until the system gets out of memory.
7/16/2021 MCQ-03 [KNC-402 (PYTHON PROGRAMMING LANGUAGE)] 2020-21

MCQ-03 [KNC-402 (PYTHON PROGRAMMING


LANGUAGE)] 2020-21
M.M:- 30

Time:- 30 min

Instructions:

* More than one answers may be correct.


* Required

1. Email *

2. Name *

3. Roll Number *

https://docs.google.com/forms/d/10CHSdg6zjkuqBBpChwFEVoDN2dMf5taUJxRjHzzdCIo/edit 1/12
7/16/2021 MCQ-03 [KNC-402 (PYTHON PROGRAMMING LANGUAGE)] 2020-21

4. Branch *

Mark only one oval.

CSE-II

IT-II

ME-II

CE-II

AG-II

BT-II

EC-II

EE-II

5. What is the data type of m after the following statement? m = (41, 54, 23, 68)

Mark only one oval.

Dictionary

Tuple

String

List

6. What is the data type of m after the following statement? m = ['July', 'September', 'December']

Mark only one oval.

Dictionary

Tuple

List

String

https://docs.google.com/forms/d/10CHSdg6zjkuqBBpChwFEVoDN2dMf5taUJxRjHzzdCIo/edit 2/12
7/16/2021 MCQ-03 [KNC-402 (PYTHON PROGRAMMING LANGUAGE)] 2020-21

7. What will be the output after the following statements? m = ['July', 'September', 'December'] n =m[1]
print(n)

Mark only one oval.

[‘July’, ‘September’,‘December’]

July

September

December

8. What will be the output after the following statements? m = [45, 51, 67] n = m[2] print(n)

Mark only one oval.

67

51

[45, 51, 67]

45

9. What will be the output after the following statements? m = [75, 23, 64] n = m[0] + m[1] print(n)

Mark only one oval.

75

23

64

98

https://docs.google.com/forms/d/10CHSdg6zjkuqBBpChwFEVoDN2dMf5taUJxRjHzzdCIo/edit 3/12
7/16/2021 MCQ-03 [KNC-402 (PYTHON PROGRAMMING LANGUAGE)] 2020-21

10. What will be the output after the following statements? m = ['July', 'September', 'December'] n = m[0]
+ m[2] print(n)

Mark only one oval.

July

JulyDecember

JulySeptember

SeptemberDecember

11. What will be the output after the following statements? m = [25, 34, 70, 63] n = m[2] - m[0] print(n)

Mark only one oval.

25

45

70

34

12. What will be the output after the following statements? m = [25, 34, 70, 63] n = str(m[1]) +str(m[2])
print(n)

Mark only one oval.

2534

95

104

3470

https://docs.google.com/forms/d/10CHSdg6zjkuqBBpChwFEVoDN2dMf5taUJxRjHzzdCIo/edit 4/12
7/16/2021 MCQ-03 [KNC-402 (PYTHON PROGRAMMING LANGUAGE)] 2020-21

13. What will be the data type of m after the following statement? m = [90, 'A', 115, 'B', 250]

Mark only one oval.

List

String

Dictionary

Tuple

14. What will be the data type of m after the following statement? m = 'World Wide Web'

Mark only one oval.

List

String

Dictionary

Tuple

15. What will be the data type of m after the following statement? m = {'Listen' :'Music', 'Play' : 'Games'}

Mark only one oval.

List

Set

Dictionary

Tuple

https://docs.google.com/forms/d/10CHSdg6zjkuqBBpChwFEVoDN2dMf5taUJxRjHzzdCIo/edit 5/12
7/16/2021 MCQ-03 [KNC-402 (PYTHON PROGRAMMING LANGUAGE)] 2020-21

16. What will be the data type of m after the following statement? m = {'A', 'F', 'R', 'Y'}

Mark only one oval.

List

Set

Dictionary

Tuple

17. What will be the output after the following statements? m = {'Listen' :'Music', 'Play' : 'Games'}
print(m.keys())

Mark only one oval.

dict_keys([‘Listen’,‘Play’])

dict_keys([‘Music’,‘Games’])

dict_keys({‘Listen’ :‘Music’, ‘Play’ :‘Games’})

dict_keys({‘Listen’ :‘Games’})

18. What will be the output after the following statements? m = {'Listen' :'Music', 'Play' : 'Games'}
print(m.values())

Mark only one oval.

dict_keys([‘Listen’,‘Play’])

dict_values([‘Music’,‘Games’])

dict_values({‘Listen’ :‘Music’, ‘Play’ :‘Games’})

dict_values({‘Listen’ :‘Games’})

https://docs.google.com/forms/d/10CHSdg6zjkuqBBpChwFEVoDN2dMf5taUJxRjHzzdCIo/edit 6/12
7/16/2021 MCQ-03 [KNC-402 (PYTHON PROGRAMMING LANGUAGE)] 2020-21

19. What will be the output after the following statements? m = {'Listen' :'Music', 'Play' : 'Games'} n =
m['Play'] print(n)

Mark only one oval.

Listen

Music

Play

Games

20. What will be the output after the following statements? m = {'Listen' :'Music', 'Play' : 'Games'} n =
list(m.values()) print(n[0])

Mark only one oval.

Listen

Music

Play

Games

21. What will be the output after the following statements? m = {'Listen' :'Music', 'Play' : 'Games'} n =
list(m.items()) print(n)

Mark only one oval.

[(‘Play’, ‘Games’), (‘Listen’,‘Music’)]

[(‘Listen’,‘Music’)]

[(‘Play’,‘Games’)]

(‘Play’, ‘Games’), (‘Listen’,‘Music’)

https://docs.google.com/forms/d/10CHSdg6zjkuqBBpChwFEVoDN2dMf5taUJxRjHzzdCIo/edit 7/12
7/16/2021 MCQ-03 [KNC-402 (PYTHON PROGRAMMING LANGUAGE)] 2020-21

22. What will be the output after the following statements? m = 36 if m > 19: print(100)

Mark only one oval.

36

19

100

23. What will be the output after the following statements? m = 50 if m > 50: print(25) else: print(75)

Mark only one oval.

50

75

25

24. What will be the output after the following statements? m = 8 if m > 7: print(50) elif m == 7:
print(60) else: print(70)

Mark only one oval.

50

60

70

https://docs.google.com/forms/d/10CHSdg6zjkuqBBpChwFEVoDN2dMf5taUJxRjHzzdCIo/edit 8/12
7/16/2021 MCQ-03 [KNC-402 (PYTHON PROGRAMMING LANGUAGE)] 2020-21

25. What will be the output after the following statements? m =85 n =17 print(m / n)

Mark only one oval.

5.5

6.0

5.0

26. What will be the output after the following statements? m =57 n =19 o = m == n print(o)

Mark only one oval.

19

True

False

57

27. What will be the output after the following statements? m = 33 if m > 33: print('A') elif m == 30:
print('B') else:print('C')

Mark only one oval.

33

https://docs.google.com/forms/d/10CHSdg6zjkuqBBpChwFEVoDN2dMf5taUJxRjHzzdCIo/edit 9/12
7/16/2021 MCQ-03 [KNC-402 (PYTHON PROGRAMMING LANGUAGE)] 2020-21

28. What will be the output after the following statements? m = 6 while m <11: print(m, end='') m = m +1

Mark only one oval.

6789

5678910

678910

56789

29. What will be the output after the following statements? m, n = 2, 5 while n < 10: print(n, end='') m, n =
n, m + n

Mark only one oval.

25

58

579

57

30. What will be the output after the following statements? m = {'m', 'n', 'o', 'p'} if 'n' in m: print('n', end='
')

Mark only one oval.

mnop

m n op

{'m', 'n', 'o', 'p'}

https://docs.google.com/forms/d/10CHSdg6zjkuqBBpChwFEVoDN2dMf5taUJxRjHzzdCIo/edit 10/12
7/16/2021 MCQ-03 [KNC-402 (PYTHON PROGRAMMING LANGUAGE)] 2020-21

31. What will be the output after the following statements? m = {45 : 75, 55 : 85} for n, o in m.items():
print(n, o, end=' ')

Mark only one oval.

45:75, 55:85

{45:75, 55:85}

45 55 75 85

45 75 5585

32. What will be the output after the following statements? for m in range(6,9): if m == 8: continue
print(m, end='')

Mark only one oval.

67

679

678

6789

33. What will be the output after the following statements? def p(m, n) : return m / n o = p(50, 5)
print(o)

Mark only one oval.

50 / 5

10.0

10

https://docs.google.com/forms/d/10CHSdg6zjkuqBBpChwFEVoDN2dMf5taUJxRjHzzdCIo/edit 11/12
7/16/2021 MCQ-03 [KNC-402 (PYTHON PROGRAMMING LANGUAGE)] 2020-21

34. What will be the output after the following statements? m = {'Listen' :'Music', 'Play' : 'Games'} n =
m['Music'] print(n)

Mark only one oval.

Music

KeyError

m['Music']

Listen

This content is neither created nor endorsed by Google.

 Forms

https://docs.google.com/forms/d/10CHSdg6zjkuqBBpChwFEVoDN2dMf5taUJxRjHzzdCIo/edit 12/12
→Telegram Channel 
→Telegram Group
Multiple Choice Questions(MCQ’s)

Subject: Python Programming

Subject Code: KNC402

1|P a g e
PYTHON PROGRAMING (KNC – 402)

UNIT 1

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Python was developed by


A. Guido van Rossum
B. James Gosling
C. Dennis Ritchie
D. Bjarne Stroustrup

2. Python was developed in which year?


A. 1972
B. 1995
C. 1989
D. 1981

3. Python is written in which language?


A. C
B. C++
C. Java
D. None of the above

4. What is the extension of python file?


A. .p
B. .py
C. .python
D. None of the above

5. Python is Object Oriented Programming Language.


A. True
B. False
C. Neither true nor false
D. None of the above

6. Python 3.0 is released in which year?


A. 2000
B. 2008
C. 2011
D. 2016

7. Which of the following statements is true?


A. Python is a high level programming language.
B. Python is an interpreted language.
C. Python is an object-oriented language
D. All of the above

2|P a g e
8. What is used to define a block of code in Python?
A. Parenthesis
B. Indentation
C. Curly braces
D. None of the above

9. By the use of which character, single line is made comment in Python?


A. *
B. @
C. #
D. !

10. What is a python file with .py extension called?


A. package
B. module
C. directory
D. None of the above

11. Which of the following statements are correct?


(i) Python is a high level programming language.
(ii) Python is an interpreted language.
(iii) Python is a compiled language.
(iv) Python program is compiled before it is interpreted.
A. i, ii
B. i, iv
C. ii, iii
D. ii, iv

12. Which of the following is incorrect variable name in Python?


A. variable_1
B. variable1
C. 1variable
D. _variable

13. Is Python case sensitive when dealing with identifiers?


a) yes
b) no
c) machine dependent
d) none of the mentioned

14. What is the maximum possible length of an identifier?


a) 31 characters
b) 63 characters
c) 79 characters
d) none of the mentioned

15. Which of the following is invalid?


a) _a = 1
b) __a = 1
c) __str__ = 1
d) none of the mentioned

3|P a g e
16. Which of the following is an invalid variable?
a) my_string_1
b) 1st_string
c) foo
d) _

17. Why are local variable names beginning with an underscore discouraged?
a) they are used to indicate a private variables of a class
b) they confuse the interpreter
c) they are used to indicate global variables
d) they slow down execution

18. Which of the following is not a keyword?


a) eval
b) assert
c) nonlocal
d) pass

19. All keywords in Python are in _________


a) lower case
b) UPPER CASE
c) Capitalized
d) None of the mentioned

20. Which of the following is true for variable names in Python?


a) unlimited length
b) all private members must have leading and trailing underscores
c) underscore and ampersand are the only two special characters allowed
d) none of the mentioned

21. Which of the following is an invalid statement?


a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000

22. Which of the following cannot be a variable?


a) __init__
b) in
c) it
d) on

23. Which of these in not a core data type?


a) Lists
b) Dictionary
c) Tuples
d) Class

24. Given a function that does not return any value, What value is thrown by default when
executed in shell.
a) int
b) bool
c) void

4|P a g e
d) None

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

>>>str="hello"
>>>str[:2]

a) he
b) lo
c) olleh
d) hello

26. Which of the following will run without errors?


a) round(45.8)
b) round(6352.898,2,5)
c) round()
d) round(7463.123,2,1)

27. What is the return type of function id?


a) int
b) float
c) bool
d) dict

28. In python we do not specify types, it is directly interpreted by the compiler, so consider the
following operation to be performed.

>>>x = 13 ? 2

objective is to make sure x has a integer value, select all that apply (python 3.xx)
a) x = 13 // 2
b) x = int(13 / 2)
c) x = 13 % 2
d) All of the mentioned

29. What error occurs when you execute the following Python code snippet?
apple = mango
a) SyntaxError
b) NameError
c) ValueError
d) TypeError

30. What will be the output of the following Python code snippet?

def example(a):
a = a + '2'
a = a*2
return a

>>>example("hello")

a) indentation Error

5|P a g e
b) cannot perform mathematical operation on strings
c) hello2
d) hello2hello2

31. What data type is the object below?


L = [1, 23, 'hello', 1]
a) list
b) dictionary
c) array
d) tuple

32. In order to store values in terms of key and value we use what core data type.
a) list
b) tuple
c) class
d) dictionary

33. Which of the following results in a SyntaxError?


a) ‘”Once upon a time…”, she said.’
b) “He said, ‘Yes!'”
c) ‘3\’
d) ”’That’s okay”’

34. The following is displayed by a print function call. Select all of the function calls that result
in this output.
1. tom
2. dick
3. harry

a) print('''tom
\ndick
\nharry''')
b) print(”’tomdickharry”’)
c) print(‘tom\ndick\nharry’)
d) print('tom
dick
harry')

35. What is the average value of the following Python code snippet?

>>>grade1 = 80
>>>grade2 = 90
>>>average = (grade1 + grade2) / 2

a) 85.0
b) 85.1
c) 95.0
d) 95.1

36. Select all options that print.


hello-how-are-you

a) print(‘hello’, ‘how’, ‘are’, ‘you’)

6|P a g e
b) print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4)
c) print(‘hello-‘ + ‘how-are-you’)
d) print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ + ‘you’)

37. What is the return value of trunc()?


a) int
b) bool
c) float
d) None

38. How we can convert the given list into the set ?
a) list.set()
b) set.list()
c) set(list)
d) None of the above

39. If we change one data type to another, then it is called


a) Type conversion
b) Type casting
c) Both of the above
d) None of the above

40. What is list data type in Python ?


a) collection of integer number
b) collection of string
c) collection of same data type
d) collection of different data type

41. What is type casting in python ?


a) declaration of data type
b) destroy data type
c) Change data type property
d) None of the above

42. Which of the following can convert the string to float number ?
a) str(float,x)
b) float(str,int)
c) int(float(str))
d) float(str)

43. Which of the following function are used to convert the string into the list ?
a) map()
b) convertor()
c) split()
d) lambda

44. Which of the following is not the data type in python ?


a) List
b) Tuple
c) Set
d) Class

45. Which of the following is the data type possible in python?

7|P a g e
a) int
b) list
c) dictionary
d) All of the above

46. Which of the following is the example of the type casting ?


a) int(2)
b) str(2)
c) str(list)
d) All of the above

ANSWERS
1.a 2.c 3.a 4.b 5.a 6.b 7.d 8.b 9.c 10.b 11.b 12.c 13.a 14.d 15.d
16.b 17.a (As Python has no concept of private variables, leading underscores are used to indicate
variables that must not be accessed from outside the class.) 18.a (eval can be used as a variable)
19.d 20.a 21b 22.b 23.d 24.d 25.a 26.a 27.a 28.d
29.b 30.a 31.a 32.d 33.c 34.c 35.a 36.c 37.a 38.c
39.c 40.d 41.c 42.d 43.c 44.d 45.d 46.d

MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which is the correct operator for power(xy)?


a) X^y
b) X**y
c) X^^y
d) None of the mentioned

2. Which one of these is floor division?


a) /
b) //
c) %
d) None of the mentioned

3. What is the order of precedence in python?


i) Parentheses
ii) Exponential
iii) Multiplication
iv) Division
v) Addition
vi) Subtraction
a) i,ii,iii,iv,v,vi
b) ii,i,iii,iv,v,vi
c) ii,i,iv,iii,v,vi
d) i,ii,iii,iv,vi,v

4. What is the answer to this expression, 22 % 3 is?


a) 7
b) 1
c) 0
d) 5

8|P a g e
5. Mathematical operations can be performed on a string.
a) True
b) False

6. Operators with the same precedence are evaluated in which manner?


a) Left to Right
b) Right to Left
c) Can’t say
d) None of the mentioned

7. What is the output of this expression, 3*1**3?


a) 27
b) 9
c) 3
d) 1

8. Which one of the following has the same precedence level?


a) Addition and Subtraction
b) Multiplication, Division and Addition
c) Multiplication, Division, Addition and Subtraction
d) Addition and Multiplication

9. The expression Int(x) implies that the variable x is converted to integer.


a) True
b) False

10. Which one of the following has the highest precedence in the expression?
a) Exponential
b) Addition
c) Multiplication
d) Parentheses

11. What is the output of print 0.1 + 0.2 == 0.3?


a) True
b) False
c) Machine dependent
d) Error

12. Which of the following is not a complex number?


a) k = 2 + 3j
b) k = complex(2, 3)
c) k = 2 + 3l
d) k = 2 + 3J

13. What is the type of inf?


a) Boolean
b) Integer
c) Float
d) Complex
14. What does ~4 evaluate to?
a) -5
b) -4
c) -3
d) +3

9|P a g e
15. What does ~~~~~~5 evaluate to?
a) +5
b) -11
c) +11
d) -5

16. Which of the following is incorrect?


a) x = 0b101
b) x = 0x4f5
c) x = 19023
d) x = 03964

17. What is the result of cmp(3, 1)?


a) 1
b) 0
c) True
d) False

18. Which of the following is incorrect?


a) float(‘inf’)
b) float(‘nan’)
c) float(’56’+’78’)
d) float(’12+34′)

19. What is the result of round(0.5) – round(-0.5)?


a) 1.0
b) 2.0
c) 0.0
d) Value depends on Python version

20. What does 3 ^ 4 evaluate to?


a) 81
b) 12
c) 0.75
d) 7

21. What will be the output of the following Python code snippet if x=1?
x<<2
a) 8
b) 1
c) 2
d) 4

22. What will be the output of the following Python expression?


bin(29)
a) ‘0b10111’
b) ‘0b11101’
c) ‘0b11111’
d) ‘0b11011’

23. What will be the value of x in the following Python expression, if the result of

10 | P a g e
that expression is 2?
x>>2
a) 8
b) 4
c) 2
d) 1

24. What will be the output of the following Python expression if x=15 and y=12?
x&y
a) b1101
b) 0b1101
c) 12
d) 1101

25. Which of the following represents the bitwise XOR operator?


a) &
b) ^
c) |
d) !

26. Bitwise _________ gives 1 if either of the bits is 1 and 0 when both of the bits are
1.
a) OR
b) AND
c) XOR
d) NOT

27. What will be the output of the following Python expression?


4^12
a) 2
b) 4
c) 8
d) 12

28. What will be the output of the following Python code if a=10 and b =20?
a=10
b=20
a=a^b
b=a^b
a=a^bprint(a,b)
a) 10 20
b) 10 10
c) 20 10
d) 20 20

29. What will be the output of the following Python expression?

11 | P a g e
~100?
a) 101
b) -101
c) 100
d) -100

30. The value of the expressions 4/(3*(2-1)) and 4/3*(2-1) is the same.
a) True
b) False

31. What will be the value of the following Python expression?


4+3%5
a) 4
b) 7
c) 2
d) 0

32. Evaluate the expression given below if A = 16 and B = 15.


A % B // A
a) 0.0
b) 0
c) 1.0
d) 1

33. Which of the following operators has its associativity from right to left?
a) +
b) //
c) %
d) **

34. What will be the value of x in the following Python expression?


x = int(43.55+2/2)
a) 43
b) 44
c) 22
d) 23

35. What is the value of the following expression?


2+4.00, 2**4.0
a) (6.0, 16.0)
b) (6.00, 16.00)
c) (6, 16)
d) (6.00, 16.0)

36. Which of the following is the truncation division operator?


a) /

12 | P a g e
b) %
c) //
d) |

37. What are the values of the following Python expressions?


2**(3**2)
(2**3)**2
2**3**2
a) 64, 512, 64
b) 64, 64, 64
c) 512, 512, 512
d) 512, 64, 512

38. What is the value of the following expression?


8/4/2, 8/(4/2)
a) (1.0, 4.0)
b) (1.0, 1.0)
c) (4.0. 1.0)
d) (4.0, 4.0)

39. What is the value of the following expression?


float(22//3+3/3)
a) 8
b) 8.0
c) 8.3
d) 8.33

40. What will be the output of the following Python expression?


print(4.00/(2.0+2.0))
a) Error
b) 1.0
c) 1.00
d) 1

41. What will be the value of X in the following Python expression?


X = 2+9*((3*12)-8)/10
a) 30.0
b) 30.8
c) 28.4
d) 27.2

42. Which of the following expressions involves coercion when evaluated in Python?
a) 4.7 – 1.5
b) 7.9 * 6.3
c) 1.7 % 2
d) 3.4 + 4.6

13 | P a g e
43. What will be the output of the following Python expression?
24//6%3, 24//4//2
a) (1,3)
b) (0,3)
c) (1,0)
d) (3,1)

44. Which among the following list of operators has the highest precedence?
+, -, **, %, /, <<, >>, |
a) <<, >>
b) **
c) |
d) %

45. What will be the value of the following Python expression?


float(4+int(2.39)%2)
a) 5.0
b) 5
c) 4.0
d) 4

46. Which of the following expressions is an example of type conversion?


a) 4.0 + float(3)
b) 5.3 + 6.3
c) 5.0 + 3
d) 3 + 7

47. Which of the following expressions results in an error?


a) float(‘10’)
b) int(‘10’)
c) float(’10.8’)
d) int(’10.8’)

48. What will be the value of the following Python expression?


4+2**5//10
a) 3
b) 7
c) 77
d) 0

49. The expression 2**2**3 is evaluates as: (2**2)**3.


a) True
b) False

14 | P a g e
ANSWERS:
1.b 2.b 3.a 4.b 5.b 6.a 7.c 8.a 9.a 10.d 11.b 12.c
13.c 14.a 15.a 16.d 17.a 18.d 19.d 20.d 21.d 22.b
23.a 24.c 25.b 26.c 27.c 28.c 29.b 30.a 31.b 32.b
33.d 34.b 35.a 36.c 37.d 38.a 39.b 40.b 41.d 42.c
43.a 44.b 45.c 46.a 47.d 48.b 49.b

15 | P a g e
UNIT II

1. In Python, a decision can be made by using if else statement.


a. True b. False

2. Checking multiple conditions in Python requires elif statements.


a. True b. False

3. If the condition is evaluated to true, the statement(s) of if block will be


executed, otherwise the statement(s) in else block(if else is specified) will be
executed.
a. True b. False

4. What kind of statement is IF statement?


a. Concurrent b. Sequential
c. Assignment d. Selected assignment

5. Which one of the following is a valid Python if statement :

a. if (a => 22) b. if(a>=2)


c. if a>=2 : d. if a >= 22
6. What keyword would you use to add an alternative condition to an if
statement?
a. Else if b. Elseif
c. Elif d. None of the above

7. Can we write if/else into one line in python?

a. Yes
b. No
c. if/else not used in python
d. None of the above

8. In a Python program, a control structure:

a. Defines program-specific data structures


b. Directs the order of execution of the statements in the program
c. Dictates what happens before the program starts and after it terminates
d. None of the above
9. What will be output of this expression:
‘p’ + ‘q’ if ‘12’.isdigit() else ‘r’ + ‘s’

16 | P a g e
a. pq
b. rs
c. pqrs
d. pq12

10. Which statement will check if a is equal to b?

a. if a = b:
b. if a == b:
c. if a === c:
d. if a == b
11. What will be the output of given Python code?
str1="hello"
c=0
for x in str1:
if(x!="l"):
c=c+1
else:
pass print(c)
a. 2
b. 0
c. 4
d. 3
12. What does the following code print to the console?
if 5 > 10:
print("fan")
elif 8 != 9:
print("glass")
else:
print("cream")
a. Cream
B. Glass
c. Fan
d. No output

13. What does the following code print to the console?


name = "maria"
if name == "melissa":
print("usa")
elif name == "mary":
print("ireland")
else:
print("colombia")

17 | P a g e
a. usa b. ireland
c.colombia d. None of the above

14. What does the following code print to the console?


if "cat" == "dog":
print("prrrr")
else:
print("ruff")
a. ruff b. ruf
c. prrrr d. prr

15. What does the following code print to the console?


hair_color = "blue"
if 3 > 2:
if hair_color == "black":
print("You rock!")
else:
print("Boring")
a. blue b. black
c. You rock! d. Boring
16. What does the following code print to the console?
if True:
print(101)
else:
print(202)
a. true b. false
c. 101 d. 202

17. What does the following code print to the console?


if False:
print("Nissan")
elif True:
print("Ford")
elif True:
print("BMW")
else:

18 | P a g e
print("Audi")
a. Nissan b. Ford
c. BMW d. Audi

18. What does the following code print to the console?


if 1:
print("1 is truthy!")
else:
print("???")
a. 1 is truthy! b. ???
c. Invalid d. None of the above

19. What does the following code print to the console?


if 0:
print("huh?")
else:
print("0 is falsy!")
a. o b. Huh
c. 0 is falsy! d. None of the above

20. What does the following code print to the console?


if 88 > 100:
print("cardio")
a. 88 b. 100
b. cardio d. Nothing is printed..

1.a 2.a 3.a 4.b 5.c 6.c 7.a (Yes, we can write if/else in one
line. For eg i = 5 if a > 7 else 0. So, option A is correct.) 8.b 9.a ( If condition
is true so pq will be the output. So, option A is correct.) 10.b 11.d 12.b
13.c 14.a 15.d 16.c 17.b (The first elif that is True will be
executed when multiple elif statements are True.) 18.a (1 does not equal True, but it's
considered True in a boolean context. Values that are considered True in a boolean
context are called "truthy" and values that are considered False in a boolean context are
called "falsy".) 19. c 20. D

19 | P a g e
1.Which of the following is the loop in python ?

A. For
B. while
C. do while
D.1 and 2

2. for loop in python are work on


A. range
B. iteration
C. Both of the above
D. None of the above

3. For loop in python is


A. Entry control loop
B. Exit control loop
C. Simple loop
D. None of the above

4. for i in range(-3), how many times this loop will run ?


A. 0
B. 1
C. Infinite
D. Error

5. for i in [1,2,3]:, how many times a loop run ?


A. 0
B. 1
C. 2
D. 3
6. How many times it will print the statement ?, for i in range(100): print(i)
A. 101
B. 99
C. 100
D. 0

7. What is the final value of the i after this, for i in range(3): pass
A. 1
B. 2
C. 3
D. 0

8. What is the value of i after the for loop ?, for i in range(4):break


A. 1
B. 2
C. 3
D. 0

9. What is the output of the following?


x = 'abcd'
for i in x:
print(i.upper())

20 | P a g e
A. a b c d
B. A B C D
C. a B C D
D. error

10. What is the output of the following?


x = 'abcd'
for i in range(len(x)):
x[i].upper()
print (x)
A. abcd
B. ABCD
C. error
D. none of the mentioned

11. What is the output of the following?


d = {0: 'a', 1: 'b', 2: 'c'}
for x in d.values():
print(x)
A. 0 1 2
B. a b c
C. 0 a 1 b 2 c
D. none of the mentioned

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


x = ['ab', 'cd']for i in x: x.append(i.upper())print(x)
A. [‘AB’,’CD’]
B. [‘ab’,’cd’,’AB’,’CD’]
C. [‘ab’,’cd’]
D. None of the mentioned

13. What will be the output of the following Python code snippet?
x = 'abcd'
for i in range(len(x)):
x = 'a'
print(x)
A. a
B. abcd abcd abcd
C. a a a a
D. None of the mentioned

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


x = 'abcd'
for i in range(len(x)):
print(x)
x = 'a'
A. a
B. abcd abcd abcd abcd
C. a a a a
D. None of the mentioned

21 | P a g e
15. What will be the output of the following Python code?
x = 123
for i in x:
print(i)
A. 1 2 3
B. 123
C. error
D. None of the mentioned

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


for i in range(2.0):
print(i)
A. 0.0 1.0
B. 0 1
C. error
D. None of the mentioned

17. What will be the output of the following Python code snippet?
for i in [1, 2, 3, 4][::-1]:
print (i)

A. 1234
B. 4321
C. error
D. none of the mentioned

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


for i in range(int(2.0)):
print(i)

A. 0.0 1.0
B. 0 1
C. error
D. none of the mentioned

19. What will be the output of the following Python code snippet?
x=2
for i in range(x):
x += 1
print (x)

A. 01234
B. 01
C. 3 4
D. 0 1 2 3

20. What will be the output of the following Python code snippet?
x=2
for i in range(x):
x -= 2

22 | P a g e
print (x)

A. 01234
B. 0 -2
C. 30
D. Error

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


for i in range(10):
if i == 5:
break
else:
print(i)
else:
print("Here")

A. 0 1 2 3 4 Here
B. 0 1 2 3 4 5 Here
C. 0 1 2 3 4
D. 0 1 2 3 4 5

ANSWERS :
1. D 2. C 3. A 4. A 5. D 6. C 7. B 8. D 9. B 10.
A 11. B 12.D ( The loop does not terminate as new elements are being added to the list in
each iteration.) 13.C ( range() is computed only at the time of entering the loop.) 14.D
15.C (Objects of type int are not iterable.) 16. C ( Object of type float cannot be
interpreted as an integer.) 17.B 18.B 19.C 20.B 21.C

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. In which of the following loop in python, we can check the condition ?


A. for loop
B. while loop
C. do while loop
D. None of the above

2. It is possible to create a loop using goto statement in python ?


A. Yes
B. No
C. Sometimes
D. None of the above

3. To break the infinite loop , which keyword we use ?


A. continue
B. break
C. exit
D. None of the above

4. While(0), how many times a loop run ?


A. 0

23 | P a g e
B. 1
C. 3
D. infinite

5. while(1==3):, how many times a loop run ?


A. 0
B. 1
C. 3
D. infinite

6. What is the output of the following?


i=2
while True:
if i%3 == 0:
break
print(i)
i += 2
A. 2 4 6 8 10 …
B. 2 4
C. 2 3
D. error

7. What is the output of the following?


x = "abcdef"
i = "i"
while i in x:
print(i, end=" ")

A. no output
B. i i i i i i …
C. a b c d e f
D. abcdef

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


i=1
while True:
if i%0O7 == 0:
break
print(i)
i += 1

A. 123456
B. 1234567
C. error
D. none of the mentioned

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


True = False
while True:
print(True)
break

A. True

24 | P a g e
B. False
C. None
D. none of the mentioned

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


i=0
while i < 5:
print(i)
i += 1
if i == 3:
Break
else:
print(0)

A. 0120
B. 012
C. None
D. none of the mentioned

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


x = "abcdef"
while i in x:
print(i, end=" ")

A. a b c d e f
B. Abcdef
C. i i i i i i...
D. Error

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


x = "abcdef" i = "a"
while i in x:
x = x[:-1]
print(i, end = " ")

A. a a a a a a
B. a a a a
C. i i i i i i
D. None of the mentioned

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


i=1
while True: if i%3 == 0: break print(i) i+=1

A. 1 2
B. 1 2 3
C. Error
D. None of the mentioned

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

25 | P a g e
i=1
while True: if i%O.7 == 0: break print(i) i += 1

A. 1 2 3 4 5 6
B. 1 2 3 4 5 6 7
C. Error
D. None of the mentioned

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


i = 5while True: if i%O.11 == 0: break print(i) i += 1

A. 5 6 7 8 9 10
B. 5 6 7 8
C. 5 6
D. Error

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


i=5
while True: if i%O.9 == 0: break print(i) i += 1
A. 5 6 7 8
B. 5 6 7 8 9
C. 5 6 7 8 9 10 11 12 13 14 15....
D. Error

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


i=1
while True: if i%2 == 0: break print(i) i += 2

A. 1
B. 1 2
C. 1 2 3 4 5 6 ....
D. 1 3 5 7 9 11 ....

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


i=2
while True:
if i%3 == 0:
break
print(i)
i += 2

A. 2 4 6 8 10 ....
B. 2 4
C. 2 3
D. Error

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


i = 1while False:
if i%2 == 0:
break
print(i)
i += 2

26 | P a g e
A. 1
B. 1 3 5 7 ...
C. 1 2 3 4 ....
D. none of the mentioned

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


True = False
while True:
print(True)
Break

A. true
B. false
C. error
D. none of the mentioned

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


i=0
while i < 5:
print(i)
i += 1
if i == 3:
Break
else:
print(0)

A. 0 1 2 0
B. 0 1 2
C. error
D. none of the mentioned

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


i=0
while i < 3:
print(i)
i += 1
else:
print(0)

A. 0 1 2 3 0
B. 0 1 2 0
C. 0 1 2
D. error

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


x = "abcdef"
i = "a"
while i in x:
x = x[1:]
print(i, end = " ")

A. a a a a a a

27 | P a g e
B. a
C. no output
D. error

ANSWERS :

1. B 2.B 3.B 4.A 5.A 6.B 7.A 8.A 9.D(SyntaxError, True


is a keyword and it’s value cannot be changed.) 10.B 11.D 12.A 13.C 14.A
15.B 16.D 17.D 18.B 19.D 20.D 21.B 22.B 23.B

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of the following functions is a built-in function in python?


A. seed()
B. sqrt()
C. factorial()
D. print()

2. What will be the output of the following Python expression?


round(4.576)

A. 4.5
B. 5
C. 4
D. 4.6

3. The function pow(x,y,z) is evaluated as:

A. (x**y)**z
B. (x**y)/z
C. (x**y)%z
D. (x**y)*z

4. What will be the output of the following Python function?


all([2,4,0,6])

A. Error
B. True
C. False
D. 0

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


any([2>8, 4>2, 1>2])

A. Error

28 | P a g e
B. True
C. False
D. 4>2

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


import math
abs(math.sqrt(25))

A. Error
B. -5
C. 5
D. 5.0

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


sum(2,4,6)sum([1,2,3])

A. Error,6
B. 12, Error
C. 12,6
D. Error, Error

8. What will be the output of the following Python function?


min(max(False,-3,-4), 2,7)

A. 2
B. False
C. -3
D. -4

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


chr(‘97’)chr(97)

A. a Error
B. ‘a’ Error
C. Error a
D. Error Error

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


complex(1+2j)

A. Error
B. 1
C. 2j
D. 1+2j

11. The function divmod(a,b), where both ‘a’ and ‘b’ are integers is evaluated as:
A. (a%b,a//b)
B. (a//b,a%b)
C. (a//b,a*b)
D. (a/b,a%b)

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


list(enumerate([2, 3]))

29 | P a g e
A. Error
B. [(1,2),(2,3)]
C. [(0,2),(1,3)]
D. [(2,3)]

13. Which of the following functions does not necessarily accept only iterables as arguments?

A. enumerate()
B. all()
C. chr()
D. max()

14. Which of the following functions accepts only integers as arguments?

A. ord()
B. min()
C. chr()
D. any()

15. Which of the following functions will not result in an error when no arguments are passed
to it?

A. min()
B. divmod()
C. all()
D. float()

16. What will be the output of the following Python function?


hex(15)

A. f
B. OxF
C. OXf
D. Oxf

17. What will be the output of the following Python function?


len(["hello",2, 4, 6])

A. 4
B. 3
C. Error
D. 6

18. Which of the following is the use of function in python?

A. functions are reusable pieces of programs


B. functions don’t provide better modularity for your application
C. you can’t also create your own functions
D. all of the mentioned

19. Which keyword is used for function?


A. Fun

30 | P a g e
B. Define
C. Def
D. Function

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

def sayHello():
print('Hello World!')

sayHello()
sayHello()

A. Hello World! Hello World!


B. 'Hello World!' 'Hello World!'
C. Hello Hello
D. None of the mentioned

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


def printMax(a, b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
printMax(3, 4)

A. 3
B. 4
C. 4 is maximum
D. None of the mentioned

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


x = 50
def func(x):
print('x is', x)
x=2
print('Changed local x to', x)
func(x)
print('x is now', x)

A. x is now 50
B. x is now 2
C. x is now 100
D. None of the mentioned

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

def say(message, times = 1):


print(message * times)

31 | P a g e
say('Hello')
say('World', 5)

A. Hello WorldWorldWorldWorldWorld
B. Hello World 5
C. Hello World,World,World,World,World
D. Hello HelloHelloHelloHelloHello

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

def func(a, b=5, c=10):


print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c = 24)
func(c = 50, a = 100)

A. a is 7 and b is 3 and c is 10 a is 25 and b is 5 and c is 24 a is 5 and b is 100 and c is 50


B. a is 3 and b is 7 and c is 10 a is 5 and b is 25 and c is 24 a is 50 and b is 100 and c is 5
C. a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50
D. None of the mentioned

25. Which of the following is a feature of DocString?


A. Provide a convenient way of associating documentation with Python modules, functions, c
classes,and methods
B. All functions should have a docstring
C. Docstrings can be accessed by the __doc__ attribute on objects
D. All of the mentioned

26. Which are the advantages of functions in python?


A. Reducing duplication of code
B. Decomposing complex problems into simpler pieces
C. Improving clarity of the code
D. All of the mentioned

27. What are the two main types of functions?


A. Custom function
B. Built-in function & User defined function
C. User function
D. System function

28. Where is function defined?


A. Module
B. Class
C. Another function
D. All of the mentioned

29. What is called when a function is defined inside a class?


A. Module
B. Class
C. Another function
D. Method

30. Which of the following is the use of id() function in python?

32 | P a g e
A. Id returns the identity of the object
B. Every object doesn’t have a unique id
C. All of the mentioned
D. None of the mentioned

31. Which of the following refers to mathematical function?


A. sqrt
B. rhombus
C. add
D. Rhombus

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

def cube(x):

return x * x * x

x = cube(3)
print x

A. 9
B. 3
C. 27
D. 30

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

def C2F(c):

return c * 9/5 + 32

print C2F(100)

print C2F(0)

A. 212
32
B. 314
24
C. 567
98
D. None of the mentioned

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

def power(x, y=2):


r=1
for i in range(y):
r=r*x
return r
print power(3)
print power(3, 3)

33 | P a g e
A. 212
32
B. 9
27
C. 567
98
D. None of the mentioned.

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


def foo(k):
k[0] = 1
q = [0]
foo(q)print(q)
A. [0]
B. [1]
C. [1, 0]
D. [0, 1]

36. How are keyword arguments specified in the function heading?


A. one-star followed by a valid identifier
B. one underscore followed by a valid identifier
C. two stars followed by a valid identifier
D. two underscores followed by a valid identifier

37. How many keyword arguments can be passed to a function in a single function call?
A. zero
B. one
C. zero or more
D. one or more

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


def foo(fname, val):
print(fname(val))
foo(max, [1, 2, 3])
foo(min, [1, 2, 3])
A. 3 1
B. 1 3
C. error
D. none of the mentioned

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


def foo():
return total + 1
total = 0print(foo())
A. 0
B. 1
C. error
D. none of the mentioned

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


def foo():
total += 1

34 | P a g e
return total
total = 0print(foo())
A. 0
B. 1
C. error
D. none of the mentioned

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


def foo(k):
k = [1]
q = [0]
foo(q)print(q)
A. [0]
B. [1]
C. [1, 0]
D. [0, 1]

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


def f1():
x=15
print(x)
x=12
f1()
A. Error
B. 12
C. 15
D. 1512

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


def f1():
x=100
print(x)
x=+1
f1()
A. Error
B. 100
C. 101
D. 99

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


def san(x):
print(x+1)
x=-2
x=4
san(12)
A. 13
B. 10
C. 2
D. 5

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


def f1():
global x

35 | P a g e
x+=1
print(x)
x=12print("x")
A. Error
B. 13
C. 13
x
D. X

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


def f1(x):
global x
x+=1
print(x)
f1(15)print("hello")
A. error
B. hello
C. 16
D. 16
hello

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


x=12def f1(a,b=x):
print(a,b)
x=15
f1(4)
A. Error
B. 12 4
C. 4 12
D. 4 15

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


def f1(a,b=[]):
b.append(a)
return bprint(f1(2,[3,4]))
A. [3,2,4]
B. [2,3,4]
C. Error
D. [3,4,2]

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


def f(p, q, r):
global s
p = 10
q = 20
r = 30
s = 40
print(p,q,r,s)
p,q,r,s = 1,2,3,4
f(5,10,15)
A. 1 2 3 4
B. 5 10 15 4
C. 10 20 30 40

36 | P a g e
D. 5 10 15 40

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


def f(x):
print("outer")
def f1(a):
print("inner")
print(a,x)
f(3)
f1(1)
A. outer
error
B. inner
error
C. outer
inner
D. error

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


x = 5 def f1():
global x
x = 4def f2(a,b):
global x
return a+b+x
f1()
total = f2(1,2)print(total)
A. Error
B. 7
C. 8
D. 15

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


x=100def f1():
global x
x=90def f2():
global x
x=80print(x)
A. 100
B. 90
C. 80
D. Error

53. Read the following Python code carefully and point out the global variables?
y, z = 1, 2def f():
global x
x = y+z
A. x
B. y and z
C. x, y and z
D. Neither x, nor y, nor z

54. Which of the following data structures is returned by the functions globals() and locals()?

37 | P a g e
A. list
B. set
C. dictionary
D. tuple

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


x=1def cg():
global x
x=x+1
cg()
x
A. 2
B. 1
C. 0
D. Error

56. What happens if a local variable exists with the same name as the global variable you want to
access?
A. Error
B. The local variable is shadowed.
C. Undefined behavior.
D. The global variable is shadowed.

ANSWERS :

1.D 2.B 3.A 4.C 5.B 6.D 7.A 8.B 9.C


10.D 11.B 12.C 13.C 14.C 15.D 16.D 17.A
18.A 19.C 20.A 21.C 22.A 23.A 24.C 25.D
26.D 27.B 28.D 29.D 30.A 31.A 32.C 33.A 34.B
35.B 36.C 37.C 38.A 39.B 40.C 41.A 42.C 43.B 44.A
45.D 46.A 47.C 48.D 49.C 50.A 51.B 52.A 53.C 54.C
55.A 56.D

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. What will be the output of the following Python statement?


"a"+"bc"
a)a
b)bc
c)bca
d) abc
Answer: d

2. What will be the output of the following Python statement?

38 | P a g e
"abcd"[2:]
a)a
b)ab
c)cd
d) dc
Answer: c
3. The output of executing string.ascii_letters can also be achieved by:
a) string.ascii_lowercase_string.digits
b) string.ascii_lowercase+string.ascii_upercase
c) string.letters
d) string.lowercase_string.upercase
Answer: b

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


>>> str1 = 'hello'
>>> str2 = ','
>>> str3 = 'world'
>>> str1[-1:]

a) olleh
b) hello
c) h
d) o
Answer: d
5. What arithmetic operators cannot be used with strings?
a)+
b)*
c) –
d) All of the mentioned
Answer: c
6. What will be the output of the following Python code?
>>>print (r"\nhello")
a) a new line and hello
b) \nhello
c) the letter r and then hello
d) error
Answer: b
7. What will be the output of the following Python statement?
>>>print('new' 'line')
a) Error
b) Output equivalent to print ‘new\nline’
c) newline
d) new line
Answer: c
8. What will be the output of the following Python code?
>>>str1="helloworld"
>>>str1[::-1]
a) dlrowolleh
b) hello
c) world
d) helloworld
Answer: a
9. print(0xA + 0xB + 0xC):

39 | P a g e
a) 0xA0xB0xC
b) Error
c) 0x22
d) 33
Answer: d
10. What will be the output of the following Python code?
>>>example = "snow world"
>>>print("%s" % example[4:7])
a) wo
b) world
c) sn
d) rl
Answer: a
11. What will be the output of the following Python code?
>>>example = "snow world"
>>>example[3] = 's'
>>>print example
a) snow
b) snow world
c) Error
d) snos world
Answer: c

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


>>>max("what are you")
a) error
b) u
c) t
d) y
Answer: d
13. Given a string example=”hello” what is the output of example.count(‘l’)?
a)2
b)1
c) None
d) 0
Answer: a
14. What will be the output of the following Python code?
>>>example = "helle"
>>>example.find("e")
a) Error
b) -1
c) 1
d) 0
Answer: c
15. What will be the output of the following Python code?
>>>example = "helle"
>>>example.rfind("e")
a) -1
b) 4
c) 3
d) 1
Answer: b
16. What will be the output of the following Python code?

40 | P a g e
>>example="helloworld"
>>example[::-1].startswith("d")
a) dlrowolleh
b) True
c) -1
d) None
Answer: b
17. To concatenate two strings to a third what statements are applicable?
a)s3=s1s2
b)s3=s1.add(s2)
c)s3=s1.__add__(s2)
d) s3 = s1 * s2
Answer: c
Explanation: __add__ is another method that can be used for concatenation.
18. Which of the following statement prints hello\example\test.txt?
a)print(“hello\example\test.txt”)
b)print(“hello\\example\\test.txt”)
c)print(“hello\”example\”test.txt”)
d) print(“hello”\example”\test.txt”)
Answer: b
Explanation: \is used to indicate that the next \ is not an escape sequence.
19. Suppose s is “\t\tWorld\n”, what is s.strip()?
a)\t\tWorld\n
b)\t\tWorld\n
c)\t\tWORLD\n
d) World
Answer: d
20. The format function, when applied on a string returns ___________
a) Error
b) int
c) bool
d) str
Answer: d
21. What will be the output of the “hello” +1+2+3?
a) hello123
b) hello
c) Error
d) hello6
Answer: c
22. What will be the output of the following Python code?
>>>print("D", end = ' ')
>>>print("C", end = ' ')
>>>print("B", end = ' ')
>>>print("A", end = ' ')
a) DCBA
b) A,B,C,D
c) DCBA
d) D, C, B, A will be displayed on four lines
Answer: c
23. What will be displayed by print(ord(‘b’) – ord(‘a’))?
a)0
b)1
c)-1

41 | P a g e
d) 2
Answer: b
Explanation: ASCII value of b is one more than a. Hence the output of this code is 98-97, which is
equal to 1.
24. Say s=”hello” what will be the return value of type(s)?
a) int
b) bool
c) str
d) String
Answer: c
25. What is “Hello”.replace(“l”, “e”)?
a) Heeeo
b) Heelo
c) Heleo
d) None
26. To retrieve the character at index 3 from string s=”Hello” what command do we execute
(multiple answers allowed)?
a) s[]
b) s.getitem(3)
c) s.__getitem__(3)
d) s.getItem(3)
27. To return the length of string s what command do we execute?
a) s.__len__()
b) len(s)
c) size(s)
d) s.size()
28. Suppose i is 5 and j is 4, i + j is same as ________
a) i.__add(j)
b) i.__add__(j)
c) i.__Add(j)
d) i.__ADD(j)

29. What function do you use to read a string?


a) input(“Enter a string”)
b) eval(input(“Enter a string”))
c) enter(“Enter a string”)
d) eval(enter(“Enter a string”))

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


print("abc DEF".capitalize())
a) abc def
b) ABC DEF
c) Abc def
d) Abc Def

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


print("xyyzxyzxzxyy".count('yy'))
a) 2
b) 0
c) error
d) none of the mentioned

42 | P a g e
32. What will be the output of the following Python code?
print("xyyzxyzxzxyy".count('yy', 2))
a) 2
b) 0
c) 1
d) none of the mentioned
Explanation: Counts the number of times the substring ‘yy’ is present in the given string, starting from
position 2.
33. What will be the output of the following Python code?
print("xyyzxyzxzxyy".endswith("xyy"))
a) 1
b) True
c) 3
d) 2
34. What will be the output of the following Python code?
print("abcdef".find("cd"))
a) True
b) 2
c) 3
d) None of the mentioned

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


print("Hello {0} and {1}".format('foo', 'bin'))
a) Hello foo and bin
b) Hello {0} and {1} foo bin
c) Error
d) Hello 0 and 1
36. What will be the output of the following Python code?
print("Hello {name1} and {name2}".format(name1='foo', name2='bin'))
a) Hello foo and bin
b) Hello {name1} and {name2}
c) Error
d) Hello and

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


print('ab12'.isalnum())
a) True
b) False
c) None
d) Error

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


print('a B'.isalpha())
a) True
b) False
c) None
d) Error
Explanation: Space is not a letter.
39. What will be the output of the following Python code snippet?
print('0xa'.isdigit())
a) True
b) False
c) None

43 | P a g e
d) Error

40. What will be the output of the following Python code snippet?
print('for'.isidentifier())
a) True
b) False
c) None
d) Error

41. What will be the output of the following Python code snippet?
print('abc'.islower())
a) True
b) False
c) None
d) Error

42. What will be the output of the following Python code snippet?
print('11'.isnumeric())
a) True
b) False
c) None
d) Error

43. What will be the output of the following Python code snippet?
print('HelloWorld'.istitle())
a) True
b) False
c) None
d) Error

44. What will be the output of the following Python code snippet?
print('abcdef12'.replace('cd', '12'))
a) ab12ef12
b) abcdef12
c) ab12efcd
d) none of the mentioned

45. What will be the output of the following Python code snippet?
print('Ab!2'.swapcase())
a) AB!@
b) ab12
c) aB!2
d) aB1@

ANSWERS :

1.d 2.c 3.b 4.d 5.c 6.b 7.c 8.a 9.d 10.a 11.c 12.d 13.a
14.c 15.b 16.b 17.c 18.b 19.d 20.d 21.c 22.c 23.b
24.c 25.a 26.c 27.a 28.b 29.a 30.c 31.a 32.c 33.b
34.b 35.a 36.a 37.a 38.b 39.b 40.a 41.a 42.a 43.b
44.a 45.c

44 | P a g e
 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of the following is a Python tuple?


a) [1, 2, 3]
b) (1, 2, 3)
c) {1, 2, 3}
d) {}

2.Suppose t = (1, 2, 4, 3), which of the following is incorrect?


a) print(t[3])
b) t[3] = 45
c) print(max(t))
d) print(len(t))

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


>>>t=(1,2,4,3)
>>>t[1:3]
a)(1,2)
b)(1,2,4)
c)(2,4)
d) (2, 4, 3)

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


t=(1,2,4,3)
t[1:-1]
a)(1,2)
b)(1,2,4)
c)(2,4)
d) (2, 4, 3)

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


t = (1, 2, 4, 3, 8, 9)
[t[i] for i in range(0, len(t), 2)]
a)[2,3,9]
b)[1,2,4,3,8,9]
c)[1,4,8]
d) (1, 4, 8)

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


d = {"john":40, "peter":45}
d["john"]
a)40
b)45
c)“john”

45 | P a g e
d) “peter”

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


t = (1, 2)
2*t
a)(1,2,1,2)
b)[1,2,1,2]
c)(1,1,2,2)
d) [1, 1, 2, 2]

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


t1 = (1, 2, 4, 3)
t2 = (1, 2, 3, 4)
t1 < t2
a)True
b)False
c)Error
d) None

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


my_tuple = (1, 2, 3, 4)
my_tuple.append( (5, 6, 7) )
print len(my_tuple)
a)1
b)2
c)5
d) Error

10. What is the data type of (1)?a)Tuple


b)Integer
c)List
d) Both tuple and integer

11. If a=(1,2,3,4), a[1:-1] is _________


a)Error, tuple slicing doesn’t exist
b)[2,3]
c)(2,3,4)
d) (2,3)

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


a=(1,2,(4,5))
b=(1,2,(3,4))
a<b
a) False
b) True
c) Error, < operator is not valid for tuples

46 | P a g e
d) Error, < operator is valid for tuples but not if there are sub-tuples

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


a=("Check")*3
a
a)(‘Check’,’Check’,’Check’)
b)* Operator not valid for tuples
c)(‘CheckCheckCheck’)
d) Syntax error

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


a=(1,2,3,4)
del(a[2])
a)Now,a=(1,2,4)
b)Now,a=(1,3,4)
c)Now,a=(3,4)
d) Error as tuple is immutable

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


a=(2,3,4)
sum(a,3)
a) Too many arguments for sum() method
b) The method sum() doesn’t exist for tuples
c)12
d) 9

16. Is the following Python code valid?


a=(1,2,3,4)
del a
a)No because tuple is immutable
b)Yes, first element in the tuple is deleted
c)Yes, the entire tuple is deleted
d) No, invalid syntax for del method

17. What type of data is: a=[(1,1),(2,4),(3,9)]?


a) Array of tuples
b) List of tuples
c) Tuples of lists
d) Invalid type

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


a=(0,1,2,3,4)
b=slice(0,2)
a[b]
a)Invalid syntax for slicing
b)[0,2]

47 | P a g e
c)(0,1)
d) (0,2)

19. Is the following Python code valid?


a=(1,2,3)
b=('A','B','C')
c=tuple(zip(a,b))
a)Yes, c will be ((1, ‘A’), (2, ‘B’), (3, ‘C’))
b)Yes, c will be ((1,2,3),(‘A’,’B’,’C’))
c)No because tuples are immutable
d) No because the syntax for zip function isn’t valid

20. Is the following Python code valid?


a,b,c=1,2,3
a,b,c
a)Yes,[1,2,3] is printed
b)No,invalid syntax
c)Yes,(1,2,3) is printed
d) 1 is printed

21. Is the following Python code valid?


a,b=1,2,3
a)Yes, this is an example of tuple unpacking. a=1 and b=2
b) Yes, this is an example of tuple unpacking. a=(1,2) and b=3
c) No, too many values to unpack
d) Yes, this is an example of tuple unpacking. a=1 and b=(2,3)

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


a=(1,2)
b=(3,4)
c=a+b
c
a)(4,6)
b)(1,2,3,4)
c)Error as tuples are immutable
d) None

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


a,b=6,7
a,b=b,a
a,b
a)(6,7)
b)Invalid syntax
c)(7,6)
d) Nothing is printed

48 | P a g e
24. Is the following Python code valid?
a=2,3,4,5
a
a)Yes, 2 is printed
b)Yes, [2,3,4,5] is printed
c)No, too many values to unpack
d) Yes, (2,3,4,5) is printed

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


a=(2,3,1,5)
a.sort()
a
a)(1,2,3,5)
b)(2,3,1,5)
c)None
d) Error, tuple has no attribute sort

26. Is the following Python code valid?


a=(1,2,3)
b=a.update(4,)
a)Yes, a=(1,2,3,4) and b=(1,2,3,4)
b)Yes, a=(1,2,3) and b=(1,2,3,4)
c)No because tuples are immutable
d) No because wrong syntax for update() method

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


a=[(2,4),(1,2),(3,9)]
a.sort()
a
a)[(1, 2), (2, 4), (3, 9)]
b)[(2,4),(1,2),(3,9)]
c)Error because tuples are immutable
d) Error, tuple has no sort attribute

1.b 2.b 3.c 4.c 5.c 6.a 7.a 8.b 9.d(Tuples are immutable and
don’t have an append method. An exception is thrown in this case.) 10.b 11.d
12.a 13.c 14.d 15.c 16.c 17.b 18.c 19.a 20.c(A tuple
needn’t be enclosed in parenthesis.) 21.c (For unpacking to happen, the number of
values of the right hand side must be equal to the number of variables on the left hand
side.) 22.b 23.c 24.d 25.d (A tuple is immutable thus it doesn’t have
a sort attribute.) 26.c (Tuple doesn’t have any update() attribute because it is
immutable.) 27.a (A list of tuples is a list itself. Hence items of a list can be
sorted.)

49 | P a g e
 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of the following commands will create a list?


a)list1=list()
b)list1=[]
c)list1=list([1,2,3])
d) all of the mentioned

2. What is the output when we execute list(“hello”)?


a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) [‘hello’]
c) [‘llo’]
d) [‘olleh’]

3. Suppose listExample is [‘h’,’e’,’l’,’l’,’o’], what is len(listExample)?


a) 5
b) 4
c) None
d) Error

4. Suppose list1 is [2445,133,12454,123], what is max(list1)?


a) 2445
b) 133
c) 12454
d) 123

5. Suppose list1 is [3, 5, 25, 1, 3], what is min(list1)?


a) 3
b) 5
c) 25
d) 1

6. Suppose list1 is [1, 5, 9], what is sum(list1)?


a) 1
b) 9
c) 15
d) Error

7. To shuffle the list(say list1) what function do we use?


a) list1.shuffle()
b) shuffle(list1)
c) random.shuffle(list1)
d) random.shuffleList(list1)

8. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of the following is correct syntax for slicing
operation?
a) print(list1[0])
b) print(list1[:2])
c) print(list1[:-2])
d) all of the mentioned

50 | P a g e
9. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1]?
a) Error
b) None
c) 25
d) 2

10. Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1]?
a) [2, 33, 222, 14]
b) Error
c) 25
d) [25, 14, 222, 33, 2]

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


>>>names = ['Amir', 'Bear', 'Charlton', 'Daman']
>>>print(names[-1][-1])
A
b) Daman
c) Error
d) n

12. Suppose list1 is [1, 3, 2], What is list1 * 2?


a) [2, 6, 4]
b) [1, 3, 2, 1, 3]
c) [1, 3, 2, 1, 3, 2]
d) [1, 3, 2, 3, 2, 1]

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


>>>list1 = [11, 2, 23]
>>>list2 = [11, 2, 2]
>>>list1 < list2 is
True
b) False
c) Error
d) None

14. To add a new element to a list we use which command?


a) list1.add(5)
b) list1.append(5)
c) list1.addLast(5)
d) list1.addEnd(5)

15. To insert 5 to the third position in list1, we use which command?


a) list1.insert(3, 5)
b) list1.insert(2, 5)
c) list1.add(3, 5)
d) list1.append(3, 5)

16. To remove string “hello” from list1, we use which command?


a) list1.remove(“hello”)
b) list1.remove(hello)
c) list1.removeAll(“hello”)
d) list1.removeOne(“hello”)

51 | P a g e
17. Suppose list1 is [3, 4, 5, 20, 5], what is list1.index(5)?
a) 0
b) 1
c) 4
d) 2

18. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1.count(5)?


a) 0
b) 4
c) 1
d) 2

19. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.reverse()?
a) [3, 4, 5, 20, 5, 25, 1, 3]
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [25, 20, 5, 5, 4, 3, 3, 1]
d) [3, 1, 25, 5, 20, 5, 4, 3]

20. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.extend([34,
5])?
a) [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
b) [1, 3, 3, 4, 5, 5, 20, 25, 34, 5]
c) [25, 20, 5, 5, 4, 3, 3, 1, 34, 5]
d) [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]

21. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.pop(1)?
a) [3, 4, 5, 20, 5, 25, 1, 3]
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [3, 5, 20, 5, 25, 1, 3]
d) [1, 3, 4, 5, 20, 5, 25]
22. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.pop()?
a) [3, 4, 5, 20, 5, 25, 1]
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [3, 5, 20, 5, 25, 1, 3]
d) [1, 3, 4, 5, 20, 5, 25]

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


>>>"Welcome to Python".split()
a) [“Welcome”, “to”, “Python”]
b) (“Welcome”, “to”, “Python”)
c) {“Welcome”, “to”, “Python”}
d) “Welcome”, “to”, “Python”

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


>>>list("a#b#c#d".split('#'))
a) [‘a’, ‘b’, ‘c’, ‘d’]
b) [‘a b c d’]
c) [‘a#b#c#d’]
d) [‘abcd’]

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


myList = [1, 5, 5, 5, 5, 1]
max = myList[0]

52 | P a g e
indexOfMax = 0
for i in range(1, len(myList)):
if myList[i] > max:
max = myList[i]
indexOfMax = i
print(indexOfMax)
a) 1
b) 2
c) 3
d) 4

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


>>>list1 = [1, 3]
>>>list2 = list1
>>>list1[0] = 4
>>>print(list2)
[1, 3]
b) [4, 3]
c) [1, 4]
d) [1, 3, 4]

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


names1 = ['Amir', 'Bala', 'Chales']
if 'amir' in names1:
print(1)
else:
print(2)
a) None
b) 1
c) 2
d) Error

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


numbers = [1, 2, 3, 4]
numbers.append([5,6,7,8])
print(len(numbers))
a) 4
b) 5
c) 8
d) 12

29. which of the following the “in” operator can be used to check if an item is in it?
a) Lists
b) Dictionary
c) Set
d) All of the mentioned

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


list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
print(len(list1 + list2))
a) 2
b) 4

53 | P a g e
c) 5
d) 8

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


matrix = [[1, 2, 3, 4],
[4, 5, 6, 7],
[8, 9, 10, 11],
[12, 13, 14, 15]]
for i in range(0, 4):
print(matrix[i][1], end = " ")
a) 1 2 3 4
b) 4 5 6 7
c) 1 3 8 12
d) 2 5 9 13

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


data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
print(data[1][0][0])
a) 1
b) 2
c) 4
d) 5

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


points = [[1, 2], [3, 1.5], [0.5, 0.5]]
points.sort()
print(points)
[[1, 2], [3, 1.5], [0.5, 0.5]]
b) [[3, 1.5], [1, 2], [0.5, 0.5]]
c) [[0.5, 0.5], [1, 2], [3, 1.5]]
d) [[0.5, 0.5], [3, 1.5], [1, 2]]

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


a=[[]]*3
a[1].append(7)
print(a)
a) Syntax error
b) [[7], [7], [7]]
c) [[7], [], []]
d) [[],7, [], []]

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


b=[2,3,4,5]
a=list(filter(lambda x:x%2,b))
print(a)
a) [2,4]
b) [ ]
c) [3,5]
d) Invalid arguments for filter function

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


lst=[3,4,6,1,2]
lst[1:2]=[7,8]

54 | P a g e
print(lst)
a) [3, 7, 8, 6, 1, 2]
b) Syntax error
c) [3,[7,8],6,1,2]
d) [3,4,6,7,8]

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


a=[1,2,3]
b=a.append(4)print(a)
print(b)
a)[1,2,3,4]
[1,2,3,4]
b)[1, 2, 3, 4]
None
c)Syntax error
d)[1,2,3]
[1,2,3,4]

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


a=[13,56,17]
a.append([87])
a.extend([45,67])
print(a)
a) [13, 56, 17, [87], 45, 67]
b) [13, 56, 17, 87, 45, 67]
c) [13, 56, 17, 87,[ 45, 67]]
d) [13, 56, 17, [87], [45, 67]]

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


lst=[[1,2],[3,4]]
print(sum(lst,[]))
a) [[3],[7]]
b) [1,2,3,4]
c) Error
d) [10]

ANSWERS :

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

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Suppose list1 = [0.5 * x for x in range(0, 4)], list1 is:


a) [0, 1, 2, 3]
b) [0, 1, 2, 3, 4]
c) [0.0, 0.5, 1.0, 1.5]

55 | P a g e
d) [0.0, 0.5, 1.0, 1.5, 2.0]

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


>>>m = [[x, x + 1, x + 2] for x in range(0, 3)]
a) [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b) [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
c) [1, 2, 3, 4, 5, 6, 7, 8, 9]
d) [0, 1, 2, 1, 2, 3, 2, 3, 4]

3. How many elements are in m?


m = [[x, y] for x in range(0, 4) for y in range(0, 4)]
a) 8
b) 12
c) 16
d) 32

4. What will be the output of the following Python code snippet?


k = [print(i) for i in my_string if i not in "aeiou"]
a) prints all the vowels in my_string
b) prints all the consonants in my_string
c) prints all characters of my_string that aren’t vowels
d) prints only on executing print(k)

5. What is the output of print(k) in the following Python code snippet?

k = [print(i) for i in my_string if i not in "aeiou"]


print(k)
a) all characters of my_string that aren’t vowels
b) a list of Nones
c) list of Trues
d) list of Falses

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

my_string = "hello world"


k = [(i.upper(), len(i)) for i in my_string]
print(k)
a) [(‘HELLO’, 5), (‘WORLD’, 5)]
b) [(‘H’, 1), (‘E’, 1), (‘L’, 1), (‘L’, 1), (‘O’, 1), (‘ ‘, 1), (‘W’, 1), (‘O’, 1), (‘R’, 1), (‘L’, 1),
(‘D’, 1)]
c) [(‘HELLO WORLD’, 11)]
d) none of the mentioned

56 | P a g e
7. What will be the output of the following Python code snippet?

x = [i**+1 for i in range(3)]; print(x);


a) [0, 1, 2]
b) [1, 2, 5]
c) error, **+ is not a valid operator
d) error, ‘;’ is not allowed

8. What will be the output of the following Python code snippet?

print([i.lower() for i in "HELLO"])


a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) ‘hello’
c) [‘hello’]
d) hello

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

print([if i%2==0: i; else: i+1; for i in range(4)])


a) [0, 2, 2, 4]
b) [1, 1, 3, 3]
c) error
d) none of the mentioned

10. Which of the following is the same as list(map(lambda x: x**-1, [1, 2, 3]))?
a) [x**-1 for x in [(1, 2, 3)]]
b) [1/x for x in [(1, 2, 3)]]
c) [1/x for x in (1, 2, 3)]
d) error

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

l1=[1,2,3]
l2=[4,5,6]
[x*y for x in l1 for y in l2]
a) [4, 8, 12, 5, 10, 15, 6, 12, 18]
b) [4, 10, 18]
c) [4, 5, 6, 8, 10, 12, 12, 15, 18]
d) [18, 12, 6, 15, 10, 5, 12, 8, 4]

12. Write the list comprehension to pick out only negative integers from a
given list ‘l’.

57 | P a g e
a) [x<0 in l]
b) [x for x<0 in l]
c) [x in l for x<0]
d) [x for x in l if x<0]

13. Write a list comprehension for number and its cube for l=[1, 2, 3, 4, 5, 6, 7, 8, 9].
a) [x**3 for x in l]
b) [x^3 for x in l]
c) [x**3 in l]
d) [x^3 in l]

14. Read the information given below carefully and write a list comprehension such
that the output is: [‘e’, ‘o’]

w="hello"
v=('a', 'e', 'i', 'o', 'u')
a) [x for w in v if x in v]
b) [x for x in w if x in v]
c) [x for x in v if w in v]
d) [x for v in w for x in w]

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

t=32.00
[round((x-32)*5/9) for x in t]
a) [0]
b) 0
c) [0.00]
d) Error

16. Write a list comprehension for producing a list of numbers between 1 and 1000
that are divisible by 3.
a) [x in range(1, 1000) if x%3==0]
b) [x for x in range(1000) if x%3==0]
c) [x%3 for x in range(1, 1000)]
d) [x%3=0 for x in range(1, 1000)]

17. Write a list comprehension to produce the list: [1, 2, 4, 8, 16……212].


a) [(2**x) for x in range(0, 13)]
b) [(x**2) for x in range(1, 13)]
c) [(2**x) for x in range(1, 13)]
d) [(x**2) for x in range(0, 13)]

58 | P a g e
18. What will be the output of the following Python list comprehension?

[j for i in range(2,8) for j in range(i*2, 50, i)]


a) A list of prime numbers up to 50
b) A list of numbers divisible by 2, up to 50
c) A list of non prime numbers, up to 50
d) Error

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

l=["good", "oh!", "excellent!", "#450"]


[n for n in l if n.isalpha() or n.isdigit()]
a) [‘good’, ‘oh’, ‘excellent’, ‘450’ ]
b) [‘good’]
c) [‘good’, ‘#450’]
d) [‘oh!’, ‘excellent!’, ‘#450’]

20. Write a list comprehension equivalent for the Python code shown below.

for i in range(1, 101):


if int(i*0.5)==i*0.5:
print(i)
a) [i for i in range(1, 100) if int(i*0.5)==(i*0.5)]
b) [i for i in range(1, 101) if int(i*0.5)==(i*0.5)]
c) [i for i in range(1, 101) if int(i*0.5)=(i*0.5)]
d) [i for i in range(1, 100) if int(i*0.5)=(i*0.5)]

1.c 2.b 3.c 4.c 5.b 6.b 7.a 8.a 9.c 10.c 11.c 12.d 13.a
14.b 15.d 16.b 17.a 18.c 19.b 20.b

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of these about a set is not true?


a) Mutable data type
b) Allows duplicate values
c) Data type with unordered values
d) Immutable data type

2. Which of the following is not the correct syntax for creating a set?
a) set([[1,2],[3,4]])
b) set([1,2,2,3,4])

59 | P a g e
c) set((1,2,3,4))
d) {1,2,3,4}

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


nums = set([1,1,2,3,3,3,4,4])
print(len(nums))
a) 7
b) Error, invalid syntax for formation of set
c) 4
d) 8

4. Which of the following statements is used to create an empty set?


a) {}
b) set()
c) []
d) ( )

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


a={5,4}
b={1,2,4,5}
a<b
a) {1,2}
b) True
c) False
d) Invalid operation
a<b returns True if a is a proper subset of b.

6. If a={5,6,7,8}, which of the following statements is false?


a) print(len(a))
b) print(min(a))
c) a.remove(5)
d) a[2]=45
7. If a={5,6,7}, what happens when a.add(5) is executed?
a) a={5,5,6,7}
b) a={5,6,7}
c) Error as there is no add function for set data type
d) Error as 5 already exists in the set

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


a={4,5,6}
b={2,8,6}
a+b
a) {4,5,6,2,8}
b) {4,5,6,2,8,6}
c) Error as unsupported operand type for sets
d) Error as the duplicate item 6 is present in both sets

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


a={4,5,6}
b={2,8,6}
a-b
a) {4,5}
b) {6}

60 | P a g e
c) Error as unsupported operand type for set data type
d) Error as the duplicate item 6 is present in both sets

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


a={5,6,7,8}
b={7,8,10,11}
a^b
a) {5,6,7,8,10,11}
b) {7,8}
c) Error as unsupported operand type of set data type
d) {5,6,10,11}
^ operator returns a set of elements in set A or set B, but not in both (symmetric difference).

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


s={5,6}
s*3
a) Error as unsupported operand type for set data type
b) {5,6,5,6,5,6}
c) {5,6}
d) Error as multiplication creates duplicate elements which isn’t allowed
The multiplication operator isn’t valid for the set data type.

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


a={3,4,5}
b={5,6,7}
a|b
a) Invalidoperation
b) {3,4,5,6,7}
c) {5}
d) {3,4,6,7}

13. Is the following Python code valid?


a={3,4,{7,5}}
print(a[2][0])
a) Yes, 7 is printed
b) Error, elements of a set can’t be printed
c) Error, subsets aren’t allowed
d) Yes, {7,5} is printed

14. Which of these about a frozenset is not true?


a)Mutable data type
b)Allows duplicate values
c)Data type with unordered values
d) Immutable data type

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


a={3,4,5}
a.update([1,2,3])
a
a) Error, no method called update for set data type
b) {1, 2, 3, 4, 5}
c) Error, list can’t be added to set

61 | P a g e
d) Error, duplicate item present in list

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


>>> a={1,2,3}
>>> a.intersection_update({2,3,4,5})
>>> a
a) {2,3}
b) Error, duplicate item present in list
c) Error, no method called intersection_update for set data type
d) {1,4,5}

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


>>> a={1,2,3}
>>> b=a
>>> b.remove(3)
>>> a
a) {1,2,3}
b) Error, copying of sets isn’t allowed
c) {1,2}
d) Error, invalid syntax for remove

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


>>> a={1,2,3}
>>> b=a.add(4)
>>> b
a) 0
b) {1,2,3,4}
c) {1,2,3}
d) Nothing is printed

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


>>> a={5,6,7}
>>> sum(a,5)
a) 5
b) 23
c) 18
d) Invalid syntax for sum method, too many arguments

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


>>> a={1,2,3}
>>> {x*2 for x in a|{4,5}}
a) {2,4,6}
b) Error, set comprehensions aren’t allowed
c) {8,2,10,4,6}
d) {8,10}
Set comprehensions are allowed

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


>>> a={5,6,7,8}
>>> b={7,8,9,10}
>>> len(a+b)
a) 8
b) Error, unsupported operand ‘+’ for sets

62 | P a g e
c) 6
d) Nothing is displayed

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


a={1,2,3}
b={1,2,3}
c=a.issubset(b)
print(c)
a) True
b) Error, no method called issubset() exists
c) Syntax error for issubset() method
d) False

23. Is the following Python code valid?


a={1,2,3}
b={1,2,3,4}
c=a.issuperset(b)
print(c)
a) False
b) True
c) Syntax error for issuperset() method
d) Error, no method called issuperset()

24.Set makes use of __________


Dictionary makes use of ____________
a) keys, keys
b) key values, keys
c) keys, key values
d) key values, key values

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


s={2, 5, 6, 6, 7}
s
a) {2,5,7}
b) {2,5,6,7}
c) {2,5,6,6,7}
d) Error

26. Which of the following functions cannot be used on heterogeneous sets?


a) pop
b) remove
c) update
d) sum

27. Which of the following functions will return the symmetric difference between two sets, x
and y?
a) x|y
b) x^y
c) x&y
d) x – y

28. What will be the output of the following Python code snippet?
z=set('abc$de')

63 | P a g e
'a' in z
a) True
b) False
c) Nooutput
d) Error

29. What will be the output of the following Python code snippet?
s=set([1, 2, 3])
s.union([4, 5])
s|([4, 5])
a) {1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
b) Error
{1, 2, 3, 4, 5}
c) {1, 2, 3, 4, 5}
Error
d) Error
Error
30. What will be the output of the following Python code snippet?
for x in set('pqr'):
print(x*2)
a) pp
qq
rr
b) pqr
pqr
c) ppqqrr
d) pqrpqr

31. What will be the output of the following Python code snippet?
{a**2 for a in range(4)}
a) {1,4,9,16}
b) {0,1,4,9,16}
c) Error
d) {0, 1, 4, 9}

32. The ____________ function removes the first element of a set and the last element of a list.
a) remove
b) pop
c) discard
d) dispose

33. The difference between the functions discard and remove is that:
a) Discard removes the last element of the set whereas remove removes the first element of the set
b) Discard throws an error if the specified element is not present in the set whereas remove does
not throw an error in case of absence of the specified element
c) Remove removes the last element of the set whereas discard removes the first element of the
set
d) Remove throws an error if the specified element is not present in the set whereas discard does
not throw an error in case of absence of the specified element

34. If we have two sets, s1 and s2, and we want to check if all the elements of s1 are present in s2
or not, we can use the function:

64 | P a g e
a) s2.issubset(s1)
b) s2.issuperset(s1)
c) s1.issuperset(s2)
d) s1.isset(s2)

35. What will be the output of the following Python code, if s1= {1, 2, 3}?
s1.issubset(s1)
a) True
b) Error
c) Nooutput
d) False

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

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of the following statements create a dictionary?


a) d={}
b) d={“john”:40,“peter”:45}
c) d={40:”john”,45:”peter”}
d) All of the mentioned

2. What will be the output of the following Python code snippet?


d = {"john":40, "peter":45}
a) “john”,40,45,and“peter”
b) “john”and“peter”
c) 40and45
d) d = (40:”john”, 45:”peter”)

3. What will be the output of the following Python code snippet?


d = {"john":40, "peter":45}
"john" in d
a) True
b) False
c) None
d) Error

4. What will be the output of the following Python code snippet?


d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 == d2
a) True
b) False
c) None
d) Error

65 | P a g e
5. What will be the output of the following Python code snippet?
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 > d2
a) True
b) False
c) Error
d) None

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


d = {"john":40, "peter":45}
d["john"]
a) 40
b) 45
c) “john”
d) “peter”

7. Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command do we
use?
a) d.delete(“john”:40)
b) d.delete(“john”)
c) del d[“john”]
d) del d(“john”:40)

8. Suppose d = {“john”:40, “peter”:45}. To obtain the number of entries in dictionary which


command do we use?
a) d.size()
b) len(d)
c) size(d)
d) d.len()

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


d = {"john":40, "peter":45}
print(list(d.keys()))
a) [“john”,“peter”]
b) [“john”:40,“peter”:45]
c) (“john”,“peter”)
d) (“john”:40, “peter”:45)

10. Suppose d = {“john”:40, “peter”:45}, what happens when we try to retrieve a value using
the expression d[“susan”]?
a) Since “susan” is not a value in the set, Python raises a KeyError exception
b) It is executed fine and no exception is raised, and it returns None
c) Since “susan” is not a key in the set, Python raises a KeyError exception
d) Since “susan” is not a key in the set, Python raises a syntax error

11. Which of these about a dictionary is false?


a) The values of a dictionary can be accessed using keys
b) The keys of a dictionary can be accessed using values
c) Dictionaries aren’t ordered
d) Dictionaries are mutable

66 | P a g e
12. Which of the following is not a declaration of the dictionary?
a) {1:‘A’,2:‘B’}
b) dict([[1,”A”],[2,”B”]])
c) {1,”A”,2”B”}
d) { }

13. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
for i,j in a.items():
print(i,j,end=" ")
a) 1A2B3C
b) 123
c) ABC
d) 1:”A” 2:”B” 3:”C”

14. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
print(a.get(1,4))
a) 1
b) A
c) 4
d) Invalid syntax for get method

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


a={1:"A",2:"B",3:"C"}
b={4:"D",5:"E"}
a.update(b)
print(a)
a) {1:‘A’,2:‘B’,3:‘C’}
b) Method update() doesn’t exist for dictionaries
c) {1:‘A’,2:‘B’,3:‘C’,4:‘D’,5:‘E’}
d) {4: ‘D’, 5: ‘E’}

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


a={1:"A",2:"B",3:"C"}
b=a.copy()
b[2]="D"
print(a)
a) Error, copy() method doesn’t exist for dictionaries
b) {1:‘A’,2:‘B’,3:‘C’}
c) {1:‘A’,2:‘D’,3:‘C’}
d) “None” is printed

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


a={1:"A",2:"B",3:"C"}
a.clear()
print(a)
a) None
b) {None:None,None:None,None:None}
c) {1:None,2:None,3:None}
d) { }

67 | P a g e
18. Which of the following isn’t true about dictionary keys?
a) More than one key isn’t allowed
b) Keys must be immutable
c) Keys must be integers
d) When duplicate keys encountered, the last assignment wins

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


a={1:5,2:3,3:4}
a.pop(3)
print(a)
a) {1:5}
b) {1:5,2:3}
c) Error, syntax error for pop() method
d) {1: 5, 3: 4}

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


a={1:5,2:3,3:4}
print(a.pop(4,9))
a) 9
b) 3
c) Too many arguments for pop() method
d) 4

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


a={1:"A",2:"B",3:"C"}
for i in a:
print(i,end=" ")
a) 123
b) ‘A’‘B’‘C’
c) 1‘A’2‘B’3‘C’
d) Error, it should be: for i in a.items():

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


>>> a={1:"A",2:"B",3:"C"}
>>> a.items()
a) Syntax error
b) dict_items([(‘A’),(‘B’),(‘C’)])
c) dict_items([(1,2,3)])
d) dict_items([(1, ‘A’), (2, ‘B’), (3, ‘C’)])

23. Which of the statements about dictionary values if false?


a) More than one key can have the same value
b) The values of the dictionary can be accessed as dict[key]
c) Values of a dictionary must be unique
d) Values of a dictionary can be a mixture of letters and numbers

24. What will be the output of the following Python code snippet?
>>> a={1:"A",2:"B",3:"C"}
>>> del a
a) method del doesn’t exist for the dictionary

68 | P a g e
b) del deletes the values in the dictionary
c) del deletes the entire dictionary
d) del deletes the keys in the dictionary

25. If a is a dictionary with some key-value pairs, what does a.popitem() do?
a) Removes an arbitrary element
b) Removes all the key-value pairs
c) Removes the key-value pair for the key given as an argument
d) Invalid method for dictionary

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


>>> a={'B':5,'A':9,'C':7}
>>> sorted(a)
a) [‘A’,’B’,’C’]
b) [‘B’,’C’,’A’]
c) [5,7,9]
d) [9,5,7]
27. What will be the output of the following Python code?
>>> a={i: i*i for i in range(6)}
>>> a
a) Dictionary comprehension doesn’t exist
b) {0:0,1:1,2:4,3:9,4:16,5:25,6:36}
c) {0:0,1:1,4:4,9:9,16:16,25:25}
d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

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


>>> a={}
>>> a.fromkeys([1,2,3],"check")
a) Syntax error
b) {1:”check”,2:”check”,3:”check”}
c) “check”
d) {1:None,2:None,3:None}

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


>>> b={}
>>> all(b)
a) {}
b) False
c) True
d) An exception is thrown

30. If b is a dictionary, what does any(b) do?


a) Returns True if any key of the dictionary is true
b) Returns False if dictionary is empty
c) Returns True if all keys of the dictionary are true
d) Method any() doesn’t exist for dictionary

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


>>> a={"a":1,"b":2,"c":3}
>>> b=dict(zip(a.values(),a.keys()))
>>> b
a) {‘a’:1,‘b’:2,‘c’:3}

69 | P a g e
b) An exception is thrown
c) {‘a’:‘b’:‘c’:}
d) {1: ‘a’, 2: ‘b’, 3: ‘c’}

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


>>> a=dict()
>>> a[1]
a) An exception is thrown since the dictionary is empty
b) ‘‘
c) 1
d) 0

ANSWERS :

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

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Lambda is a function in python?


A. True
B. False
C. Lambda is a function in python but user can not use it.
D. None of the above

2. What is the output of the following program?


z = lambda x : x * x
print(z(6))
A. 6
B. 36
C. 0
D. Error

1.a2.b3.4.5.

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. To open a file c:\scores.txt for reading, we use _____________


a) infile = open(“c:\scores.txt”, “r”)
b) infile = open(“c:\\scores.txt”, “r”)
c) infile = open(file = “c:\scores.txt”, “r”)
d) infile = open(file = “c:\\scores.txt”, “r”)

2. To open a file c:\scores.txt for writing, we use ____________


a) outfile = open(“c:\scores.txt”, “w”)

70 | P a g e
b) outfile = open(“c:\\scores.txt”, “w”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\\scores.txt”, “w”)

3. To open a file c:\scores.txt for appending data, we use ____________


a) outfile = open(“c:\\scores.txt”, “a”)
b) outfile = open(“c:\\scores.txt”, “rw”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\\scores.txt”, “w”)

4. Which of the following statements are true?


a) When you open a file for reading, if the file does not exist, an error occurs
b) When you open a file for writing, if the file does not exist, a new file is created
c) When you open a file for writing, if the file exists, the existing file is overwritten with the new file
d) All of the mentioned

5. To read two characters from a file object infile, we use ____________


a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

6. To read the entire remaining contents of the file as a string from a file object infile, we use
____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

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

f = None
for i in range (5):
with open("data.txt", "w") as f:
if i > 2:
break

print(f.closed)

a) True
b) False
c) None
d) Error

8. To read the next line of the file from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

9. To read the remaining lines of the file from a file object infile, we use ____________
a) infile.read(2)

71 | P a g e
b) infile.read()
c) infile.readline()
d) infile.readlines()

10. The readlines() method returns ____________


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

11. Which are the two built-in functions to read a line of text from standard input, which by default
comes from the keyboard?
a) Raw_input & Input
b) Input & Scan
c) Scan & Scanner
d) Scanner

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

str = raw_input("Enter your input: ");

print "Received input is : ", str

a) Enter your input: Hello Python


Received input is : Hello Python
b) Enter your input: Hello Python
Received input is : Hello
c) Enter your input: Hello Python
Received input is : Python
d) None of the mentioned

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

str = input("Enter your input: ");

print "Received input is : ", str

a) Enter your input: [x*5 for x in range(2,10,2)]


Received input is : [x*5 for x in range(2,10,2)]
b) Enter your input: [x*5 for x in range(2,10,2)]
Received input is : [10, 30, 20, 40]
c) Enter your input: [x*5 for x in range(2,10,2)]
Received input is : [10, 10, 30, 40]
d) None of the mentioned

14. Which one of the following is not attributes of file?

a) closed
b) softspace
c) rename
d) mode

15. What is the use of tell() method in python?

72 | P a g e
a) tells you the current position within the file
b) tells you the end position within the file
c) tells you the file is opened or not
d) none of the mentioned

16. What is the current syntax of rename() a file?

a) rename(current_file_name, new_file_name)
b) rename(new_file_name, current_file_name,)
c) rename(()(current_file_name, new_file_name))
d) none of the mentioned

17. What is the current syntax of remove() a file?


a) remove(file_name)
b) remove(new_file_name, current_file_name,)
c) remove(() , file_name))
d) none of the mentioned

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

fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines

# This is 1st line

# This is 2nd line

# This is 3rd line

# This is 4th line

# This is 5th line

for index in range(5):


line = fo.next()
print "Line No %d - %s" % (index, line)

# Close opened file


fo.close()

a) Compilation Error
b) Syntax Error
c) Displays Output
d) None of the mentioned

19. What is the use of seek() method in files?


a) sets the file’s current position at the offset
b) sets the file’s previous position at the offset
c) sets the file’s current position within the file
d) none of the mentioned

20. What is the use of truncate() method in file?

73 | P a g e
a) truncates the file size
b) deletes the content of the file
c) deletes the file size
d) none of the mentioned.

21. Which is/are the basic I/O connections in file?


a) Standard Input
b) Standard Output
c) Standard Errors
d) All of the mentioned

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

import sys
sys.stdout.write(' Hello\n')
sys.stdout.write('Python\n')

a) Compilation Error
b) Runtime Error
c) Hello Python
d) Hello
Python

23. Which of the following mode will refer to binary data?


a) r
b) w
c) +
d) b

24. What is the pickling?


a) It is used for object serialization
b) It is used for object deserialization
c) None of the mentioned
d) All of the mentioned

25. What is unpickling?


a) It is used for object serialization
b) It is used for object deserialization
c) None of the mentioned
d) All of the mentioned

26. What is the correct syntax of open() function?


a) file = open(file_name [, access_mode][, buffering])
b) file object = open(file_name [, access_mode][, buffering])
c) file object = open(file_name)
d) none of the mentioned.

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

fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
fo.flush()
fo.close()

74 | P a g e
a) Compilation Error
b) Runtime Error
c) No Output
d) Flushes the file when closing them

28. Correct syntax of file.writelines() is?


a) file.writelines(sequence)
b) fileObject.writelines()
c) fileObject.writelines(sequence)
d) none of the mentioned

29. Correct syntax of file.readlines() is?


a) fileObject.readlines( sizehint );
b) fileObject.readlines();
c) fileObject.readlines(sequence)
d) none of the mentioned.

30. In file handling, what does this terms means “r, a”?
a) read, append
b) append, read
c) write, append
d) none of the mentioned

31. What is the use of “w” in file handling?


a) Read
b) Write
c) Append
d) None of the mentioned

32. What is the use of “a” in file handling?


a) Read
b) Write
c) Append
d) None of the mentioned

33. Which function is used to read all the characters?


a) Read()
b) Readcharacters()
c) Readall()
d) Readchar()

34. Which function is used to read single line from file?


a) Readline()
b) Readlines()
c) Readstatement()
d) Readfullline()

35. Which function is used to write all the characters?


a) write()
b) writecharacters()
c) writeall()
d) writechar()

75 | P a g e
36. Which function is used to write a list of string in a file?
a) writeline()
b) writelines()
c) writestatement()
d) writefullline()

37. Which function is used to close a file in python?


a) Close()
b) Stop()
c) End()
d) Closefile()

38. Is it possible to create a text file in python?


a) Yes
b) No
c) Machine dependent
d) All of the mentioned

39. Which of the following are the modes of both writing and reading in binary format in file?
a) wb+
b) w
c) wb
d) w+

40. Which of the following is not a valid mode to open a file?


a) ab
b) rw
c) r+
d) w+

41. What is the difference between r+ and w+ modes?


a) no difference
b) in r+ the pointer is initially placed at the beginning of the file and the pointer is at the end for w+
c) in w+ the pointer is initially placed at the beginning of the file and the pointer is at the end for r+
d) depends on the operating system

42. How do you get the name of a file from a file object (fp)?
a) fp.name
b) fp.file(name)
c) self.__name__(fp)
d) fp.__name__()

43. Which of the following is not a valid attribute of a file object (fp)?
a) fp.name
b) fp.closed
c) fp.mode
d) fp.size

44. How do you close a file object (fp)?


a) close(fp)
b) fclose(fp)

76 | P a g e
c) fp.close()
d) fp.__close__()

45. How do you get the current position within the file?
a) fp.seek()
b) fp.tell()
c) fp.loc
d) fp.pos

46. How do you rename a file?


a) fp.name = ‘new_name.txt’
b) os.rename(existing_name, new_name)
c) os.rename(fp, new_name)
d) os.set_name(existing_name, new_name)

47. How do you delete a file?


a) del(fp)
b) fp.delete()
c) os.remove(‘file’)
d) os.delete(‘file’)

48. How do you change the file position to an offset value from the start?
a) fp.seek(offset, 0)
b) fp.seek(offset, 1)
c) fp.seek(offset, 2)
d) none of the mentioned

49. What happens if no arguments are passed to the seek function?


a) file position is set to the start of file
b) file position is set to the end of file
c) file position remains unchanged
d) error

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. How many except statements can a 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:
# Do somethingexcept:
# Do somethingfinally:
# Do something
a) no, there is no such thing as finally

77 | P a g e
b) no, finally cannot be used with except
c) no, finally must come before except
d) yes

4. Is the following Python code valid?


try:
# Do somethingexcept:
# Do somethingelse:
# Do something
a) no, there is no such thing as else
b) no, else cannot be used with except
c) no, else must come before except
d) yes

5. Can one block of except statements handle multiple exception?


a) yes, like except TypeError, SyntaxError [,…]
b) yes, like except [TypeError, SyntaxError]
c) no
d) none of the mentioned

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

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


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

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


def foo():
try:
print(1)
finally:
print(2)
foo()
a) 1 2
b) 1
c) 2
d) none of the mentioned

9. What happens when ‘1’ == 1 is executed?


a) we get a True
b) we get a False

78 | P a g e
c) an TypeError occurs
d) a ValueError occurs

10. The following Python code will result in an error if the input value is entered as -5.
assert False, 'Spanish'
a) True
b) False

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


x=10
y=8assert x>y, 'X too small'
a) Assertion Error
b) 10 8
c) No output
d) 108

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


#generatordef f(x):
yield x+1
g=f(8)print(next(g))
a) 8
b) 9
c) 7
d) Error

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


def a():
try:
f(x, 4)
finally:
print('after f')
print('after f?')
a()
a) No output
b) after f?
c) error
d) after f

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


def f(x):
for i in range(5):
yield i
g=f(8)print(list(g))
a) [0, 1, 2, 3, 4]
b) [1, 2, 3, 4, 5, 6, 7, 8]
c) [1, 2, 3, 4, 5]
d) [0, 1, 2, 3, 4, 5, 6, 7]
Explanation: The output of the code shown above is a list containing whole numbers in the range (5).
Hence the output of this code is: [0, 1, 2, 3, 4].

15. The error displayed in the following Python code is?


import itertools
l1=(1, 2, 3)

79 | P a g e
l2=[4, 5, 6]
l=itertools.chain(l1, l2)print(next(l1))
a) ‘list’ object is not iterator
b) ‘tuple’ object is not iterator
c) ‘list’ object is iterator
d) ‘tuple’ object is iterator

16. Which of the following is not an exception handling keyword in Python?


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

17. What happens if the file is not found in the following Python code?
a=Falsewhile 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

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


lst = [1, 2, 3]
lst[3]
a) NameError
b) ValueError
c) IndexError
d) TypeError
19. What will be the output of the following Python code?
t[5]
a) IndexError
b) NameError
c) TypeError
d) ValeError

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

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


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

80 | P a g e
22. What will be the output of the following Python code if the input entered is 6?
valid = Falsewhile not valid:
try:
n=int(input("Enter a number"))
while n%2==0:
print("Bye")
valid = True
except ValueError:
print("Invalid")
a) Bye (printed once)
b) No output
c) Invalid (printed once)
d) Bye (printed infinite number of times)

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

24. Which of the following statements is true?


a) The standard exceptions are automatically imported into Python programs
b) All raised standard exceptions must be handled in Python
c) When there is a deviation from the rules of a programming language, a semantic error is thrown
d) If any exception is thrown in try block, else block is executed

25. Which of the following is not a standard exception in Python?


a) NameError
b) IOError
c) AssignmentError
d) ValueError

26. Syntax errors are also known as parsing errors.


a) True
b) False

27. An exception is ____________


a) an object
b) a special function
c) a standard module
d) a module

28. _______________________ exceptions are raised as a result of an error in opening a


particular file.
a) ValueError
b) TypeError
c) ImportError
d) IOError

29. Which of the following blocks will be executed whether an exception is thrown or not?
a) except

81 | P a g e
b) else
c) finally
d) assert

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

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of these definitions correctly describes a module?


a) Denoted by triple quotes for providing the specification of certain program elements
b) Design and implementation of specific functionality to be incorporated into a program
c) Defines the specification of how it is to be used
d) Any program that reuses code

2. Which of the following is not an advantage of using modules?


a) Provides a means of reuse of program code
b) Provides a means of dividing up tasks
c) Provides a means of reducing the size of the program
d) Provides a means of testing individual parts of the program

3. Program code making use of a given module is called a ______ of the module.
a) Client
b) Docstring
c) Interface
d) Modularity

4. ______ is a string literal denoted by triple quotes for providing the specifications of certain
program elements.
a) Interface
b) Modularity
c) Client
d) Docstring

5. Which of the following is true about top-down design process?


a) The details of a program design are addressed before the overall design
b) Only the details of the program are addressed
c) The overall design of the program is addressed before the details
d) Only the design of the program is addressed

6. In top-down design every module is broken into same number of submodules.


a) True
b) False

7. All modular designs are because of a top-down design process.


a) True
b) False

82 | P a g e
8. Which of the following isn’t true about main modules?
a) When a python file is directly executed, it is considered main module of a program
b) Main modules may import any number of modules
c) Special name given to main modules is: __main__
d) Other main modules can import main modules
.
9. Which of the following is not a valid namespace?
a) Global namespace
b) Public namespace
c) Built-in namespace
d) Local namespace

10. Which of the following is false about “import modulename” form of import?
a) The namespace of imported module becomes part of importing module
b) This form of import prevents name clash
c) The namespace of imported module becomes available to importing module
d) The identifiers in module are accessed as: modulename.identifier

11. Which of the following is false about “from-import” form of import?


a) The syntax is: from modulename import identifier
b) This form of import prevents name clash
c) The namespace of imported module becomes part of importing module
d) The identifiers in module are accessed directly as: identifier

12. Which of the statements about modules is false?


a) In the “from-import” form of import, identifiers beginning with two underscores are private and
aren’t imported
b) dir() built-in function monitors the items in the namespace of the main module
c) In the “from-import” form of import, all identifiers regardless of whether they are private or public
are imported
d) When a module is loaded, a compiled version of the module with file extension .pyc is
automatically produced

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


from math import factorialprint(math.factorial(5))
a) 120
b) Nothing is printed
c) Error, method factorial doesn’t exist in math module
d) Error, the statement should be: print(factorial(5))

14. What is the order of namespaces in which Python looks for an identifier?
a) Python first searches the global namespace, then the local namespace and finally the built-in
namespace
b) Python first searches the local namespace, then the global namespace and finally the built-in
namespace
c) Python first searches the built-in namespace, then the global namespace and finally the local
namespace
d) Python first searches the built-in namespace, then the local namespace and finally the global
namespace

83 | P a g e
1.b 2.c 3.a 4.d 5.c 6.b 7.b 8.d 9.b 10.a 11.b 12.c
13.d 14.b

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. _____ represents an entity in the real world with its identity and behaviour.
a) A method
b) An object
c) A class
d) An operator

2. _____ is used to create an object.


a) class
b) constructor
c) User-defined functions
d) In-built functions

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


class test:
def __init__(self,a="Hello World"):
self.a=a

def display(self):
print(self.a)
obj=test()
obj.display()
a) The program has an error because constructor can’t have default arguments
b) Nothing is displayed
c) “Hello World” is displayed
d) The program has an error display function doesn’t have parameters

4. What is setattr() used for?


a) To access the attribute of the object
b) To set an attribute
c) To check if an attribute exists or not
d) To delete an attribute

5. What is getattr() used for?


a) To access the attribute of the object
b) To delete an attribute
c) To check if an attribute exists or not
d) To set an attribute

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


class change:
def __init__(self, x, y, z):
self.a = x + y + z

x = change(1,2,3)
y = getattr(x, 'a')setattr(x, 'a', y+1)print(x.a)

84 | P a g e
a) 6
b) 7
c) Error
d) 0

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


class test:
def __init__(self,a):
self.a=a

def display(self):
print(self.a)
obj=test()
obj.display()
a) Runs normally, doesn’t display anything
b) Displays 0, which is the automatic default value
c) Error as one argument is required while creating the object
d) Error as display function requires additional argument

8. Is the following Python code correct?


>>> class A:
def __init__(self,b):
self.b=b
def display(self):
print(self.b)>>> obj=A("Hello")>>> del obj
a) True
b) False

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


class test:
def __init__(self):
self.variable = 'Old'
self.Change(self.variable)
def Change(self, var):
var = 'New'
obj=test()print(obj.variable)
a) Error because function change can’t be called in the __init__ function
b) ‘New’ is printed
c) ‘Old’ is printed
d) Nothing is printed

10. What is Instantiation in terms of OOP terminology?


a) Deleting an instance of class
b) Modifying an instance of class
c) Copying an instance of class
d) Creating an instance of class

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


class fruits:
def __init__(self, price):
self.price = price
obj=fruits(50)

85 | P a g e
obj.quantity=10
obj.bags=2
print(obj.quantity+len(obj.__dict__))
a) 12
b) 52
c) 13
d) 60

12. The assignment of more than one function to a particular operator is _______
a) Operator over-assignment
b) Operator overriding
c) Operator overloading
d) Operator instance

13. Which of the following is not a class method?


a) Non-static
b) Static
c) Bounded
d) Unbounded

14. Which of the following Python code creates an empty class?


a)
class A:
return
b)
class A:
pass
c)
class A:
d) It is not possible to create an empty class

15. What are the methods which begin and end with two underscore characters called?
a) Special methods
b) In-built methods
c) User-defined methods
d) Additional methods

16. Special methods need to be explicitly called during object creation.


a) True
b) False

17. Is the following Python code valid?


class B(object):
def first(self):
print("First method called")
def second():
print("Second method called")
ob = B()
B.first(ob)
a) It isn’t as the object declaration isn’t right
b) It isn’t as there isn’t any __init__ method for initializing class members
c) Yes, this method of calling is called unbounded method call

86 | P a g e
d) Yes, this method of calling is called bounded method call

18. What is hasattr(obj,name) used for?


a) To access the attribute of the object
b) To delete an attribute
c) To check if an attribute exists or not
d) To set an attribute
19. What is delattr(obj,name) used for?
a) To print deleted attribute
b) To delete an attribute
c) To check if an attribute is deleted or not
d) To set an attribute

20. __del__ method is used to destroy instances of a class.


a) True
b) False

21. What does print(Test.__name__) display (assuming Test is the name of the class)?
a) ()
b) Exception is thrown
c) Test
d) __main__

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


class stud:
def __init__(self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print("Roll no : ", self.roll_no, ", Grade: ", self.grade)
stud1 = stud(34, ‘S’)
stud1.age=7print(hasattr(stud1, 'age'))
a) Error as age isn’t defined
b) True
c) False
d) 7

ANSWERS :

1.b 2.b 3.c 4.b 5.a 6.b 7.c 8.a 9.c 10.d 11.c 12.c
13.a 14.b 15.a 16.b 17.c 18.c 19.b 20.a 21.c 22.a

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which of the following best describes inheritance?


a) Ability of a class to derive members of another class as a part of its own definition
b) Means of bundling instance variables and methods in order to restrict access to certain class
members
c) Focuses on variables and passing of variables to functions

87 | P a g e
d) Allows for implementation of elegant software that is well designed and easily modified

2. Which of the following statements is wrong about inheritance?


a) Protected members of a class can be inherited
b) The inheriting class is called a subclass
c) Private members of a class can be inherited and accessed
d) Inheritance is one of the features of OOP

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


class Demo:
def __new__(self):
self.__init__(self)
print("Demo's __new__() invoked")
def __init__(self):
print("Demo's __init__() invoked")class Derived_Demo(Demo):
def __new__(self):
print("Derived_Demo's __new__() invoked")
def __init__(self):
print("Derived_Demo's __init__() invoked")def main():
obj1 = Derived_Demo()
obj2 = Demo()
main()
a) Derived_Demo’s __init__() invoked
Derived_Demo's __new__() invoked
Demo's __init__() invoked
Demo's __new__() invoked
b) Derived_Demo's __new__() invoked
Demo's __init__() invoked
Demo's __new__() invoked
c) Derived_Demo's __new__() invoked
Demo's __new__() invoked
d) Derived_Demo’s __init__() invoked
Demo's __init__() invoked

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


class Test:
def __init__(self):
self.x = 0class Derived_Test(Test):
def __init__(self):
self.y = 1def main():
b = Derived_Test()
print(b.x,b.y)
main()
a) 0 1
b) 0 0
c) Error because class B inherits A but variable x isn’t inherited
d) Error because when object is created, argument must be passed like Derived_Test(1)

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


class A():
def disp(self):
print("A disp()")class B(A):

88 | P a g e
pass
obj = B()
obj.disp()
a) Invalid syntax for inheritance
b) Error because when object is created, argument must be passed
c) Nothing is printed
d) A disp()

6. All subclasses are a subtype in object-oriented programming.


a) True
b) False

7. When defining a subclass in Python that is meant to serve as a subtype, the subtype Python
keyword is used.
a) True
b) False

8. Suppose B is a subclass of A, to invoke the __init__ method in A from B, what is the line of
code you should write?
a) A.__init__(self)
b) B.__init__(self)
c) A.__init__(B)
d) B.__init__(A)

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


class Test:
def __init__(self):
self.x = 0class Derived_Test(Test):
def __init__(self):
Test.__init__(self)
self.y = 1def main():
b = Derived_Test()
print(b.x,b.y)
main()
a) Error because class B inherits A but variable x isn’t inherited
b) 0 0
c) 0 1
d) Error, the syntax of the invoking method is wrong

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


class A:
def __init__(self, x= 1):
self.x = xclass der(A):
def __init__(self,y = 2):
super().__init__()
self.y = ydef main():
obj = der()
print(obj.x, obj.y)
main()
a) Error, the syntax of the invoking method is wrong
b) The program runs fine but nothing is printed
c) 1 0
d) 1 2

89 | P a g e
11. What does built-in function type do in context of classes?
a) Determines the object name of any value
b) Determines the class name of any value
c) Determines class description of any value
d) Determines the file name of any value

12. Which of the following is not a type of inheritance?


a) Double-level
b) Multi-level
c) Single-level
d) Multiple

13. What does built-in function help do in context of classes?


a) Determines the object name of any value
b) Determines the class identifiers of any value
c) Determines class description of any built-in type
d) Determines class description of any user-defined built-in type

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


class A:
def one(self):
return self.two()

def two(self):
return 'A'
class B(A):
def two(self):
return 'B'
obj1=A()
obj2=B()print(obj1.two(),obj2.two())
a) A A
b) A B
c) B B
d) An exception is thrown

15. What type of inheritance is illustrated in the following Python code?


class A():
passclass B():
passclass C(A,B):
pass
a) Multi-level inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Single-level inheritance

16. What type of inheritance is illustrated in the following Python code?


class A():
passclass B(A):
passclass C(B):
pass
a) Multi-level inheritance
b) Multiple inheritance

90 | P a g e
c) Hierarchical inheritance
d) Single-level inheritance

17. What does single-level inheritance mean?


a) A subclass derives from a class which in turn derives from another class
b) A single superclass inherits from multiple subclasses
c) A single subclass derives from a single superclass
d) Multiple base classes inherit a single derived class

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


class A:
def __init__(self):
self.__i = 1
self.j = 5

def display(self):
print(self.__i, self.j)class B(A):
def __init__(self):
super().__init__()
self.__i = 2
self.j = 7
c = B()
c.display()
a) 2 7
b) 1 5
c) 1 7
d) 2 5

19. Which of the following statements isn’t true?


a) A non-private method in a superclass can be overridden
b) A derived class is a subset of superclass
c) The value of a private variable in the superclass can be changed in the subclass
d) When invoking the constructor from a subclass, the constructor of superclass is automatically
invoked

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


>>> class A:
pass>>> class B(A):
pass>>> obj=B()>>> isinstance(obj,A)
a) True
b) False
c) Wrong syntax for isinstance() method
d) Invalid method for classes

21. Which of the following statements is true?


a) The __new__() method automatically invokes the __init__ method
b) The __init__ method is defined in the object class
c) The __eq(other) method is defined in the object class
d) The __repr__() method is defined in the object class

22. Method issubclass() checks if a class is a subclass of another class.


a) True
b) False

91 | P a g e
23. What will be the output of the following Python code?
class A:
def __init__(self):
self.__x = 1class B(A):
def display(self):
print(self.__x)def main():
obj = B()
obj.display()
main()
a) 1
b) 0
c) Error, invalid syntax for object declaration
d) Error, private class member can’t be accessed in a subclass

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


class A:
def __init__(self):
self._x = 5 class B(A):
def display(self):
print(self._x)def main():
obj = B()
obj.display()
main()
a) Error, invalid syntax for object declaration
b) Nothing is printed
c) 5
d) Error, private class member can’t be accessed in a subclass

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


class A:
def __init__(self,x=3):
self._x = x class B(A):
def __init__(self):
super().__init__(5)
def display(self):
print(self._x)def main():
obj = B()
obj.display()

main()
a) 5
b) Error, class member x has two values
c) 3
d) Error, protected class member can’t be accessed in a subclass
View Answer
26. What will be the output of the following Python code?
class A:
def test1(self):
print(" test of A called ")class B(A):
def test(self):
print(" test of B called ")class C(A):
def test(self):

92 | P a g e
print(" test of C called ")class D(B,C):
def test2(self):
print(" test of D called ")
obj=D()
obj.test()
a)
test of B called
test of C called
b)
test of C called
test of B called
c) test of B called
d) Error, both the classes from which D derives has same method test()

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


class A:
def test(self):
print("test of A called")class B(A):
def test(self):
print("test of B called")
super().test() class C(A):
def test(self):
print("test of C called")
super().test()class D(B,C):
def test2(self):
print("test of D called")
obj=D()
obj.test()

a) test of B called
test of C called
test of A called
b) test of C called
test of B called
c) test of B called
test of C called
d) Error, all the three classes from which D derives has same method test()

1.a 2.c 3.b 4.c 5.d 6.b 7.b 8.a 9.c 10.d 11.b 12.a 13.c 14.b
15.b 16.a 17.c 18.c 19.c 20.a 21.c 22.a 23.d 24.c 25.a 26.c
27.a

93 | P a g e
UNIT V

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Which is the most appropriate definition for recursion?


a) A function that calls itself
b) A function execution instance that calls another execution instance of the same function
c) A class method that calls another class method
d) An in-built method that is automatically called

2. Only problems that are recursively defined can be solved using recursion.

94 | P a g e
a)True
b) False

3. Which of these is false about recursion?


a) Recursive function can be replaced by a non-recursive function
b) Recursive functions usually take more memory space than non-recursive function
c) Recursive functions run faster than non-recursive function
d) Recursion makes programs easier to understand

4. Fill in the line of the following Python code for calculating the factorial of a number.
def fact(num):
if num == 0:
return 1
else:
return _____________________
a) num*fact(num-1)
b) (num-1)*(num-2)
c) num*(num-1)
d) fact(num)*fact(num-1)

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


def test(i,j):
if(i==0):
return j
else:
return test(i-1,i+j)
print(test(4,7))

a) 13
b) 7
c) Infinite loop
d) 17

6. What is tail recursion?


a) A recursive function that has two base cases
b) A function where the recursive functions leads to an infinite loop
c) A recursive function where the function doesn’t return anything and just prints the values
d) A function where the recursive call is the last thing executed by the function

7. Which of the following statements is false about recursion?


a) Every recursive function must have a base case
b) Infinite recursion can occur if the base case isn’t properly mentioned
c) A recursive function makes the code easier to understand
d) Every recursive function must have a return value

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


def fun(n):
if (n > 100):
return n - 5
return fun(fun(n+11));
print(fun(45))

a) 50

95 | P a g e
b) 100
c) 74
d) Infinite loop

9. Recursion and iteration are the same programming approach.


a)True
b) False

10. What happens if the base condition isn’t defined in recursive programs?
a) Program gets into an infinite loop
b) Program runs once
c) Program runs n number of times where n is the argument given to the function
d) An exception is thrown

11. Which of these is not true about recursion?


a) Making the code look clean
b) A complex task can be broken into sub-problems
c) Recursive calls take up less memory
d) Sequence generation is easier than a nested iteration

12. Which of these is not true about recursion?


a) It’s easier to code some real-world problems using recursion than non-recursive equivalent
b) Recursive functions are easy to debug
c) Recursive calls take up a lot of memory
d) Programs using recursion take longer time than their non-recursive equivalent

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


def a(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return a(n-1)+a(n-2)
for i in range(0,4):
print(a(i),end=" ")

a) 0 1 2 3
b) An exception is thrown
c) 0 1 1 2 3
d) 0 1 1 2

14. Suppose the first fibonnaci number is 0 and the second is 1. What is the sixth
fibonnaci number?
a) 5
b) 6
c) 7
d) 8

96 | P a g e
15. Which of the following is not a fibonnaci number?
a) 8
b) 21
c) 55
d) 14

16. Which of the following option is wrong?


a) Fibonacci number can be calculated by using Dynamic programming
b) Fibonacci number can be calculated by using Recursion method
c) Fibonacci number can be calculated by using Iteration method
d) No method is defined to calculate Fibonacci number.

17. Which of the following recurrence relations can be used to find the nth fibonacci
number?
a) F(n) = F(n) + F(n – 1)
b) F(n) = F(n) + F(n + 1)
c) F(n) = F(n – 1)
d) F(n) = F(n – 1) + F(n – 2)

18. How many times will the function fibo() be called when the following code is executed?
int fibo(int n){
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);}int main(){
int n = 5;
int ans = fibo(n);
printf("%d",ans);
return 0;}
a) 5
b) 6
c) 8
d) 9\
19. What is the output of the following code?
int fibo(int n){
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);}int main(){
int n = 10;
int ans = fibo(n);
printf("%d",ans);
return 0;}
a) 21
b) 34
c) 55
d) 13

97 | P a g e
20. What is the output of the following code?
int fibo(int n){
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);}int main(){
int n = 5;
int ans = fibo(n);
printf("%d",ans);
return 0;}
a) 1
b) 2
c) 3
d) 5

21. What is the objective of tower of hanoi puzzle?


a) To move all disks to some other rod by following rules
b) To divide the disks equally among the three rods by following rules
c) To move all disks to some other rod in random order
d) To divide the disks equally among three rods in random order

22. Which of the following is NOT a rule of tower of hanoi puzzle?


a) No disk should be placed over a smaller disk
b) Disk can only be moved if it is the uppermost disk of the stack
c) No disk should be placed over a larger disk
d) Only one disk can be moved at a time

23. The time complexity of the solution tower of hanoi problem using recursion is _________
a) O(n2)
b) O(2n)
c) O(n log n)
d) O(n)

24. Recurrence equation formed for the tower of hanoi problem is given by _________
a) T(n) = 2T(n-1)+n
b) T(n) = 2T(n/2)+c
c) T(n) = 2T(n-1)+c
d) T(n) = 2T(n/2)+n

25. Minimum number of moves required to solve a tower of hanoi problem with n disks is
__________
a) 2n
b) 2n-1
c) n2
d) n2-1

26. Space complexity of recursive solution of tower of hanoi puzzle is ________


a) O(1)
b) O(n)
c) O(log n)

98 | P a g e
d) O(n log n)

27. Recursive solution of tower of hanoi problem is an example of which of the


following algorithm?
a) Dynamic programming
b) Backtracking
c) Greedy algorithm
d) Divide and conquer

28. Tower of hanoi problem can be solved iteratively.


a) True
b) False

29. Minimum time required to solve tower of hanoi puzzle with 4 disks assuming one
move takes 2 seconds, will be __________
a) 15 seconds
b) 30 seconds
c) 16 seconds
d) 32 seconds

ANSWERS :

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

 MULTIPLE CHOICE QUESTIONS ANSWERS

1. Where is linear searching used?


a) When the list has only a few elements
b) When performing a single search in an unordered list
c) Used all the time
d) When the list has only a few elements and When performing a single search in an unordered list.

2. What is the best case for linear search?


a) O(nlogn)
b) O(logn)
c) O(n)

99 | P a g e
d) O(1)

3. What is the worst case for linear search?


a) O(nlogn)
b) O(logn)
c) O(n)
d) O(1)

4. What is the best case and worst case complexity of ordered linear search?
a) O(nlogn), O(logn)
b) O(logn), O(nlogn)
c) O(n), O(1)
d) O(1), O(n)

5. Which of the following is a disadvantage of linear search?


a) Requires more space
b) Greater time complexities compared to other searching algorithms
c) Not easy to understand
d) Not easy to implement
6. Is there any difference in the speed of execution between linear serach(recursive)
vs linear search(lterative)?
a) Both execute at same speed
b) Linear search(recursive) is faster
c) Linear search(Iterative) is faster
d) Cant be said

7. Is the space consumed by the linear search(recursive) and linear search(iterative)


same?
a) No, recursive algorithm consumes more space
b) No, recursive algorithm consumes less space
c) Yes
d) Nothing can be said

8. What is the worst case runtime of linear search(recursive) algorithm?


a) O(n)
b) O(logn)
c) O(n2)
d) O(nx)

9. Linear search(recursive) algorithm used in _____________


a) When the size of the dataset is low
b) When the size of the dataset is large
c) When the dataset is unordered
d) Never used

10. The array is as follows: 1,2,3,6,8,10. At what time the element 6 is found? (By

100 | P a g e
using linear search(recursive) algorithm)
a) 4th call
b) 3rd call
c) 6th call
d) 5th call

11. The array is as follows: 1,2,3,6,8,10. Given that the number 17 is to be searched.
At which call it tells that there’s no such element? (By using linear search(recursive)
algorithm)
a) 7th call
b) 9th call
c) 17th call
d) The function calls itself infinite number of times

12. What is the best case runtime of linear search(recursive) algorithm on an


ordered set of elements?
a) O(1)
b) O(n)
c) O(logn)
d) O(nx)

13. Can linear search recursive algorithm and binary search recursive algorithm be
performed on an unordered list?
a) Binary search can’t be used
b) Linear search can’t be used
c) Both cannot be used
d) Both can be used

14. What is the recurrence relation for the linear search recursive algorithm?
a) T(n-2)+c
b) 2T(n-1)+c
c) T(n-1)+c
d) T(n+1)+c

15. What is the advantage of recursive approach than an iterative approach?


a) Consumes less memory
b) Less code and easy to implement
c) Consumes more memory
d) More code has to be written

16. Given an input arr = {2,5,7,99,899}; key = 899; What is the level of recursion?
a) 5
b) 2
c) 3
d) 4

101 | P a g e
17. Given an array arr = {45,77,89,90,94,99,100} and key = 99; what are the mid
values(corresponding array elements) in the first and second levels of recursion?
a) 90 and 99
b) 90 and 94
c) 89 and 99
d) 89 and 94

18. What is the worst case complexity of binary search using recursion?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

19. What is the average case time complexity of binary search using recursion?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

20. Which of the following is not an application of binary search?


a) To find the lower/upper bound in an ordered sequence
b) Union of intervals
c) Debugging
d) To search in unordered list.

21. Binary Search can be categorized into which of the following?


a) Brute Force technique
b) Divide and conquer
c) Greedy algorithm
d) Dynamic programming

22. Given an array arr = {5,6,77,88,99} and key = 88; How many iterations are done
until the element is found?
a) 1
b) 3
c) 4
d) 2

23. Given an array arr = {45,77,89,90,94,99,100} and key = 100; What are the mid
values(corresponding array elements) generated in the first and second iterations?
a) 90 and 99
b) 90 and 100
c) 89 and 94
d) 94 and 99

24. What is the time complexity of binary search with iteration?

102 | P a g e
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

ANSWERS :

1.d 2.d 3.c 4.d 5.b 6.c 7.a 8.a 9.a 10.a 11.a 12.a 13.a 14.c
15.b 16.c 17.a 18.b 19.b 20.d 21.b 22.d 23.a 24.b

 MULTIPLE CHOICE QUESTIONS ANSWERS

1.What is an in-place sorting algorithm?


a) It needs O(1) or O(logn) memory to create auxiliary locations
b) The input is already sorted and in-place
c) It requires additional storage
d) It requires additional space

2. In the following scenarios, when will you use selection sort?


a) The input is already sorted
b) A large file has to be sorted
c) Large values need to be sorted with small keys
d) Small values need to be sorted with large keys

3. What is the worst case complexity of selection sort?


a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

4. What is the advantage of selection sort over other sorting techniques?


a) It requires no additional storage space
b) It is scalable
c) It works best for inputs which are already sorted
d) It is faster than any other sorting technique

5. What is the average case complexity of selection sort?


a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

6. What is the disadvantage of selection sort?


a) It requires auxiliary memory
b) It is not scalable

103 | P a g e
c) It can be used for small keys
d) It takes linear time to sort the elements

7. The given array is arr = {3,4,5,2,1}. The number of iterations in bubble sort and
selection sort respectively are,
a) 5 and 4
b) 4 and 5
c) 2 and 4
d) 2 and 5

8. The given array is arr = {1,2,3,4,5}. (bubble sort is implemented with a flag
variable)The number of iterations in selection sort and bubble sort respectively are,
a) 5 and 4
b) 1 and 4
c) 0 and 4
d) 4 and 1

9. What is the best case complexity of selection sort?


a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

10. Merge sort uses which of the following technique to implement sorting?
a) backtracking
b) greedy algorithm
c) divide and conquer
d) dynamic programming

11. What is the average case time complexity of merge sort?


a) O(n log n)
b) O(n2)
c) O(n2 聽 log n)
d) O(n log n2)
12. What is the auxiliary space complexity of merge sort?
a) O(1)
b) O(log n)
c) O(n)
d) O(n log n)

13. Merge sort can be implemented using O(1) auxiliary space.


a) true
b) false

14. What is the worst case time complexity of merge sort?


a) O(n log n)

104 | P a g e
b) O(n2)
c) O(n2log n)
d) O(n log n2)

15. Which of the following method is used for sorting in merge sort?
a) merging
b) partitioning
c) selection
d) exchanging

16. What will be the best case time complexity of merge sort?
a) O(n log n)
b) O(n2)
c) O(n2 log n)
d) O(n log n2)

17. Which of the following is not a variant of merge sort?


a) in-place merge sort
b) bottom up merge sort
c) top down merge sort
d) linear merge sort

18. Choose the incorrect statement about merge sort from the following?
a) it is a comparison based sort
b) it is an adaptive algorithm
c) it is not an in place algorithm
d) it is stable algorithm

19. Which of the following is not in place sorting algorithm?


a) merge sort
b) quick sort
c) heap sort
d) insertion sort

20. Which of the following is not a stable sorting algorithm?


a) Quick sort
b) Cocktail sort
c) Bubble sort
d) Merge sort

21. Which of the following stable sorting algorithm takes the least time when applied
to an almost sorted array?
a) Quick sort
b) Insertion sort
c) Selection sort
d) Merge sort

105 | P a g e
22. Merge sort is preferred for arrays over linked lists.
a) true
b) false

23. Which of the following sorting algorithm makes use of merge sort?
a) tim sort
b) intro sort
c) bogo sort
d) quick sort

24. Which of the following sorting algorithm does not use recursion?
a) quick sort
b) merge sort
c) heap sort
d) bottom up merge sort

ANSWERS :
1.a 2.c 3.d 4.a 5.d 6.b 7.a 8.d 9.d 10.c
11.a 12.c 13.a 14.a 15.a 16.a 17.a 18.b 19.a
20.a 21.d 22.b 23.a 24.d

106 | P a g e
→Telegram Channel 
→Telegram Group

You might also like