0% found this document useful (0 votes)
2K views

Python MCQ 3

This document contains questions and answers about Python core data types and basic operators. It includes 15 multiple choice questions about lists, tuples, dictionaries, classes, strings, functions, and basic math operators like floor division. The questions cover concepts like return types, string slicing, error handling, and data types.

Uploaded by

Mamatha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

Python MCQ 3

This document contains questions and answers about Python core data types and basic operators. It includes 15 multiple choice questions about lists, tuples, dictionaries, classes, strings, functions, and basic math operators like floor division. The questions cover concepts like return types, string slicing, error handling, and data types.

Uploaded by

Mamatha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 148

Python Questions and Answers – Core

Datatypes
This set of Python Questions & Answers focuses on “Core Data Types”.

1. Which of these in not a core datatype?


a) Lists
b) Dictionary
c) Tuples
d) Class
View Answer

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

4. Which of the following will run without errors(multiple answers possible) ?


a) round(45.8)
b) round(6352.898,2)
c) round()
d) round(7463.123,2,1)
View Answer
Answer:a,b
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
View Answer

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.

7. What error occurs when you execute?


apple = mango
a) SyntaxError
b) NameError
c) ValueError
d) TypeError
View Answer

Answer:b
Explanation:Banana is not defined hence name error.

8. Carefully observe the code and give the answer.

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.

9. What dataype is the object below ?


L = [1, 23, ‘hello’, 1] a) List
b) dictionary
c) array
d) tuple
View Answer

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.

11. Which of the following results in a SyntaxError(Multiple answers possible) ?


a) ‘”Once upon a time…”, she said.’
b) “He said, “Yes!””
c) ‘3\’
d) ”’That’s okay”’
View Answer

Answer:b,c
Explanation:Carefully look at the colons.

12. The following is displayed by a print function call:

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.

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’)
View Answer

Answer:c,d
Explanation:Execute in the shell.

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


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

Answer:a
Explanation:Executle help(math.trunc) to get details.

Python Questions and Answers – Basic


Operators
This section on Python aptitude questions and answers 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
View Answer

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
View Answer

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) Division
iv) Multiplication
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
View Answer

Answer: a
Explanation: For order of precedence, just remember this PEDMAS.

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


a) 7
b) 1
c) 0
d) 5
View Answer
Answer: b
Explanation: Modulus operator gives remainder. So, 22%3 gives 1 remainder.

advertisements

5. You can perform mathematical operation on String?


a) True
b) False
View Answer

Answer: b
Explanation: You can’t perform mathematical operation on string even if string looks like integers.

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


a) Left to Right
b) Right to Left
View Answer

Answer: a
Explanation: None.

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


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

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.

8. Which one of the following have the same precedence?


a) Addition and Subtraction
b) Multiplication and Division
c) a and b
d) None of the mentioned
View Answer

Answer: c
Explanation: None.

9. Int(x) means variable x is converted to integer.


a) True
b) False
View Answer

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.

Python Questions and Answers – Variable


Names
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) sometimes only
d) none of the mentioned
View Answer

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
View Answer

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
View Answer
Answer: d
Explanation: All the statements will execute successfully but at the cost of reduced readability.

advertisements

4. Which of the following is an invalid variable?


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

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
View Answer

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
View Answer

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
View Answer

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 charaters allowed
d) none
View Answer

Answer: a
Explanation: Variable names can be of any length.

advertisements

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
View Answer

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
View Answer

Answer: b
Explanation: in is a keyword.

Python Questions and Answers – Regular


Expressions
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
View Answer

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.

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
View Answer

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
View Answer

Answer: b
Explanation: It will look for the pattern at any position in the string.

5. What is the output of the following?

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’
View Answer

Answer: a
Explanation: This function returns all the subgroups that have been matched.

advertisements

6. What is the output of the following?

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’
View Answer

Answer: d
Explanation: This function returns the entire match.

7. What is the output of the following?

sentence = 'we are humans'


matched = re.match(r'(.*) (.*?) (.*)', sentence)
print(matched.group(2))

a) ‘are’
b) ‘we’
c) ‘humans’
d) ‘we are humans’
View Answer

Answer: c
Explanation: This function returns the particular subgroup.

8. What is the output of the following?

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’
View Answer

Answer: a
Explanation: This function returns a dictionary that contains all the mathches.

advertisements

9. What is the output of the following?

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’
View Answer

Answer: b
Explanation: This function returns all the subgroups that have been matched.

10. What is the output of the following?

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’
View Answer

Answer: d
Explanation: This function returns the particular subgroup.

Python Questions and Answers – Numeric


Types
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
View Answer

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
View Answer

Answer: c
Explanation: l (or L) stands for long.

advertisements

3. What is the type of inf?


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

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
View Answer

Answer: a
Explanation: ~x is equivalent to -(x+1).

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


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

Answer: a
Explanation: ~x is equivalent to -(x+1).

advertisements

6. Which of the following is incorrect?


a) x = 0b101
b) x = 0x4f5
c) x = 19023
d) x = 03964
View Answer
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
View AnswerAnswer: a
Explanation: cmp(x, y) returns 1 if x > y, 0 if x == y and -1 if x < y.[/expand] 8. Which of the
following is incorrect? a) float('inf') b) float('nan') c) float('56'+'78') d) float('12+34') [expand
title="View Answer"]Answer: d Explanation: '+' cannot be converted to a float.[/expand] 9.
What is the result of round(0.5) - round(-0.5)? a) 1.0 b) 2.0 c) 0.0 d) None of the mentioned
[expand title="View Answer"]Answer: b Explanation: Python 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.[/expand] 10. What does 3 ^ 4 evaluate to? a) 81 b) 12 c) 0.75 d) 7 [expand
title="View Answer"]Answer: d Explanation: ^ is the Binary XOR operator.[/expand]

Python Questions and Answers – While and


For Loops – 1
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “While and
For Loops”.

1. What is the output of the following?

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


View Answer

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 is the output of the following?

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.

3. What is the output of the following?

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 +=.

4. What is the output of the following?

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.

5. What is the output of the following?

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.

6. What is the output of the following?

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.

7. What is the output of the following?

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

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

9. What is the output of the following?

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.

10. What is the output of the following?

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.

Python Questions and Answers – While and


For Loops – 2
This set of Advanced Python Questions & Answers focuses on “While and For Loops”.

1. What is the output of the following?

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.

2. What is the output of the following?

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.

3. What is the output of the following?

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.

4. What is the output of the following?

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

5. What is the output of the following?

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.

6. What is the output of the following?

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

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

9. What is the output of the following?

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

Python Questions and Answers – While and


For Loops – 3
This set of Tough Python Questions & Answers focuses on “While and For Loops”.

1. What is the output of the following?

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.

2. 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
View Answer
Answer: b
Explanation: The instance of the string returned by upper() is being printed.

3. What is the output of the following?

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.

4. What is the output of the following?

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.

5. What is the output of the following?

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

6. What is the output of the following?


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
View Answer

Answer: c
Explanation: Objects of type int have no attribute upper().

7. 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
View Answer

Answer: a
Explanation: Changes do not happen in-place, rather a new instance of the string is returned.

advertisements

8. What is the output of the following?

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.

9. What is the output of the following?

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.

10. What is the output of the following?

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.

Python Questions and Answers – While and


For Loops – 4
This set of Python Questions & Answers focuses on “While and For Loops” and is useful for
freshers who are preparing for their interviews.

1. What is the output of the following?

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.

2. What is the output of the following?

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
View Answer

Answer: a
Explanation: Loops over the keys of the dictionary.

3. What is the output of the following?

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
View Answer

Answer: d
Explanation: Error, objects of type int aren’t iterable.

4. What is the output of the following?

d = {0: 'a', 1: 'b', 2: 'c'}


for x, y in d.items():
print(x, y)
advertisements

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.

5. What is the output of the following?


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
View Answer

Answer: b
Explanation: Loops over the keys and prints the values.

6. 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
View Answer

Answer: b
Explanation: Loops over the values.

7. What is the output of the following?

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
View Answer

Answer: d
Explanation: Causes a KeyError.

8. What is the output of the following?

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.

9. What is the output of the following?

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.

10. What is the output of the following?

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.

11. What is the output of the following?

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.

Python Questions and Answers – While and


For Loops – 5
This set of Python Questions & Answers focuses on “While and For Loops” and is useful for
experienced people who are preparing for their interviews.

1. What is the output of the following?

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.

2. What is the output of the following?

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

3. What is the output of the following?

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
View Answer

Answer: d
Explanation: Error, objects of type float cannot be interpreted as an integer.

4. What is the output of the following?

for i in range(int(float('inf'))):
print (i)
advertisements

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
View Answer

Answer: d
Explanation: OverflowError, cannot convert float infinity to integer.

5. What is the output of the following?

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
View Answer

Answer: b
Explanation: [::-1] reverses the list.

6. What is the output of the following?

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.

7. What is the output of the following?


for i in 'abcd'[::-1]:
print (i)

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

8. What is the output of the following?

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.

9. What is the output of the following?

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.

10. What is the output of the following?

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.

Python Questions and Answers – While and


For Loops – 6
This set of Python Technical Questions & Answers focuses on “While/For Loops”.

1. What is the output of the following?

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.

2. What is the output of the following?

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.

3. What is the output of the following?

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.

4. What is the output of the following?

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.

5. What is the output of the following?

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
View Answer

Answer: a
Explanation: Variable i takes the value of one character at a time.
6. What is the output of the following?

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
View Answer

Answer: c
Explanation: Variable i takes the value of one word at a time.

7. What is the output of the following?

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

8. What is the output of the following?

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.

9. What is the output of the following?

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.

10. What is the output of the following?

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
View Answer

Answer: a
Explanation: Variable i takes the value of one character at a time.

Python Questions and Answers – Strings –


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

1. What is the output when following statement is executed ?

1. >>>"a"+"bc"

a) a
b) bc
c) bca
d) abc
View Answer

Answer:d
Explanation:+ operator is concatenation operator.

2. What is the output when following statement is executed ?


1. >>>"abcd"[2:]

a) a
b) ab
c) cd
d) dc
View Answer

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_upercase
c) string.letters
d) string.lowercase_string.upercase
View Answer

Answer:b
Explanation:Execute in shell and check.

4. What is the output when following code is executed ?

1. >>> str1 = 'hello'


2. >>> str2 = ','
3. >>> str3 = 'world'
4. >>> str1[-1:]
advertisements
a) olleh
b) hello
c) h
d) o
View Answer
Answer:d
Explanation:-1 corresponds to the last index.

5. What arithmetic operators cannot be used with strings ?


a) +
b) *
c) –
d) **
View Answer

Answer:c,d
Explanation:+ is used to concatenate and * is used to multiply strings.

6. What is the output when following code is executed ?

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.

7. What is the output when following statement is executed ?

1. >>>print 'new' 'line'

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.

9. What is the output when following code is executed ?

1. >>>str1="helloworld"
2. >>>str1[::-1]

a) dlrowolleh
b) hello
c) world
d) helloworld
View Answer
Answer:a
Explanation:Execute in shell to verify.

10. print 0xA + 0xB + 0xC :


a) 0xA0xB0xC
b) Error
c) 0x22
d) 33
View Answer

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.

Python Questions and Answers – Strings –


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

1. What is the output of the following code ?

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.

2. What is the output of the following code ?

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.

3. What is the output of the following code ?

1. >>>example = "snow world"


2. >>>print "%s" % example[4:7]

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.

5. What is the output of the following code ?

1. >>>max("what are you")

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.

7. What is the output of the following code ?

1. >>>example = "helle"
2. >>>example.find("e")
advertisements
a) Error
b) -1
c) 1
d) 0
View Answer
Answer:c
Explanation:returns lowest index .

8. What is the output of the following code ?

1. >>>example = "helle"
2. >>>example.rfind("e")

a) -1
b) 4
c) 3
d) 1
View Answer

Answer:b
Explanation:returns highest index.

9. What is the output of the following code ?

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.

Python Questions and Answers – Strings –


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

1. What is the output when following statement is executed ?

1. >>>chr(ord('A'))

a) A
b) B
c) a
d) Error
View Answer

Answer:a
Explanation:Execute in shell to verify.

2. What is the output when following statement is executed ?

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.

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
View Answer

Answer:d
Explanation:Execute help(string.strip) to find details.

5. The format function returns :


a) Error
b) int
c) bool
d) str
View Answer

Answer:d
Explanation:Format function returns a string.

6. What is the output of “hello”+1+2+3 ?


a) hello123
b) hello
c) Error
d) hello6
View Answer

Answer:c
Explanation:Cannot concantenate str and int objects.

7. What is the output when following code is executed ?

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

9. What will be displayed by print(ord(‘b’) – ord(‘a’)) ?


a) 0
b) 1
c) -1
d) 2
View Answer

Answer:b
Explanation:ascii value of b is one more than a.

10. Say s=”hello” what will be the return value of type(s) ?


a) int
b) bool
c) str
d) String
View Answer

Answer:c
Explanation:str is used to represent strings in python.

Python Questions and Answers – Strings –


4
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
View Answer
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[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.

5. To check whether string s1 contains s2, use


a) s1.__contains__(s2)
b) s1 in s2
c) s1.contains(s2)
d) si.in(s2)
View Answer

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.

7. What is the output of the following code ?

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.

8. What is the output of the following code ?

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.

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

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
View Answer

Answer:b
Explanation:Execute in the shell to verify.

Python Questions and Answers – Strings –


5
This set of Basic Python Questions & Answers focuses on “Strings”.

1. What is the output of the following?

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.

2. What is the output of the following?

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.

3. What is the output of the following?

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.

4. What is the output of the following?

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.

5. What is the output of the following?

print('*', "abcdef".center(7), '*')

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.

6. What is the output of the following?

print('*', "abcdef".center(7), '*', sep='')


a) * abcdef *
b) * abcdef *
c) *abcdef *
d) * abcdef*
View Answer

Answer: d
Explanation: Padding is done towards the left-hand-side first when the final string is of odd length.

7. What is the output of the following?

print('*', "abcde".center(6), '*', sep='')

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

8. What is the output of the following?

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.

9. What is the output of the following?

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.

Python Questions and Answers – Strings –


6
This set of Python Quiz focuses on “Strings”.

1. What is the output of the following?

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.

2. What is the output of the following?

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.

3. What is the output of the following?


print("xyyzxyzxzxyy".count('yy', 2))

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

4. What is the output of the following?

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.

5. What is the output of the following?

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.

6. What is the output of the following?

print("xyyzxyzxzxyy".count('xyy', -10, -1))

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.

7. What is the output of the following?

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.

8. What is the default value of encoding in encode()?


a) ascii
b) qwerty
c) utf-8
d) utf-16
View Answer

Answer: c
Explanation: The default value of encoding is utf-8.

9. What is the output of the following?

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.

10. What is the output of the following?

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.

Python Questions and Answers – Strings –


7
This set of Online Python Quiz focuses on “Strings”.

1. What is the output of the following?

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.

2. What is the output of the following?

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.

3. What is the output of the following?

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.

4. What is the output of the following?


print("abcdef".find("cd") == "cd" in "abcdef")

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

5. What is the output of the following?

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.

6. What is the output of the following?

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.

7. What is the output of the following?

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
View Answer
Answer: a
Explanation: The numbers 0 and 1 represent the position at which the strings are present.

8. What is the output of the following?

print("Hello {1} and {0}".format('bin', 'foo'))


advertisements

a) Hello foo and bin


b) Hello bin and foo
c) error
d) none of the mentioned
View Answer

Answer: a
Explanation: The numbers 0 and 1 represent the position at which the strings are present.

9. What is the output of the following?

print("Hello {} and {}".format('foo', 'bin'))

a) Hello foo and bin


b) Hello {} and {}
c) error
d) Hello and
View Answer

Answer: a
Explanation: It is the same as Hello {0} and {1}.

10. What is the output of the following?

print("Hello {name1} and {name2}".format('foo', 'bin'))

a) Hello foo and bin


b) Hello {name1} and {name2}
c) error
d) Hello and
View Answer

Answer: c
Explanation: The arguments passed to the function format aren’t keyword arguments.

Python Questions and Answers – Strings –


8
This set of Python Multiple Choice Questions and Answers focuses on “Strings”.

1. What is the output of the following?

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
View Answer

Answer: a
Explanation: The arguments are accessed by their names.

2. What is the output of the following?

print("Hello {0!r} and {0!s}".format('foo', 'bin'))

a) Hello foo and bin


b) Hello ‘foo’ and bin
c) Hello foo and ‘bin’
d) error
View Answer

Answer: b
Explanation: !r causes the charactes ‘ or ” to be printed as well.

3. What is the output of the following?

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
View Answer

Answer: c
Explanation: IndexError, the tuple index is out of range.

4. What is the output of the following?

print("Hello {0[0]} and {0[1]}".format(('foo', 'bin')))


advertisements

a) Hello foo and bin


b) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)
c) error
d) none of the mentioned
View Answer

Answer: a
Explanation: The elements of the tuple are accessed by their indices.

5. What is the output of the following?

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
View Answer

Answer: a
Explanation: The arguments passed to the function format can be integers also.

6. What is the output of the following?

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
View Answer

Answer: b
Explanation: 2 is converted to binary, 10 to hexadecimal and 12 to octal.

7. What is the output of the following?

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

8. What is the output of the following?

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.

9. What is the output of the following?

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.

10. What is the output of the following?

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.

Python Questions and Answers – Strings –


9
This set of Python MCQs focuses on “Strings”.

1. What is the output of the following?

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.

2. What is the output of the following?

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.

3. What is the output of the following?

print('ab12'.isalnum())

a) True
b) False
c) None
d) error
View Answer

Answer: a
Explanation: The string has only letters and digits.

4. What is the output of the following?

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.

5. What is the output of the following?


print('ab'.isalpha())

a) True
b) False
c) None
d) error
View Answer

Answer: a
Explanation: The string has only letters.

6. What is the output of the following?

print('a B'.isalpha())

a) True
b) False
c) None
d) error
View Answer

Answer: b
Explanation: Space is not a letter.

7. What is the output of the following?

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

8. What is the output of the following?

print(''.isdigit())

a) True
b) False
c) None
d) error
View Answer
Answer: b
Explanation: If there are no characters then False is returned.

9. What is the output of the following?

print('my_string'.isidentifier())

a) True
b) False
c) None
d) error
View Answer

Answer: a
Explanation: It is a valid identifier.

10. What is the output of the following?

print('__foo__'.isidentifier())

a) True
b) False
c) None
d) error
View Answer

Answer: a
Explanation: It is a valid identifier.

Python Questions and Answers – Strings –


10
This set of Python Test focuses on “Strings”.

1. What is the output of the following?

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.

3. What is the output of the following?

print('a@ 1,'.islower())

a) True
b) False
c) None
d) error
View Answer

Answer: a
Explanation: There are no uppercase letters.

4. What is the output of the following?

print('11'.isnumeric())
advertisements

a) True
b) False
c) None
d) error
View Answer

Answer: a
Explanation: All the character are numeric.

5. What is the output of the following?

print('1.1'.isnumeric())

a) True
b) False
c) None
d) error
View Answer
Answer: b
Explanation: The character . is not a numeric character.

6. What is the output of the following?

print('1@ a'.isprintable())

a) True
b) False
c) None
d) error
View Answer

Answer: a
Explanation: All those characters are printable.

7. What is the output of the following?

print('''
'''.isspace())

a) True
b) False
c) None
d) error
View Answer

Answer: a
Explanation: A newline character is considered as space.

advertisements

8. What is the output of the following?

print('\t'.isspace())

a) True
b) False
c) None
d) error
View Answer

Answer: a
Explanation: Tabspaces are considered as spaces.

9. What is the output of the following?

print('HelloWorld'.istitle())
a) True
b) False
c) None
d) error
View Answer

Answer: b
Explanation: The letter W is uppercased.

10. What is the output of the following?

print('Hello World'.istitle())

a) True
b) False
c) None
d) Error
View Answer

Answer: a
Explanation: It is in title form.

Python Questions and Answers – Strings –


11
This set of Online Python Test focuses on “Strings”.

1. What is the output of the following?

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.

2. What is the output of the following?

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.

3. What is the output of the following?

print('''
\tfoo'''.lstrip())

a) \tfoo
b) foo
c) foo
d) none of the mentioned
View Answer

Answer: b
Explanation: All leading whitespace is removed.

4. What is the output of the following?

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.

5. What is the output of the following?

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

a) {97: 49, 98: 50, 99: 51}


b) {65: 49, 66: 50, 67: 51}
c) 321
d) 123
View Answer

Answer: a
Explanation: A translation table is returned by maketrans.

7. What is the output of the following?

print('a'.maketrans('ABC', '123'))

a) {97: 49, 98: 50, 99: 51}


b) {65: 49, 66: 50, 67: 51}
c) {97: 49}
d) 1
View Answer

Answer: a
Explanation: maketrans() is a static method so it’s behaviour does not depend on the object from
which it is being called.

Python Questions and Answers – Strings –


12
This set of Python Problems focuses on “Strings”.

1. What is the output of the following?

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.

3. What is the output of the following?

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.

4. What is the output of the following?

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.

5. What is the output of the following?

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.

6. What is the output of the following?

print('xyyxyyxyxyxxy'.replace('xy', '12', 0))

a) xyyxyyxyxyxxy
b) 12y12y1212x12
c) 12yxyyxyxyxxy
d) xyyxyyxyxyx12
View Answer

Answer: a
Explanation: The first 0 occurances of the given substring are replaced.

7. What is the output of the following?

print('xyyxyyxyxyxxy'.replace('xy', '12', 100))

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

8. What is the output of the following?

print('abcdefcdghcd'.split('cd'))

a) [‘ab’, ‘ef’, ‘gh’] b) [‘ab’, ‘ef’, ‘gh’, ”] c) (‘ab’, ‘ef’, ‘gh’)


d) (‘ab’, ‘ef’, ‘gh’, ”)
View Answer

Answer: b
Explanation: The given string is split and a list of substrings is returned.

9. What is the output of the following?

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.

10. What is the output of the following?

print('abcdefcdghcd'.split('cd', -1))

a) [‘ab’, ‘ef’, ‘gh’] b) [‘ab’, ‘ef’, ‘gh’, ”] c) (‘ab’, ‘ef’, ‘gh’)


d) (‘ab’, ‘ef’, ‘gh’, ”)
View Answer

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.

Python Questions and Answers – Strings –


13
This set of Python Question Bank focuses on “Strings”.

1. What is the output of the following?

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.

2. What is the output of the following?

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

3. What is the output of the following?

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.

4. What is the output of the following?

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.

5. What is the output of the following?

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.

6. What is the output of the following?

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.

7. What is the output of the following?


print('abcd'.translate({97: 98, 98: 99, 99: 100}))

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

8. What is the output of the following?

print('abcd'.translate({'a': '1', 'b': '2', 'c': '3', 'd': '4'}))

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.

9. What is the output of the following?

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.

10. What is the output of the following?

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.

Python Questions and Answers – Lists – 1


This set of Python Questions & Answers focuses on “Lists”.

1. Which of the following commands will create a list(multiple answers allowed) ?


a) list1 = list()
b) list1 = [] c) list1 = list([1, 2, 3])
d) list1 = [1, 2, 3] View Answer

Answer:a,b,c,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’] View Answer

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
View Answer

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
View Answer

Answer:c
Explanation:max returns the maximum element in the list.

advertisements

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


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

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
View Answer

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

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

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


a) Error
b) None
c) 25
d) 2
View Answer

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.

Python Questions and Answers – Lists – 2


This set of Python Coding Interview Questions & Answers focuses on “Lists”.

1. What is the output when following code is executed ?

1. >>>names = ['Amir', 'Bear', 'Charlton', 'Daman']


2. >>>print names[-1][-1]

a) A
b) Daman
c) Error
d) n
View Answer

Answer:d
Explanation:Execute in the shell to verify.

2. What is the output when following code is executed ?

1. names1 = ['Amir', 'Bear', 'Charlton', 'Daman']


2. names2 = names1
3. names3 = names1[:]
4.  
5. names2[0] = 'Alice'
6. names3[1] = 'Bob'
7.  
8. sum = 0
9. for ls in (names1, names2, names3):
10. if ls[0] == 'Alice':
11. sum += 1
12. if ls[1] == 'Bob':
13. sum += 10
14.  
15. print sum

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

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] View Answer

Answer:c
Explanation:Execute in the shell to verify.

5. What is the output when following code is executed ?

1. >>>list1 = [11, 2, 23]


2. >>>list2 = [11, 2, 2]
3. >>>list1 < list2 is

a) True
b) False
c) Error
d) None
View Answer

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

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.

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


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

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
View Answer

Answer:d
Explanation:Execute in the shell to verify.

Python Questions and Answers – Lists – 3


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

5. What is the output when following code is executed ?

1. >>>"Welcome to Python".split()

a) [“Welcome”, “to”, “Python”] b) (“Welcome”, “to”, “Python”)


c) {“Welcome”, “to”, “Python”}
d) “Welcome”, “to”, “Python”
View Answer

Answer:a
Explanation:split() function returns the elements in a list.

6. What is the output when following code is executed ?

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.

7. What is the output when following code is executed ?

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.

8. What is the output when following code is executed ?

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)

a) [1, 3] b) [4, 3] c) [1, 4] d) [1, 3, 4] View Answer

Answer:b
Explanation:Lists should be copied by executing [:] operation.

10. What is the output when following code is executed ?

1. def f(values):
2. values[0] = 44
3.  
4. v = [1, 2, 3]
5. f(v)
6. print(v)

a) [1, 44] b) [1, 2, 3, 44] c) [44, 2, 3] d) [1, 2, 3] View Answer

Answer:c
Explanation:Execute in the shell to verify.

Python Questions and Answers – Lists – 4


This set of Python Programming Interview Questions & Answers focuses on “Lists”.
1. What will be the output?

1. def f(i, values = []):


2. values.append(i)
3. return values
4.  
5. f(1)
6. f(2)
7. v = f(3)
8. print(v)

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


View Answer

Answer:c
Explanation:execute in the shell to verify

2. What will be the output?

1. names1 = ['Amir', 'Bala', 'Chales']


2.  
3. if 'amir' in names1:
4. print 1
5. else:
6. print 2

a) None
b) 1
c) 2
d) Error
View Answer

Answer:c
Explanation:execute in the shell to verify.

3. What will be the output?

1. names1 = ['Amir', 'Bala', 'Charlie']


2. names2 = [name.lower() for name in names1]
3.  
4. print names2[2][0]

a) None
b) a
c) b
d) c
View Answer

Answer:d
Explanation:List Comprehension are a shorthand for creating new lists.

4. What will be the output?


1. numbers = [1, 2, 3, 4]
2.  
3. numbers.append([5,6,7,8])
4.  
5. print len(numbers)
advertisements
a) 4
b) 5
c) 8
d) 12
View Answer
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 Above
View Answer

Answer:d
Explanation:in can be used in all data structures.

6. What will be the output?

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.

7. What will be the output?

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.

8. What will be the output?

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.  
7. values = [1, 2, 3]
8. print(increment_items(values, 2))
9. print(values)
advertisements
a) None
[3, 4, 5] b) None
[1, 2, 3] c) [3, 4, 5] [1, 2, 3] d) [3, 4, 5] None
View Answer
Answer:a
Explanation:Execute in the shell to verify.

9. What will be the output?

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.
View Answer

Answer:a
Explanation:Run the code to get a better understanding with many arguements.

10. What will be the output?

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’] View Answer

Answer:a
Explanation:Execute in the shell to verify.

Python Questions and Answers – Lists – 5


This set of Python Question Paper focuses on “Lists”.

1. What will be the output?

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] View Answer

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
View Answer

Answer:c
Explanation:Execute in the shell to verify.

3. What will be the output?

1. values = [[3, 4, 5, 1], [33, 6, 1, 2]]


2.  
3. v = values[0][0]
4. for row in range(0, len(values)):
5. for column in range(0, len(values[row])):
6. if v < values[row][column]:
7. v = values[row][column]
8.  
9. print(v)

a) 3
b) 5
c) 6
d) 33
View Answer

Answer:d
Explanation:Execute in the shell to verify.

4. What will be the output?

1. values = [[3, 4, 5, 1], [33, 6, 1, 2]]


2.  
3. v = values[0][0]
4. for lst in values:
5. for element in lst:
6. if v > element:
7. v = element
8.  
9. print(v)
advertisements
a) 1
b) 3
c) 5
d) 6
View Answer
Answer:a
Explanation:Execute in the shell to verify.

5. What will be the output?

1. values = [[3, 4, 5, 1 ], [33, 6, 1, 2]]


2.  
3. for row in values:
4. row.sort()
5. for element in row:
6. print(element, end = " ")
7. 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
View Answer

Answer:d
Explanation:Execute in the shell to verify.

6. What is the output?

1. matrix = [[1, 2, 3, 4],


2. [4, 5, 6, 7],
3. [8, 9, 10, 11],
4. [12, 13, 14, 15]]
5.  
6. for i in range(0, 4):
7. 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
View Answer

Answer:d
Explanation:Execute in the shell to verify.

7. What will be the output?

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.

9. What will be the output?

1. data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]


2.  
3. def ttt(m):
4. v = m[0][0]
5.  
6. for row in m:
7. for element in row:
8. if v < element: v = element
9.  
10. return v
11.  
12. print(ttt(data[0]))

a) 1
b) 2
c) 4
d) 5
View Answer

Answer:c
Explanation:Execute in the shell to verify.

10. What will be the output?

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]] View Answer

Answer:c
Explanation:Execute in the shell to verify.

Python Questions and Answers –


Dictionary – 1
This set of Python Questions & Answers focuses on “Dictionaries”.

1. Which of the following statements create a dictionary?(multiple answers allowed)


a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) d = (40:”john”, 45:”peter”)
View Answer

Answer:a,b,c
Explanation:Dictionaries are created by specifying keys and values

2. What are the keys?

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.

3. What will be the output?

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.

4. What will be the output?

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.

5. What will be the output?

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.

8. Suppose d = {“john”:40, “peter”:45}, to obtain the number of entries in dictionary what


command do we use
a) d.size()
b) len(d)
c) size(d)
d) d.len()
View Answer

Answer:b
Explanation:Execute in the shell to verify.

9. What will be the output?

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

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.

Python Questions and Answers – Tuples


This set of Python Questions & Answers focuses on “tuples”.

1. Which of the following is a Python tuple?


a) [1, 2, 3] b) (1, 2, 3)
c) {1, 2, 3}
d) {}
View Answer

Answer:b
Explanation:Tuples are characterised by their 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))
View Answer

Answer:b
Explanation:Values cannot be modified in the case of tuple.

3. What will be the output?

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.

4. What will be the output?

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.

5. What will be the output?

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.

6. What will be 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.

7. What will be the output?

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.

8. What will be the output?

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.

9. What will be the output?

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

10. What will be the output?

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.

Python Questions and Answers – Files – 1


This set of Python Questions & Answers 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”)
View Answer

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

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

Answer:a
Explanation:a is used to indicate that data is to be apended.

4. Which of the following statements are true? (multiple answers allowed)


a) A. When you open a file for reading, if the file does not exist, an error occurs.
b) When you open a file for reading, if the file does not exist, the program will open an empty
file.
c) When you open a file for writing, if the file does not exist, a new file is created.
d) When you open a file for writing, if the file exists, the existing file is overwritten with the
new file.
View Answer

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.

7. What is the output?

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.

10. The readlines() method returns


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

Answer:b
Explanation:Every line is stored in a list and returned

Python Questions and Answers – Files – 2


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

2. What is the output of this program?

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
View Answer

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?

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

4. Which one of the following is not attributes of file


a) closed
b) softspace
c) rename
d) mode
View Answer

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.

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
View Answer

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)

8. What is the output of this program?

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

Line No 1 – This is 2nd line

Line No 2 – This is 3rd line

Line No 3 – This is 4th 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.

10. What is the use of truncate() method in file?


a) truncates the file’s size
b) deletes the content of the file
c) deletes the file’s size
d) None of the mentioned
View Answer

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

Python Questions and Answers – Files-3


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 above
e) None of the above
View Answer
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 is the output of this program?

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

If entered name is sanfoundry


a) sanfoundry
b) sanfoundry, sanfoundry
c) San
d) None of the mentioned
View Answer

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

3. What is the output of this program?

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

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


a) r
b) w
c) +
d) b
View Answer

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
View Answer

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.

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
View Answer

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 is the output of this program?

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.

9. Correct syntax of file.writelines() is?


a) file.writelines(sequence)
b) fileObject.writelines()
c) fileObject.writelines(sequence)
d) None of the mentioned
View Answer

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.

Python Questions and Answers – Files – 4


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) All of the mentioned
d) None of the the mentioned
View Answer

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 the mentioned
View Answer

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 the mentioned
View Answer

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

Answer:a
Explanation:The read function reads all characters fh = open(“filename”, “r”)
content = fh.read().

advertisements

5. Which function is used to read single line from file?


a) Readline()
b) Readlines()
c) Readstatement()
d) Readfullline()
View Answer

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

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

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

Answer: a
Explanation: f.close()to close it and free up any system resources taken up by the open file.

9. Whether we can create a text file in python?


a) Yes
b) No
c) None of the mentioned
View Answer

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

Python Questions and Answers – Files-5


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+
View Answer

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
View Answer

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

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
View Answer

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__()
View Answer

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
View Answer

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

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’)
View Answer

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.

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
View Answer

Answer: d
Explanation: seek() takes at least one argument.

Python Questions and Answers – Function


–1
This section on Python aptitude questions and answers 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
View Answer

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 use for function?


a) Fun
b) Define
c) Def
d) Function
View Answer
Answer: c
Explanation: None.

3. What is the output of the below program?

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

4. What is the output of the below program?

1. def printMax(a, b):


2. if a > b:
3. print(a, 'is maximum')
4. elseif 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
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.

6. What is the output of the below program?

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.

7. What is the output of below program?

1. def say(message, times = 1):


2. print(message * times)
3.  
4. say('Hello')
5. say('World', 5)

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.

8. What is the output of the below program?

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


2. print('a is', a, 'and b is', b, 'and c is', c)
3.  
4. func(3, 7)
5. func(25, c = 24)
6. 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
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.

9. What is the output of below program?

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.  
9. print(maximum(2, 3))

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.

10. Which of the following is a features 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
View Answer

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.

Python Questions and Answers – Function


–2
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) Reuse of code
e) Information hiding
f) All of the mentioned
View Answer

Answer: f
Explanation: None.

2. What are the two types of functions?


a) Custom function
b) Built-in function
c) User-Defined function
d) System function
View Answer

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.

3. Where is function defined?


a) Module
b) Class
c) Another function
d) None of the mentioned
View Answer

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.

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
View Answer

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
View Answer

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.

7. What is the output of below program?

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.

8. What is the output of the below program?

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.

9. What is the output of the below program?

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)
advertisements
a) 212
32
b) 9
27
c) 567
98
d) None of the mentioned
View Answer
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 is the output of the below program?

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.

Python Questions and Answers – Function


–3
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
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.

2. What is the output of this program?

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.

3. What is the output of below program?

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.

4. Is Lambda contains return statements


a) True
b) False
View Answer

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.

6. Lambda contains block of statements


a) True
b) False
View Answer
Answer: b
Explanation: None.

7. What is the output of below program?

1. def f(x, y, z): return x + y + z


2.  
3. f(2, 30, 400)

a) 432
b) 24000
c) 430
d) None of the mentioned
View Answer

Answer: a
Explanation: None.

8. What is the output of below program?

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.

9. What is the output of this program?

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.

10. What is the output of this program?

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
View Answer

Answer: c
Explanation: None.

Python Questions and Answers – Exception


Handling
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
View Answer

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
View Answer

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

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
View Answer

Answer: b
Explanation: Refer documentation.

4. Is the following code valid?

try:
# Do something
except:
# Do something
else:
# Do something
advertisements

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
View Answer

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
View Answer

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
View Answer

Answer: d
Explanation: The finally block is always executed.

7. What is the output of the following 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
View Answer

Answer: b
Explanation: The finally block is executed even there is a return statement in the try block.

8. What is the output of the following code?

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.

9. What is the output of the following?

try:
if '1' != 1:
raise "someError"
else:
print("someError has not occured")
except "someError":
print ("someError has occured")

a) someError has occured


b) someError has not occured
c) invalid code
d) none of the mentioned
View Answer

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
View Answer

Answer: b
Explanation: It simply evaluates to False and does not raise any exception.

Python Questions and Answers – Argument


Passing 1
This set of Python Puzzles focuses on “Argument Passing”.

1. What is the type of each element in sys.argv?


a) set
b) list
c) tuple
d) string
View Answer

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
View Answer
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 is the output of the following code?

def foo(k):
k[0] = 1
q = [0]
foo(q)
print(q)

a) [0] b) [1] c) [1, 0] d) [0, 1] View Answer

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
View Answer

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

6. What is the output of the following 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
View Answer
Answer: a
Explanation: It is possible to pass function names as arguments to other functions.

7. What is the output of the following code?

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.

8. What is the output of the following code?

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

9. What is the output of the following 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
View Answer
Answer: b
Explanation: A new object is created in the function.

10. What is the output of the following 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] View Answer

Answer: b
Explanation: When a list is a default value, the same list will be reused.

Python Questions and Answers – Argument


Passing 2
This set of Tricky Python Questions & Answers focuses on “Argument Passing”.

1. What is the output of the following code?

def foo(k):
k = [1]
q = [0]
foo(q)
print(q)

a) [0] b) [1] c) [1, 0] d) [0, 1] View Answer

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
View Answer

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

4. What is the type of sys.argv?


a) set
b) list
c) tuple
d) string
View Answer

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
View Answer

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
View Answer

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
View Answer
Answer: d
Explanation: Refer documentation.

8. What is the output of the following 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
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.

10. What is the output of the following?

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

1. What is the output of the following?

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

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?

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
View Answer

Answer: b
Explanation: print() returns None.

3. What is the output of the following?

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

d) none of the mentioned


View Answer

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.

5. What is the output of the following?

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
View Answer

Answer: a
Explanation: i**+1 is evaluated as (i)**(+1).

6. What is the output of the following?

print([i.lower() for i in "HELLO"])

a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] b) ‘hello’


c) [‘hello’] d) hello
View Answer

Answer: a
Explanation: We are iterating over each letter in the string.
7. What is the output of the following?

print([i+j for i in "abc" for j in "def"])


advertisements

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.

8. What is the output of the following?

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’] View Answer

Answer: b
Explanation: The inner list is generated once for each value of j.

9. What is the output of the following?

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
View Answer

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

Python Questions and Answers – Mapping


Functions – 1
This set of Python Interview Questions & Answers focuses on “Mapping Functions”.
1. What is the output of the following?

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
View Answer

Answer: c
Explanation: The list should be the second parameter to the mapping function.

2. What is the output of the following?

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
View Answer

Answer: a
Explanation: Each element of the list is incremented.

3. What is the output of the following?

x = ['ab', 'cd']
print(list(map(upper, x)))

a) [‘AB’, ‘CD’] b) [‘ab’, ‘cd’] c) error


d) none of the mentioned
View Answer

Answer: c
Explanation: A NameError occurs because upper is a class method.

4. What is the output of the following?

def to_upper(k):
return k.upper()
x = ['ab', 'cd']
print(list(map(upper, x)))
advertisements

a) [‘AB’, ‘CD’] b) [‘ab’, ‘cd’] c) none of the mentioned


d) error
View Answer
Answer: d
Explanation: A NameError occurs because upper is a class method.

5. What is the output of the following?

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
View Answer

Answer: a
Explanation: Each element of the list is converted to uppercase.

6. What is the output of the following?

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
View Answer

Answer: c
Explanation: A list of Nones is printed as to_upper() returns None.

7. What is the output of the following?

x = ['ab', 'cd']
print(map(len, x))

a) [‘ab’, ‘cd’] b) [2, 2] c) [‘2’, ‘2’] d) none of the mentioned


View Answer

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

8. What is the output of the following?

x = ['ab', 'cd']
print(list(map(len, x)))

a) [‘ab’, ‘cd’] b) [2, 2] c) [‘2’, ‘2’] d) none of the mentioned


View Answer
Answer: b
Explanation: The length of each string is 2.

9. What is the output of the following?

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

10. What is the output of the following?

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.

Python Questions and Answers – Mapping


Functions – 2
This set of Tough Python Interview Questions & Answers focuses on “Mapping Functions”.

1. What is the output of the following?

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.

2. What is the output of the following?

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.

3. What is the output of the following?

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

4. What is the output of the following?

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.

5. What is the output of the following?

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.

6. What is the output of the following?

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.

7. What is the output of the following?

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

8. What is the output of the following?

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

10. What is the output of the following?

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.

Python Questions and Answers – Mapping


Functions – 3
This set of Python Interview Questions & Answers focuses on “Mapping Functions” and is
useful for freshers who are preparing for their interviews.

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

3. What is the output of the following?

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.

4. What is the output of the following?

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.

5. What is the output of the following?

x = [34, 56]
print(len(map(str, x)))

a) [34, 56] b) [’34’, ’56’] c) 34 56


d) error
View Answer
Answer: d
Explanation: TypeError, map has no len.

6. What is the output of the following?

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.

7. What is the output of the following?

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

8. What is the output of the following?

x = 1234
print(list(map(list, x)))

a) [1, 2, 3, 4] b) [1234] c) [[1], [2], [3], [4]] d) none of the mentioned


View Answer

Answer: d
Explanation: TypeError, int is not iterable.

9. What is the output of the following?

x = 1234
print(list(map(list, [x])))

a) [1, 2, 3, 4] b) [1234] c) [[1], [2], [3], [4]] d) none of the mentioned


View Answer

Answer: d
Explanation: TypeError, int is not iterable.

10. What is the output of the following?


x = 'abcd'
print(list(map([], x)))

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.

Python Questions and Answers – Operator


Overloading
This set of Python Questions & Answers focuses on “Operator Overloading” and is useful for
experienced people who are preparing for their interviews.

1. Which function is called when the following code is executed?

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

2. Which of the following 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
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

7. Which function overloads the >> operator?


a) __more__()
b) __gt__()
c) __ge__()
d) none of the mentioned
View Answer
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__()
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.

9. Which operator is overloaded by the __or__() function?


a) ||
b) |
c) //
d) /
View Answer

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__()
View Answer

Answer: c
Explanation: __floordiv__() is for //.

Python Questions and Answers – Random


This set of Python Aptitude Test focuses on “Randow module”.

1. What the does random.seed(3) return?


a) True
b) None
c) 3
d) 1
View Answer
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
View Answer

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

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.

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

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
View Answer

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
View Answer

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) return a list in which the elements 1, 2 and 3 are in random positions
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
View Answer

Answer: c
Explanation: The elements of the list passed to it are shuffled in-place.

advertisements

9. Which type of elements are accepted by random.shuffle()?


a) strings
b) lists
c) tuples
d) integers
View Answer

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

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

1. What is returned by math.ceil(3.4)?


a) 3
b) 4
c) 4.0
d) 3.0
View Answer

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
View Answer

Answer: a
Explanation: The floor function returns the biggest number that is smaller than or equal to the
number itself.

3. What is the output of print(math.copysign(3, -1))?


a) 1
b) 1.0
c) -3
d) -3.0
View Answer

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

4. What is displayed on executing print(math.fabs(-3.4))?


a) -3.4
b) 3.4
c) 3
d) -3
View Answer

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.

6. What is the value returned by math.fact(6)?


a) 720
b) 6
c) [1, 2, 3, 6] d) error
View Answer

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
View Answer

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

9. What is the output of print(math.factorial(4.5))?


a) 24
b) 120
c) error
d) none of the mentioned
View Answer
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
View Answer

Answer: a
Explanation: 0o10 is 8 and floor(8) is 8.

Python Questions and Answers – Math – 2


This set of Python Developer Questions & Answers focuses on “Mathematical Functions”.

1. What does the function math.frexp(x) return?


a) a tuple containing of the mantissa and the exponent of x
b) a list containing of the mantissa and the exponent of x
c) a tuple containing of the mantissa of x
d) a list containing of the exponent of x
View Answer

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
View Answer

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
View Answer
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
View Answer

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
View Answer

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.

7. What is the result of the following?

>>> -float('inf') + float('inf')

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

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
View Answer

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

Answer: a
Explanation: The first element is the fractional part and the second element is the integral part of
the argument.

Python Questions and Answers – Math – 3


This set of Python Developer Interview Questions & Answers focuses on “Maths”.

1. What is the result of math.trunc(3.1)?


a) 3.0
b) 3
c) 0.1
d) 1
View Answer
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
View Answer

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
View Answer

Answer: b
Explanation: math.e is the constant defined in the math module.

advertisements

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
View Answer

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
View Answer

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
View Answer

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
View Answer

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
View Answer

Answer: b
Explanation: math.pow() returns a floating point number.

advertisements

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

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
View Answer

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

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
View Answer

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
View Answer

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 above
View Answer

Answer: a
Explanation: It returns the name of the user who is currently logged in and is running the script.

advertisements

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
View Answer

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.

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
View Answer

Answer: b
Explanation: os.link(source, destination) will create a hard link from source to destination.

advertisements

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

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

Answer: a
Explanation: It is the function that allows you to create a symbolic link.

You might also like