Python Quiz Answers

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

Q 1 - What is output for −

'search'. find('S') ?
A-s
B - -1
C-‘‘
D - None of the above
Ans: B
2. What will be the output of the following code?

def total(initial = 5, *num, **key):


count = initial
for n in num:
count+=n
for k in key:
count+=key[k]
return count
print(total(100,2,3, clouds=50, stars=100))

A - 260
B - 160
C - 155
D – 255
Ans: D
3. Select the correct code to create a check button under parent frame1 and it should be bind to
v1?
A - CheckButton(frame1, text=''Bold'' , command=CheckButton)
B - Checkbutton(frame1 , text=''Bold’’ ,variable=v1 ,command=processCheckbutton)
C - Checkbutton(frame1,text=''Bold'',variable=v1.set(),command=v1.set(processCheckbut ton)
D - Checkbutton(frame.set(f1) ,text.set(''bold'') ,command=v1.set(processCheckbutton)
Ans: B
4. Select the valid code to bind a canvas with a key event p −
A - Canvas.entered(Enter, p)
B - Canvas.entered(''<Enter> '',p)
C - Canvas.bind(''<key> '',p)
D - Canvas.bind(key,p)
Answer : C
5.What is the data type of the following
aTuple = (1, 'Jhon', 1+3j)
print(type(aTuple[2:3]))
a. list
b. complex
c. tuple
ans: C
6. What is the output of the following variable assignment

x = 75
def myfunc():
x=x+1
print(x)
myfunc()
print(x)

A. Error
B. 76
C. 1
D. None
Ans: A
7. Select the right way to create a string literal Ault'Kelly

A. str1 = ‘Ault\\’Kelly’
B. str1 = ‘Ault\’Kelly’
C. str1 = ‘Ault\’Kelly’
D. str1 = “””Ault’Kelly”””

ans: B
8. What is the value of the following Python Expression

print(36 / 4)

A. 9.0
B. 9

Ans: A
9. What is the output of the expression print(-18 // 4)

A. -4
B. 4
C. -5
D. 5

Ans : C

10. What will be the output of the following program ?

filter_none

edit

play_arrow

brightness_4

tuple = {}

tuple[(1,2,4)] = 8

tuple[(4,2,1)] = 10

tuple[(1,2)] = 12

_sum = 0

for k in tuple:

_sum += tuple[k]

print(len(tuple) + _sum)

Options:

A. 34
B. 12
C. 31
D. 33

Ans . D
11.What is the output of the following program?

str1 = '{2}, {1} and {0}'.format('a', 'b', 'c')


str2 = '{0}{1}{0}'.format('abra', 'cad')
print(str1, str2)
chevron_right
('c, b and a', 'abracadabra')

a) c, b and a abracad0
b) a, b and c abracadabra
c) a, b and c abracadcad
d) c, b and a abracadabra
Ans. (d)
12. What is the output of the following program?

a=2
b = '3.77'
c = -8
str1 = '{0:.4f} {0:3d} {2} {1}'.format(a, b, c)
print(str1)

a) 2.0000 2 -8 3.77
b) 2 3.77 -8 3.77
c) 2.000 3 -8 3.77
d) 2.000 2 8 3.77
Ans. (a)
13. What is the output of the following program?

line = "What will have so will"


L = line.split('a')
for i in L:
print(i, end=' ')

a) [‘What’, ‘will’, ‘have’, ‘so’, ‘will’]


b) Wh t will h ve so will
c) What will have so will
d) [‘Wh’, ‘t will h’, ‘ve so will’]
Ans. (b)
14. What is the output of the following program?

T = (2e-04, True, False, 8, 1.001, True)


val = 0
for x in T:
val += int(x)
print(val)

a) 12
b) 11
c) 11.001199999999999
d) TypeError
Ans. (b)
16. What is the output of the following program?

import threading

class thread(threading.Thread):
def __init__(self, thread_ID):
self.thread_ID = thread_ID
def run(self):
print(self.thread_ID)

thread1 = thread(100)

thread1.start()

a) 100
b) Compilation error
c) Runtime error
d) None of these

Ans. (c)
17. Which of the options below could possibly be the output of the following program?

from random import randrange


L = list()
for x in range(5):
L.append(randrange(0, 100, 2)-10)

# Choose which of outputs below are valid for this code.


print(L)

a) [-8, 88, 8, 58, 0]


b) [-8, 81, 18, 46, 0]
c) [-7, 88, 8, 58, 0]
d) [-8, 88, 94, 58, 0]
Ans. (a)
18. Which of the options below could possibly be the output of the following program

import math
import random
L = [1, 2, 30000000000000]
for x in range(3):
L[x] = math.sqrt(L[x])

# random.choices() is available on Python 3.6.1 only.


string = random.choices(["apple", "carrot", "pineapple"], L, k = 1)
print(string)

a) [‘pineapple’]
b) [‘apple’]
c) ‘pineapple’
d) both a and b
Ans. (d)
19. What is the output of the following program?

D = {1 : {'A' : {1 : "A"}, 2 : "B"}, 3 :"C", 'B' : "D", "D": 'E'}


print(D[D[D[1][2]]], end = " ")
print(D[D[1]["A"][2]])

a) D C
b) E B
c) D B
d) E KeyError
Ans. (d)
20. What is the output of the following program?

def REVERSE(L):
L.reverse()
return(L)
def YKNJS(L):
List = list()
List.extend(REVERSE(L))
print(List)

L = [1, 3.1, 5.31, 7.531]


YKNJS(L)

a) [1, 3.1, 5.31, 7.531]


b) [7.531, 5.31, 3.1, 1]
c) IndexError
d) AttributeError: ‘NoneType’ object has no attribute ‘REVERSE’
Ans. (b)
21. What is the output of the following program?

from math import sqrt


L1 = [x**2 for x in range(10)].pop()
L1 + = 19
print(sqrt(L1), end = " ")
L1 = [x**2 for x in reversed(range(10))].pop()
L1 + = 16
print(int(sqrt(L1)))

a) 10.0 4.0
b) 4.3588 4
c) 10 .0 4
d) 10.0 0
Ans. (c)
22. What is the output of the following program?

L1 = [1, 1.33, 'GFG', 0, 'NO', None, 'G', True]


val1, val2 = 0, ''
for x in L1:
if(type(x) == int or type(x) == float):
val1 += x
elif(type(x) == str):
val2 += x
else:
break
print(val1, val2)

a) 2 GFGNO
b) 2.33 GFGNOG
c) 2.33 GFGNONoneGTrue
d) 2.33 GFGNO
Ans. (d)
23. What is the output of the following program?

import sys
L1 = tuple()
print(sys.getsizeof(L1), end = " ")
L1 = (1, 2)
print(sys.getsizeof(L1), end = " ")
L1 = (1, 3, (4, 5))
print(sys.getsizeof(L1), end = " ")
L1 = (1, 2, 3, 4, 5, [3, 4], 'p', '8', 9.777, (1, 3))
print(sys.getsizeof(L1))

a) 0 2 3 10
b) 32 34 35 42
c) 48 64 72 128
d) 48 144 192 480
Ans. (c
24. What is the output of the following program?

data = 50
try:
data = data/0
except ZeroDivisionError:
print('Cannot divide by 0 ', end = '')
else:
print('Division successful ', end = '')

try:
data = data/5
except:
print('Inside except block ', end = '')
else:
print('GFG', end = '')

a) Cannot divide by 0 GFG


b) Cannot divide by 0
c) Cannot divide by 0 Inside except block GFG
d) Cannot divide by 0 Inside except block

Ans. (a)
25. What is the output of the following program?

dictionary1 = {'Google' : 1,
'Facebook' : 2,
'Microsoft' : 3
}
dictionary2 = {'GFG' : 1,
'Microsoft' : 2,
'Youtube' : 3
}
dictionary1.update(dictionary2);
for key, values in dictionary1.items():
print(key, values)

a) Compilation error
b) Runtime error
c) (‘Google’, 1)
(‘Facebook’, 2)
(‘Youtube’, 3)
(‘Microsoft’, 2)
(‘GFG’, 1)
d) None of these

Ans. (c)
26. What is the output of the following program?

temp = dict()
temp['key1'] = {'key1' : 44, 'key2' : 566}
temp['key2'] = [1, 2, 3, 4]
for (key, values) in temp.items():
print(values, end = "")

a) Compilation error
b) {‘key1’: 44, ‘key2’: 566}[1, 2, 3, 4]
c) Runtime error
d) None of the above

Ans. (b)
27. Which of the following function removes all leading and trailing whitespace in string?

A - replace(old, new [, max])

B - strip([chars])

C - swapcase()

D - title()

Ans: B
28. What is the output of the following code snippet?

func = lambda x: return x

print(func(2))

A. 2
B. 0
C. SyntaxError
D. X
Ans C
29. Which of the following are true regarding multiple statements per line in Python:

Multiple statements on the same line are separated by the & character.
Placing multiple statements on a single line is discouraged by PEP 8.
Specifying more than one statement on a line is typically not considered Pythonic, but may
be acceptable if it enhances readability.
Only variable assignment statements may occur multiply on a single line.
Ans: B and C both
30. Consider the following code snippet:

from functools import reduce


numbers = [1, 2, 3]
reduce(lambda x, y: x + y, numbers)

What is the output when you run the code?

A. 3
B. 6
C. 2
D. SyntaxError
Ans: B
31. Which one of the following statements about block comments is true:

Block comments should always be specified using triple-quoted multiline string literals.
You can create a block comment in Python by using a triple-quoted multiline string literal.
However, PEP 8 discourages the practice because, by convention, that type of free-standing
triple-quoted string literal is reserved for function docstrings.
There is no way to create a multiline block comment in Python.
ans: B
32. You have a set s defined as follows:

s = {100, 200, 300}

Which one of the following statements does not correctly produce the union of s and the set
{300, 400, 500}:

s.union({300, 400, 500})


s | set([300, 400, 500])
s | {300, 400, 500}
s.union(set([300, 400, 500]))

Ans: D
33. What is the result of this statement:

{1, 2, 3, 4, 5} - {3, 4} ^ {5, 6, 7}


set()
{3, 4, 5, 6, 7}
{1, 2}
{1, 2, 6, 7}
Ans D
34. What is the result of the highlighted expression:

>>> x = {1, 2, 3}
>>> y = {1, 2}

>>> y.ispropersubset(x)

False
True
set()
It raises an exception.
Ans: D
35. What does a threading.Lock do?

Allow only one thread at a time to access a resource


Pass messages between threads
Synchronize threads
SHIFT TO ALL CAPS
Wait until a thread is finished
Ans: A and C
36. How many CPUs (or cores) will the Python threading library take advantage of
simultaneously?

All of the available CPUs


None
One
Two
Ans: C
37. Race conditions are …

Two threads incorrectly accessing a shared resource


Testing which thread completes first
The weather on race day
Something you should add to your code
Ans: A
38. Assume you have a file object my_data which has properly opened a separated value file that
uses the tab character (\t) as the delimiter.

What is the proper way to open the file using the Python csv module and assign it to the variable
csv_reader?

Assume that csv has already been imported.

csv.tab_reader(my_data)
csv.reader(my_data, tab_delimited=True)
csv.reader(my_data, delimiter='\t')
csv.reader(my_data)
Ans: C
39. When writing to a CSV file using the .writerow() method of the csv.DictWriter object, what
must each key in the input dict represent? Below is an example:
with open('test_file.csv', mode='w') as csv_file:

writer = csv.DictWriter(
csv_file,
fieldnames=['first_col', 'second_col']
)
writer.writeheader()

# This input dictionary is what the question is referring


# to and is not necessarily correct as shown.
writer.writerow({'key1':'value1', 'key2':'value2'})
Each key must match up to the field names (column names) used to identify the column data
Each key indicates the column index as an integer for where the value should go
Each key must match up to the field names (index names) used to identify the row data
Each key indicates the row index as an integer for where the data should go
Ans: A
40. Which of the following would separate a string input_string on the first 2 occurences of the
letter “e”?

'e'.split(input_string, maxsplit=2)
input_string.split('e', 2)
input_string.split('e', maxsplit=2)
'e'.split(input_string, 2)
Ans: B and C
41. Python strings have a property called “immutability.” What does this mean?

Strings in Python can be represented as arrays of chars


Strings in Python can’t be changed
You can update a string in Python with concatenation
Strings can’t be divided by numbers

Ans: B
42. Given the file jack_russell.png, which of the following is the correct way to open the file for
reading as a buffered binary file? Select all that apply.

open('jack_russell.png', bytes=True)
open('jack_russell.png')
open('jack_russell.png', 'r')
open('jack_russell.png', 'wb')
open('jack_russell.png', 'rb')
Ans E
43. Whenever possible, what is the recommended way to ensure that a file object is properly
closed after usage?

By using the with statement


Making sure that you use the .close() method before the end of the script
It doesn’t matter
By using the try/finally block
Ans: A
44.When reading a file using the file object, what method is best for reading the entire file into a
single string?
.read_file_to_str()
.read()
.readlines()
.readline()

Ans:B
What gets printed?import resum = 0 pattern = 'back'if re.match(pattern, 'backup.txt'): sum += 1if
re.match(pattern, 'text.back'): sum += 2if re.search(pattern, 'backup.txt'): sum += 4if re.search(pattern,
'text.back'): sum += 8 print sum

A. 3

B. 7

C. 13

D. 14

E. 15

ANS: C
Is the given sentence true or false?

The following code will successfully print the days and then the monthsdaysOfWeek = ['Monday',
'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday
months = ['Jan', \\ 'Feb', \\ 'Mar', \\ 'Apr', \\ 'May',
\\ 'Jun', \\ 'Jul', \\ 'Aug', \\ 'Sep', \\ 'Oct', \\
'Nov', \\ 'Dec print "DAYS: %s, MONTHS %s" % (daysOfWeek, months)

A: True

B: False

Ans: False
What gets printed?x = Truey = Falsez = False if not x or y: print 1elif not x or not y
and z: print 2elif not x or y or not y and x: print 3else: print 4

A. 1
B. 2
C. 3
D. 4

Ans: 3
What gets printed?class parent: def __init__(self, param): self.v1 = param class child(parent): def
__init__(self, param): self.v2 = param obj = child(11)print "%d %d" % (obj.v1, obj.v2)

A. None None

B. None 11

C. 11 None

D. 11 11

E. Error is generated by program

Ans: E
What numbers get printed import pickle class account: def __init__(self, ID, balance): self.ID = ID
self.balance = balance def deposit(self, amount): self.balance += amount def withdraw(self, amount):
self.balance -= amount myac = account('123', 100) myac.deposit(800) myac.withdraw(500) fd = open(
"archive", "w" ) pickle.dump( myac, fd) fd.close() myac.deposit(200) print myac.balance fd = open(
"archive", "r" ) myac = pickle.load( fd ) fd.close() print myac.balance

A. 500 300

B. 500 500

C. 600 400

D. 600 600

E. 300 500

Ans:C
Assuming the filename for the code below is /usr/lib/python/person.pyand the program is run as:
python /usr/lib/python/person.py What gets printed?class Person: def __init__(self): pass def
getAge(self): print __name__ p = Person()p.getAge()

A. Person

B. GetAge

C. Usr.lib.python.person

D. __main__

E. An exception is thrown

Ans: D
What gets printed? def print_header(str): print "+++%s+++" % str print_header.category = 1
print_header.text = "some info" print_header("%d %s" % \\ (print_header.category, print_header.text))

A. +++1 some info+++

B. +++%s+++

C. 1

D. Some info

Ans: A
What gets printed?class NumFactory: def __init__(self, n): self.val = n def timesTwo(self): self.val *= 2
def plusTwo(self): self.val += 2 f = NumFactory(2)for m in dir(f): mthd = getattr(f,m) if callable(mthd):
mthd() print f.val

A. 2

B. 4

C. 6

D. 8

E. An exception is thrown

Ans: E

You might also like