Python MCQ 3
Python MCQ 3
Datatypes
This set of Python Questions & Answers focuses on “Core Data Types”.
Answer:d
Explanation:Class is a user defined datatype.
2. Given a function that does not return any value, What value is thrown by itby default when
executed in shell.
a) int
b) bool
c) void
d) None
View Answer
Answer:d
Explanation:Python shell throws a NoneType object back.
3. Following set of commands are executed in shell, what will be the output?
1. >>>str="hello"
2. >>>str[:2]
3. >>>
a) he
b) lo
c) olleh
d) hello
View Answer
Answer:a
Explanation:We are printing only the 1st two bytes of string and hence the answer is “he”.
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
advertisements
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) x = 13 % 2
View Answer
Answer:a,b
Explanation:// is integer operation in python 3.0 and int(..) is a type cast operator.
Answer:b
Explanation:Banana is not defined hence name error.
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
View Answer
Answer:a
Explanation:Python codes have to be indented properly.
Answer:a
Explanation:List datatype can store any values within it.
10. In order to store values in terms of key and value we use what core datatype.
a) List
b) tuple
c) class
d) dictionary
View Answer
Answer:d
Explanation:Dictionary stores values in terms of keys and values.
Answer:b,c
Explanation:Carefully look at the colons.
1. tom
2. dick
3. harry
advertisements
Select all of the function calls that result in this output
a) print(”’tom
\ndick
\nharry”’)
b) print(”’tom
dick
harry”’)
c) print(‘tom\ndick\nharry’)
d) print(‘tom
dick
harry’)
View Answer
Answer:b,c
Explanation:The \n adds a new line.
13. What is the average value of the code that is executed below ?
1. >>>grade1 = 80
2. >>>grade2 = 90
3. >>>average = (grade1 + grade2) / 2
a) 85
b) 85.0
c) 95
d) 95.0
View Answer
Answer:b
Explanation:Cause a decimal value to appear as output.
Answer:c,d
Explanation:Execute in the shell.
Answer:a
Explanation:Executle help(math.trunc) to get details.
Answer: b
Explanation: In python, power operator is x**y i.e. 2**3=8.
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.
Answer: a
Explanation: For order of precedence, just remember this PEDMAS.
advertisements
Answer: b
Explanation: You can’t perform mathematical operation on string even if string looks like integers.
Answer: a
Explanation: None.
Answer: c
Explanation: First this expression will solve 1**3 because exponential have higher precedence than
multiplication, so 1**3 = 1 and 3*1 = 3. Final answer is 3.
Answer: c
Explanation: None.
Answer: a
Explanation: None.
advertisements
10. Which one of the following have the highest precedence in the expression?
a) Exponential
b) Addition
c) Multiplication
d) Parentheses
View Answer
Answer: d
Explanation: None.
Answer: a
Explanation: Case is always significant.
Answer: d
Explanation: Identifiers can be of any length.
advertisements
Answer: b
Explanation: Variable names should not start with a number.
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.
Answer: a
Explanation: eval can be used as a variable.
Answer: d
Explanation: True, False and None are capitalized while the others are in lower case.
Answer: a
Explanation: Variable names can be of any length.
advertisements
Answer: b
Explanation: Spaces are not allowed in variable names.
Answer: b
Explanation: in is a keyword.
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)
View Answer
Answer: c
Explanation: It converts a given string into a pattern object.
Answer: a
Explanation: It will look for the pattern at the beginning and return None if it isn’t found.
Answer: b
Explanation: It will look for the pattern at any position in the string.
Answer: a
Explanation: This function returns all the subgroups that have been matched.
advertisements
Answer: d
Explanation: This function returns the entire match.
a) ‘are’
b) ‘we’
c) ‘humans’
d) ‘we are humans’
View Answer
Answer: c
Explanation: This function returns the particular subgroup.
Answer: a
Explanation: This function returns a dictionary that contains all the mathches.
advertisements
Answer: b
Explanation: This function returns all the subgroups that have been matched.
Answer: d
Explanation: This function returns the particular subgroup.
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.
Answer: c
Explanation: l (or L) stands for long.
advertisements
Answer: c
Explanation: Infinity is a special case of floating point numbers. It can be obtained by float(‘inf’).
Answer: a
Explanation: ~x is equivalent to -(x+1).
Answer: a
Explanation: ~x is equivalent to -(x+1).
advertisements
x = ['ab', 'cd']
for i in x:
i.upper()
print(x)
Answer: a
Explanation: The function upper() does not modify a string in place, it returns a new string which
isn’t being stored anywhere.
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
View Answer
Answer: d
Explanation: The loop does not terminate as new elements are being added to the list in each
iteration.
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
View Answer
Answer: c
Explanation: SyntaxError, there shouldn’t be a space between + and = in +=.
i = 1
while True:
if i%0O7 == 0:
break
print(i)
i += 1
advertisements
a) 1 2 3 4 5 6
b) 1 2 3 4 5 6 7
c) error
d) none of the mentioned
View Answer
Answer: a
Explanation: Control exits the loop when i becomes 7.
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
View Answer
Answer: b
Explanation: 0O11 is an octal number.
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
View Answer
Answer: d
Explanation: 9 isn’t allowed in an octal number.
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 …
View Answer
Answer: d
Explanation: The loop does not terminate since i is never an even number.
advertisements
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
View Answer
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.
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
View Answer
Answer: d
Explanation: Control does not enter the loop because of False.
True = False
while True:
print(True)
break
a) True
b) False
c) None
d) none of the mentioned
View Answer
Answer: d
Explanation: SyntaxError, True is a keyword and it’s value cannot be changed.
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
View Answer
Answer: b
Explanation: The else part is not executed if control breaks out of the loop.
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
c) error
View Answer
Answer: b
Explanation: The else part is executed when the condition in the while statement is false.
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
View Answer
Answer: d
Explanation: NameError, i is not defined.
x = "abcdef"
i = "i"
while i in x:
print(i, end=" ")
advertisements
a) no output
b) i i i i i i …
c) a b c d e f
d) abcdef
View Answer
Answer: a
Explanation: “i” is not in “abcdef”.
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
View Answer
Answer: c
Explanation: As the value of i or x isn’t changing, the condition will always evaluate to True.
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
View Answer
Answer: b
Explanation: As the value of i or x isn’t changing, the condition will always evaluate to True.
7. What is the output of the following?
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
View Answer
Answer: b
Explanation: The string x is being shortened by one charater in each iteration.
advertisements
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
View Answer
Answer: c
Explanation: String x is not being altered and i is in x[:-1].
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
View Answer
Answer: b
Explanation: The string x is being shortened by one charater in each iteration.
10. What is the output of the following?
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
View Answer
Answer: c
Explanation: i is not in x[1:].
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
View Answer
Answer: b
Explanation: Changes do not happen in-place, rather a new instance of the string is returned.
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
View Answer
Answer: b
Explanation: The instance of the string returned by upper() is being printed.
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
View Answer
Answer: c
Explanation: range(str) is not allowed.
x = 'abcd'
for i in range(len(x)):
print(i)
advertisements
a) a b c d
b) 0 1 2 3
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: i takes values 0, 1, 2 and 3.
x = 'abcd'
for i in range(len(x)):
print(i.upper())
a) a b c d
b) 0 1 2 3
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: Objects of type int have no attribute upper().
a) a b c d
b) 0 1 2 3
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: Objects of type int have no attribute upper().
x = 'abcd'
for i in range(len(x)):
x[i].upper()
print (x)
a) abcd
b) ABCD
c) error
d) none of the mentioned
View Answer
Answer: a
Explanation: Changes do not happen in-place, rather a new instance of the string is returned.
advertisements
x = 'abcd'
for i in range(len(x)):
i[x].upper()
print (x)
a) abcd
b) ABCD
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: Objects of type int aren’t subscriptable.
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
View Answer
Answer: c
Explanation: range() is computed only at the time of entering the loop.
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
View Answer
Answer: d
Explanation: abcd a a a is the output as x is modified only after ‘abcd’ has been printed once.
x = 123
for i in x:
print(i)
a) 1 2 3
b) 123
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: Objects of type int are not iterable.
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
View Answer
Answer: a
Explanation: Loops over the keys of the dictionary.
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
View Answer
Answer: d
Explanation: Error, objects of type int aren’t iterable.
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
View Answer
Answer: c
Explanation: Loops over key, value pairs.
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
View Answer
Answer: b
Explanation: Loops over the keys and prints the values.
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
View Answer
Answer: b
Explanation: Loops over the values.
a) 0 1 2
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
View Answer
Answer: d
Explanation: Causes a KeyError.
d = {0, 1, 2}
for x in d.values():
print(x)
advertisements
a) 0 1 2
b) None None None
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: Objects of type set have no attribute values.
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
View Answer
Answer: a
Explanation: Loops over the elements of the set and prints them.
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
View Answer
Answer: c
Explanation: Variable x takes the values 0, 1 and 2. set.add() returns None which is printed.
for i in range(0):
print(i)
a) 0
b) (nothing is printed)
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: range(0) is empty.
for i in range(2.0):
print(i)
a) 0.0 1.0
b) 0 1
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: Object of type float cannot be interpreted as an integer.
for i in range(int(2.0)):
print(i)
a) 0.0 1.0
b) 0 1
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: range(int(2.0)) is the same as range(2).
for i in range(float('inf')):
print (i)
Answer: d
Explanation: Error, objects of type float cannot be interpreted as an integer.
for i in range(int(float('inf'))):
print (i)
advertisements
Answer: d
Explanation: OverflowError, cannot convert float infinity to integer.
a) 1 2 3 4
b) 4 3 2 1
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: [::-1] reverses the list.
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
View Answer
Answer: b
Explanation: ”.join(reversed(list(‘abcd’))) reverses a string.
a) a b c d
b) d c b a
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: [::-1] reverses the string.
advertisements
for i in '':
print (i)
a) None
b) (nothing is printed)
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: The string does not have any character to loop over.
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
View Answer
Answer: c
Explanation: Variable x is incremented and printed twice.
x = 2
for i in range(x):
x -= 2
print (x)
a) 0 1 2 3 4 …
b) 0 -2
c) 0
d) error
View Answer
Answer: b
Explanation: The loop is entered twice.
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
View Answer
Answer: c
Explanation: The else part is executed if control doesn’t break out of the loop.
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
View Answer
Answer: a
Explanation: The else part is executed if control doesn’t break out of the loop.
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
View Answer
Answer: a
Explanation: The first statement creates a generator object.
x = (i for i in range(3))
for i in x:
print(i)
for i in x:
print(i)
advertisements
a) 0 1 2
b) error
c) 0 1 2 0 1 2
d) none of the mentioned
View Answer
Answer: a
Explanation: We can loop over a generator object only once.
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
View Answer
Answer: a
Explanation: Variable i takes the value of one character at a time.
6. What is the output of the following?
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
View Answer
Answer: c
Explanation: Variable i takes the value of one word at a time.
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
View Answer
Answer: b
Explanation: The value of a[-1] changes in each iteration.
advertisements
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
View Answer
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.
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
View Answer
Answer: c
Explanation: SyntaxError, not in isn’t allowed in for loops.
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
View Answer
Answer: a
Explanation: Variable i takes the value of one character at a time.
1. >>>"a"+"bc"
a) a
b) bc
c) bca
d) abc
View Answer
Answer:d
Explanation:+ operator is concatenation operator.
a) a
b) ab
c) cd
d) dc
View Answer
Answer:c
Explanation:Slice operation is performed on string.
Answer:b
Explanation:Execute in shell and check.
Answer:c,d
Explanation:+ is used to concatenate and * is used to multiply strings.
1. >>>print r"\nhello"
The output is
a) a new line and hello
b) \nhello
c) the letter r and then hello
d) Error
View Answer
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.
a) Error
b) Output equivalent to print ‘new\nline’
c) newline
d) new line
View Answer
Answer:c
Explanation:String literals seperated by white space are allowed. They are concatenated.
advertisements
8. What is the output when following statement is executed ?
1. >>>print '\x97\x98'
a) Error
b) 97
98
c) _~
d) \x97\x98
View Answer
Answer:c
Explanation:\x is an escape sequence that means the following 2 digits are a hexadicmal
number encoding a character.
1. >>>str1="helloworld"
2. >>>str1[::-1]
a) dlrowolleh
b) hello
c) world
d) helloworld
View Answer
Answer:a
Explanation:Execute in shell to verify.
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.
1. class father:
2. def __init__(self, param):
3. self.o1 = param
4.
5. class child(father):
6. def __init__(self, param):
7. self.o2 = param
8.
9. >>>obj = child(22)
10. >>>print "%d %d" % (obj.o1, obj.o2)
a) None None
b) None 22
c) 22 None
d) Error is generated
View Answer
Answer:d
Explanation:self.o1 was never created.
1. class tester:
2. def __init__(self, id):
3. self.id = str(id)
4. id="224"
5.
6. >>>temp = tester(12)
7. >>>print temp.id
a) 224
b) Error
c) 12
d) None
View Answer
Answer:c
Explanation:id in this case will be the attribute of the class.
a) wo
b) world
c) sn
d) rl
View Answer
Answer:a
Explanation:Execute in the shell and verify.
advertisements
4. What is the output of the following code ?
1. >>>example = "snow world"
2. >>>example[3] = 's'
3. >>>print example
a) snow
b) snow world
c) Error
d) snos world
View Answer
Answer:c
Explanation:Strings cannot be modified.
a) Error
b) u
c) t
d) y
View Answer
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
View Answer
Answer:a
Explanation:l occurs twice in hello.
1. >>>example = "helle"
2. >>>example.find("e")
advertisements
a) Error
b) -1
c) 1
d) 0
View Answer
Answer:c
Explanation:returns lowest index .
1. >>>example = "helle"
2. >>>example.rfind("e")
a) -1
b) 4
c) 3
d) 1
View Answer
Answer:b
Explanation:returns highest index.
1. >>>example="helloworld"
2. >>>example[::-1].startswith("d")
a) dlrowolleh
b) True
c) -1
d) None
View Answer
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 (multiple answers are
allowed) ?
a) s3 = s1 + s2
b) s3 = s1.add(s2)
c) s3 = s1.__add__(s2)
d) s3 = s1 * s2
View Answer
Answer:a,c
Explanation:__add__ is another method that can be used for concatenation.
1. >>>chr(ord('A'))
a) A
b) B
c) a
d) Error
View Answer
Answer:a
Explanation:Execute in shell to verify.
1. >>>print(chr(ord('b')+1))
a) a
b) b
c) c
d) A
View Answer
Answer:c
Explanation:Execute in the shell to verify.
advertisements
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”)
View Answer
Answer:b
Explanation:\is used to indicate that the next \ is not an escape sequence.
Answer:d
Explanation:Execute help(string.strip) to find details.
Answer:d
Explanation:Format function returns a string.
Answer:c
Explanation:Cannot concantenate str and int objects.
a) DCBA
b) A, B, C, D
c) D C B A
d) A, B, C, D will be displayed on four lines
View Answer
Answer:c
Explanation:Execute in the shell.
advertisements
8. What is the output when following statement is executed ?(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
View Answer
Answer:d
Explanation:Execute in the shell to verify.
Answer:b
Explanation:ascii value of b is one more than a.
Answer:c
Explanation:str is used to represent strings in python.
2. To retrieve the character at index 3 from string s=”Hello” what command do we execute
(multiple answers allowed) ?
a) s[3] b) s.getitem(3)
c) s.__getitem__(3)
d) s.getItem(3)
View Answer
Answer:a, 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 (multiple answers allowed) ?
a) s.__len__()
b) len(s)
c) size(s)
d) s.size()
View Answer
Answer:a,b
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.(multiple answers allowed)
a) obj.__str__()
b) str(obj)
c) print obj
d) __str__(obj)
View Answer
Answer:a,b,c
Explanation:Execute in shell to verify.
Answer:a,b
Explanation:s1 in s2 works in the same way as calling the special function __contains__ .
advertisements
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)
View Answer
Answer:b
Explanation:Execute in shell to verify.
1. class Count:
2. def __init__(self, count = 0):
3. self.__count = count
4.
5. c1 = Count(2)
6. c2 = Count(2)
7. print(id(c1) == id(c2), end = " ")
8.
9. s1 = "Good"
10. s2 = "Good"
11. print(id(s1) == id(s2))
a) True False
b) True True
c) False True
d) False False
View Answer
Answer:c
Explanation:Execute in the shell objects cannot have same id, however in the case of strings
its different.
1. class Name:
2. def __init__(self, firstName, mi, lastName):
3. self.firstName = firstName
4. self.mi = mi
5. self.lastName = lastName
6.
7. firstName = "John"
8. name = Name(firstName, 'F', "Smith")
9. firstName = "Peter"
10. name.lastName = "Pan"
11. print(name.firstName, name.lastName)
advertisements
a) Peter Pan.
b) John Pan.
c) Peter Smith.
d) John Smith.
View Answer
Answer:b
Explanation:Execute in the shell to verify.
Answer:a
Explanation:Execute in shell to verify.
Answer:b
Explanation:Execute in the shell to verify.
print("abc DEF".capitalize())
a) abc def
b) ABC DEF
c) Abc def
d) Abc Def
View Answer
Answer: c
Explanation: The first letter of the string is converted to uppercase and the others are converted to
lowercase.
print("abc. DEF".capitalize())
a) abc def
b) ABC DEF
c) Abc def
d) Abc Def
View Answer
Answer: c
Explanation: The first letter of the string is converted to uppercase and the others are converted to
lowercase.
print("abcdef".center())
a) cd
b) abcdef
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: The function center() takes atleast one parameter.
print("abcdef".center(0))
advertisements
a) cd
b) abcdef
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: The entire string is printed when the argument passed to center() is less than the length
of the string.
a) * abcdef *
b) * abcdef *
c) *abcdef *
d) * abcdef*
View Answer
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.
Answer: d
Explanation: Padding is done towards the left-hand-side first when the final string is of odd length.
a) * abcde *
b) * abcde *
c) *abcde *
d) * abcde*
View Answer
Answer: c
Explanation: Padding is done towards the right-hand-side first when the final string is of even length.
advertisements
print("abcdef".center(7, 1))
a) 1abcdef
b) abcdef1
c) abcdef
d) error
View Answer
Answer: d
Explanation: TypeError, the fill character must be a character, not an int.
print("abcdef".center(7, '1'))
a) 1abcdef
b) abcdef1
c) abcdef
d) error
View Answer
Answer: a
Explanation: The character ‘1’ is used for padding instead of a space.
10. What is the output of the following?
print("abcdef".center(10, '12'))
a) 12abcdef12
b) abcdef1212
c) 1212abcdef
d) error
View Answer
Answer: d
Explanation: The fill character must be exactly one character long.
print("xyyzxyzxzxyy".count('yy'))
a) 2
b) 0
c) error
d) none of the mentioned
View Answer
Answer: a
Explanation: Counts the number of times the substring ‘yy’ is present in the given string.
print("xyyzxyzxzxyy".count('yy', 1))
a) 2
b) 0
c) 1
d) none of the mentioned
View Answer
Answer: a
Explanation: Counts the number of times the substring ‘yy’ is present in the given string, starting
from position 1.
a) 2
b) 0
c) 1
d) none of the mentioned
View Answer
Answer: c
Explanation: Counts the number of times the substring ‘yy’ is present in the given string, starting
from position 2.
advertisements
print("xyyzxyzxzxyy".count('xyy', 0, 100))
a) 2
b) 0
c) 1
d) error
View Answer
Answer: a
Explanation: An error will not occur if the end value is greater than the length of the string itself.
print("xyyzxyzxzxyy".count('xyy', 2, 11))
a) 2
b) 0
c) 1
d) error
View Answer
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.
a) 2
b) 0
c) 1
d) error
View Answer
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.
print('abc'.encode())
advertisements
a) abc
b) ‘abc’
c) b’abc’
d) h’abc’
View Answer
Answer: c
Explanation: A bytes object is returned by encode.
Answer: c
Explanation: The default value of encoding is utf-8.
print("xyyzxyzxzxyy".endswith("xyy"))
a) 1
b) True
c) 3
d) 2
View Answer
Answer: b
Explanation: The function returns True if the given string ends with the specified substring.
print("xyyzxyzxzxyy".endswith("xyy", 0, 2))
a) 0
b) 1
c) True
d) False
View Answer
Answer: d
Explanation: The function returns False if the given string does not end with the specified substring.
print("ab\tcd\tef".expandtabs())
a) ab cd ef
b) abcdef
c) ab\tcd\tef
d) ab cd ef
View Answer
Answer: a
Explanation: Each \t is converted to 8 blank spaces by default.
print("ab\tcd\tef".expandtabs(4))
a) ab cd ef
b) abcdef
c) ab\tcd\tef
d) ab cd ef
View Answer
Answer: d
Explanation: Each \t is converted to 4 blank spaces.
print("ab\tcd\tef".expandtabs('+'))
a) ab+cd+ef
b) ab++++++++cd++++++++ef
c) ab cd ef
d) none of the mentioned
View Answer
Answer: d
Explanation: TypeError, an integer should be passed as an argument.
a) True
b) False
c) error
d) none of the mentioned
View Answer
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.
advertisements
print("abcdef".find("cd"))
a) True
b) 2
c) 3
d) none of the mentioned
View Answer
Answer: b
Explanation: The first position in the given string at which the substring can be found is returned.
print("ccdcddcd".find("c"))
a) 4
b) 0
c) error
d) True
View Answer
Answer: b
Explanation: The first position in the given string at which the substring can be found is returned.
Answer: a
Explanation: The numbers 0 and 1 represent the position at which the strings are present.
Answer: a
Explanation: It is the same as Hello {0} and {1}.
Answer: c
Explanation: The arguments passed to the function format aren’t keyword arguments.
Answer: a
Explanation: The arguments are accessed by their names.
Answer: b
Explanation: !r causes the charactes ‘ or ” to be printed as well.
Answer: c
Explanation: IndexError, the tuple index is out of range.
Answer: a
Explanation: The elements of the tuple are accessed by their indices.
Answer: a
Explanation: The arguments passed to the function format can be integers also.
Answer: b
Explanation: 2 is converted to binary, 10 to hexadecimal and 12 to octal.
print('{:,}'.format(1112223334))
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
d) error
View Answer
Answer: a
Explanation: A comma is added after every third digit from the right.
advertisements
print('{:,}'.format('1112223334'))
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
d) error
View Answer
Answer: d
Explanation: An integer is expected.
print('{:$}'.format(1112223334))
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
d) error
View Answer
Answer: d
Explanation: $ is an invalid format code.
print('{:#}'.format(1112223334))
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
d) error
View Answer
Answer: c
Explanation: The number is printed as it is.
print('{0:.2}'.format(1/3))
a) 0.333333
b) 0.33
c) 0.333333:.2
d) error
View Answer
Answer: b
Explanation: .2 specifies the precision.
print('{0:.2%}'.format(1/3))
a) 0.33
b) 0.33%
c) 33.33%
d) 33%
View Answer
Answer: c
Explanation: The symbol % is used to represent the result of an expression as a percentage.
print('ab12'.isalnum())
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: The string has only letters and digits.
print('ab,12'.isalnum())
advertisements
a) True
b) False
c) None
d) error
View Answer
Answer: b
Explanation: The character , is not a letter or a digit.
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: The string has only letters.
print('a B'.isalpha())
a) True
b) False
c) None
d) error
View Answer
Answer: b
Explanation: Space is not a letter.
print('0xa'.isdigit())
a) True
b) False
c) None
d) error
View Answer
Answer: b
Explanation: Hexadecimal digits aren’t considered as digits (a-f).
advertisements
print(''.isdigit())
a) True
b) False
c) None
d) error
View Answer
Answer: b
Explanation: If there are no characters then False is returned.
print('my_string'.isidentifier())
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: It is a valid identifier.
print('__foo__'.isidentifier())
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: It is a valid identifier.
print('for'.isidentifier())
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: Even keywords are considered as valid identifiers.
2. What is the output of the following?
print('abc'.islower())
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: There are no uppercase letters.
print('a@ 1,'.islower())
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: There are no uppercase letters.
print('11'.isnumeric())
advertisements
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: All the character are numeric.
print('1.1'.isnumeric())
a) True
b) False
c) None
d) error
View Answer
Answer: b
Explanation: The character . is not a numeric character.
print('1@ a'.isprintable())
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: All those characters are printable.
print('''
'''.isspace())
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: A newline character is considered as space.
advertisements
print('\t'.isspace())
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: Tabspaces are considered as spaces.
print('HelloWorld'.istitle())
a) True
b) False
c) None
d) error
View Answer
Answer: b
Explanation: The letter W is uppercased.
print('Hello World'.istitle())
a) True
b) False
c) None
d) Error
View Answer
Answer: a
Explanation: It is in title form.
print('Hello!2@#World'.istitle())
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: It is in the form of a title.
print('1Rn@'.lower())
a) n
b) 1rn@
c) rn
d) r
View Answer
Answer: b
Explanation: Uppercase letters are converted to lowercase. The other characters are left unchanged.
print('''
\tfoo'''.lstrip())
a) \tfoo
b) foo
c) foo
d) none of the mentioned
View Answer
Answer: b
Explanation: All leading whitespace is removed.
print('xyyzxxyxyy'.lstrip('xyy'))
advertisements
a) error
b) zxxyxyy
c) z
d) zxxy
View Answer
Answer: b
Explanation: The leading characters containing xyy are removed.
print('xyxxyyzxxy'.lstrip('xyy'))
a) zxxy
b) xyxxyyzxxy
c) xyxzxxy
d) none of the mentioned
View Answer
Answer: a
Explanation: All combinations of the characters passed as an argument are removed from the left
hand side.
6. What is the output of the following?
print('cba'.maketrans('abc', '123'))
Answer: a
Explanation: A translation table is returned by maketrans.
print('a'.maketrans('ABC', '123'))
Answer: a
Explanation: maketrans() is a static method so it’s behaviour does not depend on the object from
which it is being called.
print('cd'.partition('cd'))
a) (‘cd’)
b) (”)
c) (‘cd’, ”, ”)
d) (”, ‘cd’, ”)
View Answer
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 is the output of the following?
print('abef'.partition('cd'))
a) (‘abef’)
b) (‘abef’, ‘cd’, ”)
c) (‘abef’, ”, ”)
d) error
View Answer
Answer: c
Explanation: The separator is not present in the string hence the second and the third elements of
the tuple are null strings.
print('abcdef12'.replace('cd', '12'))
a) ab12ef12
b) abcdef12
c) ab12efcd
d) none of the mentioned
View Answer
Answer: a
Explanation: All occurences of the first substring are replaced by the second substring.
print('abef'.replace('cd', '12'))
advertisements
a) abef
b) 12
c) error
d) none of the mentioned
View Answer
Answer: a
Explanation: The first substring is not present in the given string and hence nothing is replaced.
print('abcefd'.replace('cd', '12'))
a) ab1ef2
b) abcefd
c) ab1efd
d) ab12ed2
View Answer
Answer: b
Explanation: The first substring is not present in the given string and hence nothing is replaced.
a) xyyxyyxyxyxxy
b) 12y12y1212x12
c) 12yxyyxyxyxxy
d) xyyxyyxyxyx12
View Answer
Answer: a
Explanation: The first 0 occurances of the given substring are replaced.
a) xyyxyyxyxyxxy
b) 12y12y1212x12
c) none of the mentioned
d) error
View Answer
Answer: b
Explanation: The first 100 occurances of the given substring are replaced.
advertisements
print('abcdefcdghcd'.split('cd'))
Answer: b
Explanation: The given string is split and a list of substrings is returned.
print('abcdefcdghcd'.split('cd', 0))
a) [‘abcdefcdghcd’] b) ‘abcdefcdghcd’
c) error
d) none of the mentioned
View Answer
Answer: a
Explanation: The given string is split at 0 occurances of the specified substring.
print('abcdefcdghcd'.split('cd', -1))
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.
print('abcdefcdghcd'.split('cd', 2))
a) [‘ab’, ‘ef’, ‘ghcd’] b) [‘ab’, ‘efcdghcd’] c) [‘abcdef’, ‘ghcd’] d) none of the mentioned
View Answer
Answer: a
Explanation: The string is split into a maximum of maxsplit+1 substrings.
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’] View
Answer
Answer: a
Explanation: It is similar to calling split(‘\n’).
print('Ab!2'.swapcase())
a) AB!@
b) ab12
c) aB!2
d) aB1@
View Answer
Answer: c
Explanation: Lowercase letters are converted to uppercase and vice-versa.
print('ab cd ef'.title())
advertisements
a) Ab cd ef
b) Ab cd eF
c) Ab Cd Ef
d) none of the mentioned
View Answer
Answer: c
Explanation: The first letter of every word is capitalized.
print('ab cd-ef'.title())
a) Ab cd-ef
b) Ab Cd-ef
c) Ab Cd-Ef
d) none of the mentioned
View Answer
Answer: c
Explanation: The first letter of every word is capitalized. Special symbols terminate a word.
print('abcd'.translate('a'.maketrans('abc', 'bcd')))
a) bcde
b) abcd
c) error
d) none of the mentioned
View Answer
Answer: d
Explanation: The output is bcdd since no translation is provided for d.
a) bcde
b) abcd
c) error
d) none of the mentioned
View Answer
Answer: d
Explanation: The output is bcdd since no translation is provided for d.
advertisements
a) abcd
b) 1234
c) error
d) none of the mentioned
View Answer
Answer: a
Explanation: The function translate expects a dictionary of integers. Use maketrans() instead of
doing the above.
print('ab'.zfill(5))
a) 000ab
b) 00ab0
c) 0ab00
d) ab000
View Answer
Answer: a
Explanation: The string is padded with zeroes on the left hand side. It is useful for formatting
numbers.
print('+99'.zfill(5))
a) 00+99
b) 00099
c) +0099
d) +++99
View Answer
Answer: c
Explanation: Zeroes are filled in between the first sign and the rest of the string.
Answer:a,b,c,d
Explanation:Execute in the shell to verify
Answer:a
Explanation:execute in the shell to verify.
Answer:a
Explanation:Execute in the shell and verify.
Answer:c
Explanation:max returns the maximum element in the list.
advertisements
Answer:d
Explanation:min returns the minimum element in the list.
Answer:c
Explanation:Sum returns the sum of all elements in the list.
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 (multiple answers
allowed) ?
a) print(list1[0])
b) print(list1[:2])
c) print(list1[:-2])
d) print(list1[4:6])
View Answer
Answer:a, b, c, d
Explanation:Slicing is allowed in lists just as in the case of strings.
advertisements
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] View Answer
Answer:a
Explanation:Execute in the shell to verify.
a) A
b) Daman
c) Error
d) n
View Answer
Answer:d
Explanation:Execute in the shell to verify.
a) 11
b) 12
c) 21
d) 22
View Answer
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.
advertisements
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] View Answer
Answer:c
Explanation:Execute in the shell to verify.
a) True
b) False
c) Error
d) None
View Answer
Answer:b
Explanation:Elements are compared one by one.
Answer:b
Explanation:We use the function append to add an element to the list.
advertisements
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)
View Answer
Answer:a
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”)
View Answer
Answer:a
Explanation:Execute in the shell to verify.
Answer:d
Explanation:Execute help(list.index) to get details.
Answer:d
Explanation:Execute in the shell to verify.
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] View Answer
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] View Answer
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] View Answer
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] View Answer
Answer:a
Explanation:pop() by default will remove the last element.
1. >>>"Welcome to Python".split()
Answer:a
Explanation:split() function returns the elements in a list.
1. >>>list("a#b#c#d".split('#'))
advertisements
a) [‘a’, ‘b’, ‘c’, ‘d’] b) [‘a b c d’] c) [‘a#b#c#d’] d) [‘abcd’] View Answer
Answer:a
Explanation:Execute in the shell to verify.
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.
9. >>>print(indexOfMax)
a) 1
b) 2
c) 3
d) 4
View Answer
Answer:a
Explanation:First time the highest number is encountered is at index 1.
1. myList = [1, 2, 3, 4, 5, 6]
2. for i in range(1, 6):
3. myList[i - 1] = myList[i]
4.
5. for i in range(0, 6):
6. 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
View Answer
Answer:c
Explanation:Execute in the shell to verify.
advertisements
9. What is the output when following code is executed ?
1. >>>list1 = [1, 3]
2. >>>list2 = list1
3. >>>list1[0] = 4
4. >>>print(list2)
Answer:b
Explanation:Lists should be copied by executing [:] operation.
1. def f(values):
2. values[0] = 44
3.
4. v = [1, 2, 3]
5. f(v)
6. print(v)
Answer:c
Explanation:Execute in the shell to verify.
Answer:c
Explanation:execute in the shell to verify
a) None
b) 1
c) 2
d) Error
View Answer
Answer:c
Explanation:execute in the shell to verify.
a) None
b) a
c) b
d) c
View Answer
Answer:d
Explanation:List Comprehension are a shorthand for creating new lists.
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 Above
View Answer
Answer:d
Explanation:in can be used in all data structures.
1. list1 = [1, 2, 3, 4]
2. list2 = [5, 6, 7, 8]
3.
4. print len(list1 + list2)
a) 2
b) 4
c) 5
d) 8
View Answer
Answer:d
Explanation:+ appends all the elements individually into a new list.
1. def addItem(listParam):
2. listParam += [1]
3.
4. mylist = [1, 2, 3, 4]
5. addItem(mylist)
6. print len(mylist)
a) 1
b) 4
c) 5
d) 8
View Answer
Answer:c
Explanation:+ will append the element to the list.
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
Answer:a
Explanation:Run the code to get a better understanding with many arguements.
Answer:a
Explanation:Execute in the shell to verify.
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] View Answer
Answer:b
Explanation:Execute in the shell to verify
a) 8
b) 12
c) 16
d) 32
View Answer
Answer:c
Explanation:Execute in the shell to verify.
a) 3
b) 5
c) 6
d) 33
View Answer
Answer:d
Explanation:Execute in the shell to verify.
Answer:d
Explanation:Execute in the shell to verify.
a) 1 2 3 4
b) 4 5 6 7
c) 1 3 8 12
d) 2 5 9 13
View Answer
Answer:d
Explanation:Execute in the shell to verify.
1. def m(list):
2. v = list[0]
3. for e in list:
4. if v < e: v = e
5. return v
6.
7. values = [[3, 4, 5, 1], [33, 6, 1, 2]]
8.
9. for row in values:
10. print(m(row), end = " ")
a) 3 33
b) 1 1
c) 5 6
d) 5 33
View Answer
Answer:d
Explanation:Execute in the shell to verify.
advertisements
8. What will be the output?
1. data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
2.
3. print(data[1][0][0])
a) 1
b) 2
c) 4
d) 5
View Answer
Answer:d
Explanation:Execute in the shell to verify.
a) 1
b) 2
c) 4
d) 5
View Answer
Answer:c
Explanation:Execute in the shell to verify.
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]] View Answer
Answer:c
Explanation:Execute in the shell to verify.
Answer:a,b,c
Explanation:Dictionaries are created by specifying keys and values
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”)
View Answer
Answer:b
Explanation:Dictionaries appear in the form of keys and values.
1. d = {"john":40, "peter":45}
2. "john" in d
a) True
b) False
c) None
d) Error
View Answer
Answer:a
Explanation:In can be used to check if the key is int dictionary.
1. d1 = {"john":40, "peter":45}
2. d2 = {"john":466, "peter":45}
3. d1 == d2
advertisements
a) True
b) False
c) None
d) Error
View Answer
Answer:b
Explanation:If d2 was initialized as d2 = d1 the answer would be true.
1. d1 = {"john":40, "peter":45}
2. d2 = {"john":466, "peter":45}
3. d1 > d2
a) True
b) False
c) Error
d) None
View Answer
Answer:c
Explanation:Arithmetic > operator cannot be used with dictionaries.
6. What is the output?
1. d = {"john":40, "peter":45}
2. d["john"]
a) 40
b) 45
c) “john”
d) “peter”
View Answer
Answer:a
Explanation:Execute in the shell to verify.
advertisements
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)
View Answer
Answer:c
Explanation:Execute in the shell to verify.
Answer:b
Explanation:Execute in the shell to verify.
1. d = {"john":40, "peter":45}
2. print(list(d.keys()))
Answer:a
Explanation:Execute in the shell to verify.
10. Suppose d = {“john”:40, “peter”:45}, what happens when retieving a value using
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.
View Answer
Answer:c
Explanation:Execute in the shell to verify.
Answer:b
Explanation:Tuples are characterised by their round brackets.
Answer:b
Explanation:Values cannot be modified in the case of tuple.
1. >>>t=(1,2,4,3)
2. >>>t[1:3]
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
View Answer
Answer:c
Explanation:Slicing just as in the case of strings takes place in tuples.
1. >>>t=(1,2,4,3)
2. >>>t[1:-1]
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
View Answer
Answer:c
Explanation:Slicing just as in the case of strings takes place in tuples.
1. >>>t = (1, 2, 4, 3, 8, 9)
2. >>>[t[i] for i in range(0, len(t), 2)]
advertisements
a) [2, 3, 9] b) [1, 2, 4, 3, 8, 9] c) [1, 4, 8] d) (1, 4, 8)
View Answer
Answer:c
Explanation:Execute in the shell to verify.
1. d = {"john":40, "peter":45}
2. d["john"]
a) 40
b) 45
c) “john”
d) “peter”
View Answer
Answer:a
Explanation:Execute in the shell to verify.
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] View Answer
Answer:a
Explanation:* operator concatenates tuple.
1. >>>t1 = (1, 2, 4, 3)
2. >>>t2 = (1, 2, 3, 4)
3. >>>t1 < t2
advertisements
a) True
b) False
c) Error
d) None
View Answer
Answer:b
Explanation:Elements are compared one by one in this case.
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
View Answer
Answer:d
Explanation:Tuples are immutable and don’t have an append method. An exception is thrown
in this case..
1. numberGames = {}
2. numberGames[(1,2,4)] = 8
3. numberGames[(4,2,1)] = 10
4. numberGames[(1,2)] = 12
5.
6. sum = 0
7. for k in numberGames:
8. sum += numberGames[k]
9.
10. print len(numberGames) + sum
a) 30
b) 24
c) 33
d) 12
View Answer
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.
Answer:b
Explanation:Execute help(open) to get more details.
Answer:b
Explanation:w is used to indicate that file is to be written to.
Answer:a
Explanation:a is used to indicate that data is to be apended.
Answer:a,c,d.
Explanation:The program will throw an error.
advertisements
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()
View Answer
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()
View Answer
Answer:b
Explanation:read function is used to read all the lines in a file.
1. f = None
2.
3. for i in range (5):
4. with open("data.txt", "w") as f:
5. if i > 2:
6. break
7.
8. print f.closed
a) True
b) False
c) None
d) Error
View Answer
Answer:a
Explanation:The WITH statement when used with open file guarantees that the file object is
closed when the with block exits..
advertisements
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()
View Answer
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()
View Answer
Answer:d
Explanation:Execute in the shell to verify.
Answer:b
Explanation:Every line is stored in a list and returned
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
b) Input
c) Scan
d) Scanner
View Answer
Answer: a, b
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
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 is the output of this program?
a) Enter your input: [x*5 for x in range(2,10,2)] Received input is : [10, 20, 30, 40] 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
View Answer
Answer: a
Explanation: The input([prompt]) function is equivalent to raw_input, except that it assumes
the input is a valid Python expression and returns the evaluated result to you.
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.
advertisements
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
View Answer
Answer: a
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.
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
View Answer
Answer: a
remove(file_name)
1. fo = open("foo.txt", "rw+")
2. print "Name of the file: ", fo.name
3.
4. # Assuming file has following 5 lines
5. # This is 1st line
6. # This is 2nd line
7. # This is 3rd line
8. # This is 4th line
9. # This is 5th line
10.
11. for index in range(5):
12. line = fo.next()
13. print "Line No %d - %s" % (index, line)
14.
15. # Close opend file
16. fo.close()
a) Compilation Error
b) Syntax Error
c) Displays Output
d) None of the mentioned
View Answer
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
advertisements
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
View Answer
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.
Answer: a
Explanation: The method truncate() truncates the file’s 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
1. import sys
2. print 'Enter your name: ',
3.
4. name = ''
5.
6. while True:
7. c = sys.stdin.read(1)
8. if c == '\n':
9. break
10. name = name + c
11.
12. print 'Your name is:', name
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 promt
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
1. import sys
2.
3. sys.stdout.write(' Hello\n')
4. sys.stdout.write('Python\n')
advertisements
a) Compilation Error
b) Runtime Error
c) Hello Python
d) Hello
Python
View Answer
Answer: d
Explanation: None
Output:
Hello
Python
Answer:d
Explanation: Mode Meaning is as explained below:
r Reading
w Writing
a Appending
b Binary data
+ Updating.
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
View Answer
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.
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).
1. fo = open("foo.txt", "wb")
2. print "Name of the file: ", fo.name
3.
4. fo.flush()
5.
6. fo.close()
advertisements
a) Compilation Error
b) Runtime Error
c) No Output
d) Flushes the file when closing them
View Answer
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.
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
View Answer
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.
Answer: a
Explanation: r- reading, a-appending.
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”).
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”).
Answer:a
Explanation:The read function reads all characters fh = open(“filename”, “r”)
content = fh.read().
advertisements
Answer:b
Explanation: The readline function reads a single line from the file fh = open(“filename”, “r”)
content = fh.readline().
Answer: a
Explanation:To write a fixed sequence of characters to a file
fh = open(“hello.txt”,”w”)
write(“Hello World”).
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).
Answer: a
Explanation: f.close()to close it and free up any system resources taken up by the open file.
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().
advertisements
10. Which of the following is modes of both writing and reading in binary format in file.?
a) wb+
b) w
c) wb
d) w+
View Answer
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
Answer: b
Explanation: Use r+, w+ or a+ to perform both read and write operations using a single file object.
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__()
View Answer
Answer: a
Explanation: name is an attribute of the file object.
advertisements
Answer: d
Explanation: fp.size has not been implemented.
Answer: c
Explanation: close() is a method of the file object.
Answer: b
Explanation: It gives the current position as an offset from the start of file.
Answer: b
Explanation: os.rename() is used to rename files.
Answer: c
Explanation: os.remove() is used to delete files.
advertisements
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
View Answer
Answer: a
Explanation: 0 indicates that the offset is with respect to the start.
Answer: d
Explanation: seek() takes at least one argument.
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.
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
View Answer
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.
5. sayHello() # call the function
6. sayHello() # call the function again
a) 3
b) 4
c) 4 is maximum
d) None of the mentioned
View Answer
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 is the output of the below program ?
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 still', x)
advertisements
a) x is still 50
b) x is still 2
c) x is still 100
d) None of the mentioned
View Answer
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.
1. x = 50
2.
3. def func():
4. global x
5.
6. print('x is', x)
7. x = 2
8. print('Changed global x to', x)
9. func()
10. 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
View Answer
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.
a) Hello
WorldWorldWorldWorldWorld
b) Hello
World 5
c) Hello
World,World,World,World,World
d) Hello
d
View Answer
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.
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
View Answer
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.
advertisements
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.
a) 2
b) 3
c) The numbers are equal
d) None of the mentioned
View Answer
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.
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.
Answer: f
Explanation: None.
Answer: b and c
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.
Answer: a, b and c
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
View Answer
Answer: d
Explanation: None.
Answer: a
Explanation: Each object in Python has a unique id. The id() function returns the object’s id.
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
The sqrt() function is imported from the math module.
1. def cube(x):
2. return x * x * x
3.
4. x = cube(3)
5. print x
advertisements
a) 9
b) 3
c) 27
d) 30
View Answer
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.
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
View Answer
Answer: a
Explanation: None.
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
View Answer
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.
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
View Answer
Answer: a
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.
1. y = 6
2.
3. z = lambda x: x * y
4. print z(8)
a) 48
b) 14
c) 64
d) None of the mentioned
View Answer
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.
1. lamb = lambda x: x ** 3
2. print(lamb(5))
a) 15
b) 555
c) 125
d) None of the mentioned
View Answer
Answer: c
Explanation: None.
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, and we don’t have to assign it to a variable at all.
advertisements
5. Lambda is a statement.
a) True
b) False
View Answer
Answer: b
Explanation: None.
a) 432
b) 24000
c) 430
d) None of the mentioned
View Answer
Answer: a
Explanation: None.
1. def writer():
2. title = 'Sir'
3. name = (lambda x:title + ' ' + x)
4. return name
5.
6. who = writer()
7. who('Arthur')
a) Arthur Sir
b) Sir Arthur
c) Arthur
d) None of the mentioned
View Answer
Answer: b
Explanation: None.
1. L = [lambda x: x ** 2,
2. lambda x: x ** 3,
3. lambda x: x ** 4]
4.
5. for f in L:
6. print(f(3))
advertisements
a) 27
81
343
b) 6
9
12
c) 9
27
81
d) None of the mentioned
View Answer
Answer: c
Explanation: None.
a) 9997
b) 9999
c) 9996
d) None of the mentioned
View Answer
Answer: c
Explanation: None.
Answer: d
Explanation: There has to be at least one except statement.
Answer: c
Explanation: The else part is executed when no exception occurs.
3. Is the following code valid?
try:
# Do something
except:
# Do something
finally:
# Do something
Answer: b
Explanation: Refer documentation.
try:
# Do something
except:
# Do something
else:
# Do something
advertisements
Answer: d
Explanation: Refer documentation.
Answer: a
Explanation: Each type of exception can be specified directly. There is no need to put it in a list.
Answer: d
Explanation: The finally block is always executed.
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
View Answer
Answer: b
Explanation: The finally block is executed even there is a return statement in the try block.
def foo():
try:
print(1)
finally:
print(2)
foo()
advertisements
a) 1 2
b) 1
c) 2
d) none of the mentioned
View Answer
Answer: a
Explanation: No error occurs in the try block so 1 is printed. Then the finally block is executed and 2
is printed.
try:
if '1' != 1:
raise "someError"
else:
print("someError has not occured")
except "someError":
print ("someError has occured")
Answer: c
Explanation: A new exception class must inherit from a BaseException. There is no such inheritance
here.
Answer: b
Explanation: It simply evaluates to False and does not raise any exception.
Answer: d
Explanation: It is a list of strings.
def foo(k):
k[0] = 1
q = [0]
foo(q)
print(q)
Answer: b
Explanation: Lists are passed by reference.
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
View Answer
Answer: c
Explanation: zero keyword arguments may be passed if all the arguments have default values.
advertisements
a) 3 1
b) 1 3
c) error
d) none of the mentioned
View Answer
Answer: a
Explanation: It is possible to pass function names as arguments to other functions.
def foo():
return total + 1
total = 0
print(foo())
a) 0
b) 1
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: It is possible to read the value of a global variable directly.
def foo():
total += 1
return total
total = 0
print(foo())
a) 0
b) 1
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: It is not possible to change the value of a global variable without explicitly specifying it.
advertisements
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
View Answer
Answer: b
Explanation: A new object is created in the function.
a) [0] [1] [2] b) [0] [0, 1] [0, 1, 2] c) [1] [2] [3] d) [1] [1, 2] [1, 2, 3] View Answer
Answer: b
Explanation: When a list is a default value, the same list will be reused.
def foo(k):
k = [1]
q = [0]
foo(q)
print(q)
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].
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
View Answer
Answer: a
Explanation: getopt parses options received from the command line.
advertisements
Answer: b
Explanation: It is a list of elements.
Answer: c
Explanation: Refer documentation.
Answer: a
Explanation: Refer documentation.
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
View Answer
Answer: a
Explanation: The same object is modified in the function.
advertisements
9. Where are the arguments recived from the command line stored?
a) sys.argv
b) os.argv
c) argv
d) none of the mentioned
View Answer
Answer: a
Explanation: Refer documentation.
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]]] View Answer
Answer: c
Explanation: append() returns None.
Python Questions and Answers – List
Comprehension
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “List
Comprehension”.
Answer: c
Explanation: print(i) is executed if the given character is not a vowel.
Answer: b
Explanation: print() returns None.
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
View Answer
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)
advertisements
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))
Answer: c
Explanation: We have to create an empty list, loop over the contents of the existing list and check if
a condtion is satisfied before performing some operation and adding it to the new list.
Answer: a
Explanation: i**+1 is evaluated as (i)**(+1).
Answer: a
Explanation: We are iterating over each letter in the string.
7. What is the output of the following?
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’] View
Answer
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.
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’] View Answer
Answer: b
Explanation: The inner list is generated once for each value of j.
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
View Answer
Answer: c
Explanation: x**-1 is evaluated as (x)**(-1).
elements = [0, 1, 2]
def incr(x):
return x+1
print(list(map(elements, incr)))
Answer: c
Explanation: The list should be the second parameter to the mapping function.
elements = [0, 1, 2]
def incr(x):
return x+1
print(list(map(incr, elements)))
Answer: a
Explanation: Each element of the list is incremented.
x = ['ab', 'cd']
print(list(map(upper, x)))
Answer: c
Explanation: A NameError occurs because upper is a class method.
def to_upper(k):
return k.upper()
x = ['ab', 'cd']
print(list(map(upper, x)))
advertisements
def to_upper(k):
return k.upper()
x = ['ab', 'cd']
print(list(map(to_upper, x)))
Answer: a
Explanation: Each element of the list is converted to uppercase.
def to_upper(k):
k.upper()
x = ['ab', 'cd']
print(list(map(to_upper, x)))
Answer: c
Explanation: A list of Nones is printed as to_upper() returns None.
x = ['ab', 'cd']
print(map(len, x))
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.
advertisements
x = ['ab', 'cd']
print(list(map(len, x)))
x = ['ab', 'cd']
print(len(map(list, x)))
a) [2, 2] b) 2
c) 4
d) none of the mentioned
View Answer
Answer: d
Explanation: A TypeError occurs as map has no len().
x = ['ab', 'cd']
print(len(list(map(list, x))))
a) 2
b) 4
c) error
d) none of the mentioned
View Answer
Answer: a
Explanation: The outer list has two lists in it. So it’s length is 2.
x = ['ab', 'cd']
print(len(list(map(list, x))))))
a) 2
b) 4
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: SyntaxError, unbalanced parenthesis.
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
View Answer
Answer: c
Explanation: Each element of x is converted into a list.
x = [12, 34]
print(len(list(map(len, x))))
a) 2
b) 1
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: TypeError, int has no len().
x = [12, 34]
print(len(list(map(int, x))))
advertisements
a) 2
b) 1
c) error
d) none of the mentioned
View Answer
Answer: a
Explanation: list(map()) returns a list of two items in this example.
x = [12, 34]
print(len(''.join(list(map(int, x)))))
a) 4
b) 2
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: Cannot perform join on a list of ints.
x = [12, 34]
print(len(''.join(list(map(str, x)))))
a) 4
b) 5
c) 6
d) error
View Answer
Answer: a
Explanation: Each number is mapped into a string of length 2.
x = [12, 34]
print(len(' '.join(list(map(int, x)))))
a) 4
b) 5
c) 6
d) error
View Answer
Answer: b
Explanation: The elements of the list are joined by a space.
advertisements
x = [12.1, 34.0]
print(len(' '.join(list(map(str, x)))))
a) 6
b) 8
c) 9
d) error
View Answer
Answer: c
Explanation: The floating point numbers are converted to strings and joined with a space between
them.
9. What is the output of the following?
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
View Answer
Answer: d
Explanation: str(ab.c) is ‘ab.c’.
x = [[0], [1]]
print(len(' '.join(list(map(str, x)))))
a) 2
b) 3
c) 7
d) 8
View Answer
Answer: c
Explanation: map() is applied to the elements of the outer loop.
x = [[0], [1]]
print((' '.join(list(map(str, x)))))
a) (‘[0] [1]’,)
b) (’01’,)
c) [0] [1] d) 01
View Answer
Answer: c
Explanation: (element) is the same as element. It is not a tuple with one item.
2. What is the output of the following?
x = [[0], [1]]
print((' '.join(list(map(str, x))),))
a) (‘[0] [1]’,)
b) (’01’)
c) [0] [1] d) 01
View Answer
Answer: a
Explanation: (element,) is not the same as element. It is a tuple with one item.
x = [34, 56]
print((''.join(list(map(str, x))),))
a) 3456
b) (3456)
c) (‘3456’)
d) (‘3456’,)
View Answer
Answer: d
Explanation: We have created a tuple with one string in it.
x = [34, 56]
print((''.join(list(map(str, x)))),)
advertisements
a) 3456
b) (3456)
c) (‘3456’)
d) (‘3456’,)
View Answer
Answer: a
Explanation: We have just created a string.
x = [34, 56]
print(len(map(str, x)))
x = 'abcd'
print(list(map(list, x)))
a) [‘a’, ‘b’, ‘c’, ‘d’] b) [‘abcd’] c) [[‘a’], [‘b’], [‘c’], [‘d’]] d) none of the mentioned
View Answer
Answer: c
Explanation: list() is performed on each character in x.
x = abcd
print(list(map(list, x)))
a) [‘a’, ‘b’, ‘c’, ‘d’] b) [‘abcd’] c) [[‘a’], [‘b’], [‘c’], [‘d’]] d) none of the mentioned
View Answer
Answer: d
Explanation: NameError, we have not defined abcd.
advertisements
x = 1234
print(list(map(list, x)))
Answer: d
Explanation: TypeError, int is not iterable.
x = 1234
print(list(map(list, [x])))
Answer: d
Explanation: TypeError, int is not iterable.
a) [‘a’, ‘b’, ‘c’, ‘d’] b) [‘abcd’] c) [[‘a’], [‘b’], [‘c’], [‘d’]] d) none of the mentioned
View Answer
Answer: d
Explanation: TypeError, list object is not callable.
f = foo()
format(f)
a) format()
b) __format__()
c) str()
d) __str__()
View Answer
Answer: d
Explanation: Both str(f) and format(f) call f.__str__().
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
advertisements
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
View Answer
Answer: c
Explanation: __lt__ overloads the < operator. [/expand] 3. Which function overloads the + operator?
a) __add__() b) __plus__() c) __sum__() d) none of the mentioned [expand title="View
Answer"]Answer: a Explanation: Refer documentation.[/expand] 4. Which operator is overloaded by
__invert__()? a) ! b) ~ c) ^ d) - [expand title="View Answer"]Answer: b Explanation: __invert__()
overloads ~.[/expand] 5. Which function overloads the == operator? a) __eq__() b) __equ__() c)
__isequal__() d) none of the mentioned [expand title="View Answer"]Answer: a Explanation: The
other two do not exist.[/expand] 6. Which operator is overloaded by __lg__()? a) < b) >
c) !=
d) none of the mentioned
View AnswerAnswer: d
Explanation: __lg__() is invalid.
advertisements
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__()
View Answer
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 recieved after adding A and B.
Answer: b
Explanation: The function __or__() overloads the bitwise OR operator |.
Answer: c
Explanation: __floordiv__() is for //.
Answer: c
Explanation: Only integers can be returned.
Answer: b
Explanation: It returns one number from the given range.
advertisements
4. The function random.randint(4) can return only one of the following values. Which?
a) 4
b) 3.4
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: Error, the function takes two arguments.
Answer: d
Explanation: random.randint(3, 6) can return any one of 3, 4, 5 and 6.
Answer: d
Explanation: Any of the characters present in the string may be returned.
Answer: a
Explanation: It will not print 0 but dict[0] i.e. 1 may be printed.
Answer: c
Explanation: The elements of the list passed to it are shuffled in-place.
advertisements
Answer: b
Explanation: Strings and tuples are immutable and an integer has no len().
Answer: d
Explanation: Any number that is greater than or equal to 0.0 and lesser than 1.0 can be returned.
Python Questions and Answers – Math – 1
This set of Python Objective Questions & Answers focuses on “Mathematical Functions”.
Answer: b
Explanation: The ceil function returns the smallest integer that is bigger than or equal to the number
itself.
Answer: a
Explanation: The floor function returns the biggest number that is smaller than or equal to the
number itself.
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.
advertisements
Answer: b
Explanation: A negative floating point number is returned as a positive floating point number.
5. Is the function abs() same as math.fabs()?
a) sometimes
b) always
c) never
d) none of the mentioned
View Answer
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.
Answer: d
Explanation: NameError, fact() is not defined.
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
View Answer
Answer: a
Explanation: The factorial of 4 is returned.
advertisements
Answer: a
Explanation: 0o10 is 8 and floor(8) is 8.
Answer: a
Explanation: It returns a tuple with two elements. The first element is the mantissa and the second
element is the exponent.
Answer: a
Explanation: The function fsum returns an accurate floating point sum of the elements of its
argument.
Answer: b
Explanation: float(‘inf’) is not a finite number.
Answer: b
Explanation: float(‘nan’) is not a finite number.
advertisements
6. What is x if x = math.isfinite(float(‘0.0’))?
a) True
b) False
c) None
d) error
View Answer
Answer: a
Explanation: float(‘0.0’) is a finite number.
a) inf
b) nan
c) 0
d) 0.0
View Answer
Answer: b
Explanation: The result of float(‘inf’)-float(‘inf’) is undefined.
8. What is the output of the following?
print(math.isinf(float('-inf')))
advertisements
a) error, the minus sign shouldn’t havve been inside the brackets
b) error, there is no function called isinf
c) True
d) False
View Answer
Answer: c
Explanation: -float(‘inf’) is the same as float(‘-inf’).
Answer: d
Explanation: The value returned by ldexp(x, y) is x * (2 ** y). In the current case x is 1.0.
Answer: a
Explanation: The first element is the fractional part and the second element is the integral part of
the argument.
Answer: c
Explanation: TypeError, a string does not have __trunc__ method.
Answer: b
Explanation: math.e is the constant defined in the math module.
advertisements
Answer: a
Explanation: One is subtracted from the result of math.exp(p) and returned.
Answer: a
Explanation: The natural log of x is returned by default.
Answer: c
Explanation: log2() and log10() are defined in the math module.
Answer: b
Explanation: math.pow(a, b) returns a ** b.
Answer: b
Explanation: math.pow() returns a floating point number.
advertisements
Answer: b
Explanation: The function returns one floating point number.
Answer: c
Explanation: The function takes only one argument.
Python Questions and Answers – Operating
System
This set of Python Questions & Answers for Exams focuses on “Operating System”.
Answer: a
Explanation: It contains the name of the operating system dependent module imported such as
‘posix’, ‘java’ etc.
Answer: b
Explanation: os.geteuid() gives the user id while the os.getegid() gives the group id.
Answer: a
Explanation: It returns the name of the user who is currently logged in and is running the script.
advertisements
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
View Answer
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()
View Answer
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()
View Answer
Answer: a
Explanation: The function getcwd() (get current working directory) returns a string that represents th
present working directory.
Answer: b
Explanation: os.link(source, destination) will create a hard link from source to destination.
advertisements
Answer: a
Explanation: The function mkdir() creates a directory in the path specified.
Answer: a
Explanation: It is the function that allows you to create a symbolic link.