ABCDEFGHIJKLMNOPQRSTUVWXYZ
3
PYTHON UNIT 6,7,8 MCQ TEST
4
5
PREPARED BY - PROF MANISH PATELCorrect Answer
6
SrQUESTIONSABCDYour AnswerD
7
1Which option/s is/are a possible output of following code?
import random
SEL=random. randint (1, 3)
ANIMAL = ["DEER", "Monkey", "COW", "Kangaroo"]
for A in ANIMAL:
for AA in range (0, SEL):
print (A, end ="")
print ()
DEERDEER
MonkeysMonkey
COWCOW
KangarooKangaroo
DEER
DELHIMONKEY
DELHIMONKEYCOW
DEER
MONKEY
cow
KANGAROO
DEER
Monkey
COW
Kangaroo
DC
8
2Which option/s is/are a possible output of following code?
import random
PICK=random.randint (1,3)
CITY= ["DELHI", "MUMBAI", "CHENNAI", "KOLKATA"]
for I in CITY:
for J in range (0, PICK):
print (I, end = "")
print ()
DELHIDELHII
MUMBAIMUMBAI
CHENNAICHENNAI
KOLKATAKOLKATA
DELHI
DELHIMUMBAI
DELHIMUMBAICHENNAI
DELHI
MUMBAI
CHENNAI
KOLKATA
DELHI
MUMBAIMUMBAI
KOLKATAKOLKATAKOLKATA
b
9
3Which option is not a possible output of following code?
import random
def main():
p = "MY PROGRAM"
i = 0
while p[i] != "R":
l = random.randint(0,3) + 5
print (p[l],end ="_")
i += 1
main()
M_M_Y_PR_G_A_GG_G_R_O O_G_G_AC
10
4Which option is not a possible output of following code?
x = 3
N = random.randint (1, x)
for i in range (N):
print (i, "#", i + 1)
0#1
1#2
2#3
0#1
1#2
0#1
1#2
2#3
3#4
0#1A
11
5Which option/s is/are a possible output of following code?
import random
movie_list = ['The Jungle Book', 'Finding Nemo', 'Harry Potter', 'The Incredibles', 'Frozen']
movie1 = random.choice(movie_list)
movie2 = random.choice(movie_list)
print ( movie1 ," or " ,movie2)
Finding Nemo or Harry PotterHarry Potter or Toy StoryFrozen or The JungleToy Story or Spider ManD
12
6Which option/s is/are a possible output of following code?
import random
color_list = ["Pink", "Red", "Sky blue", "Yellow", "Green"]
random.shuffle(color_list)
print ( color_list )
[‘Sky Blue’, ‘Green’, ‘Yellow’, ‘Pink’, ‘Red’][‘Blue’, ‘Green’, ‘Pink’, ’Brown’, ‘Red’, ‘Black’][Yellow, Sky blue, Green, Pink, Red](‘Yellow’, ‘Red’, ‘Sky blue’, ‘Green’, ‘Pink’)C
13
7Which option/s is/are not a possible output of following code?
import random
list=[14, 62, 30, 57, 91]
str= ('Simply')
print ( random.choice(list),"and" , random.choice(str) )
57 and i62 and S20 and p30 and mA
14
8Which option/s is/are a possible output of following code?
import random
N=3
PICKER = random.randint (1, N)
COLOR = ["BLUE", "PINK", "GREEN", "RED"]
for I in COLOR :
for J in range (0, PICKER):
print (I, end = " ")
print ()
BLUE
PINK
GREEN
RED
BLUE
BLUEPINK
BLUEPINKGREEN
BLUEPINKGREENRED
PINK
PINKGREEN
GREENRED
BLUEBLUE
PINKPINK
GREEENGREEN
GREENGREEN
B
15
9Which option/s is/are a possible output of following code?
import random
n1= random.randrange(1, 10, 2)
n2= random.randrange(1, 10, 3)
print (n1,"and",n2)
2 and 73 and 48 and 108 and 9A
16
10To include the use of functions which are present in the random library, we must use the option:import randomrandom.himport.randomrandom.randomC
17
11 What will be the output of the following Python code?
import random
random.choice(2,3,4)
An integer other than 2, 3 and 4Either 2, 3 or 4Error3 onlyB
18
12 What will be the output of the following Python code?
import random
random.choice([10.4, 56.99, 76])
ErrorEither 10.4, 56.99 or 76Any number other than 10.4, 56.99 and 7656.99 onlyC
19
13What will be the output of the following Python function (random module has already been imported)?
random.choice('sun')
sunUeither s, u or nerrorA
20
14What will be the output of the following Python function if the random module has already been imported?
random.randint(3.5,7)
ErrorAny integer between 3.5 and 7, including 7Any integer between 3.5 and 7, excluding 7The integer closest to the mean of 3.5 and 7C
21
15Which of the following functions helps us to randomize the items of a list?seedrandomiseshuffleuniformD
22
16 What will be the output of the following Python function, assuming that the random library has already been included?
random.shuffle[1,2,24]
Randomized list containing the same numbers in any orderThe same list, that is [1,2,24]A list containing any random numbers between 1 and 24ErrorB
23
17What does random.seed(3) return?TRUENone31C
24
18Which is the only one of the following values the function random.randint(4) can return?43.4error5D
25
19 Which of the following will not be returned by random.choice(“1 ,”)?1Space tab,none of theseA
26
20Which of the following will never be displayed on executing print(random.choice({0: 1, 2: 3})) initially ?01KeyErrornone of theseC
27
21What does random.shuffle(x) do when x = [1, 2, 3]?errordo nothingshuffle elements of list in placenone of theseB
28
22Which type of elements are accepted by random.shuffle()?stringslisttuplesintegersD
29
23What is the range of values that random.random() can return?[0.0,1.0](0.0,1.0](0.0,1.0)[0.0,1.0)A
30
24In SimpleGUICS2Pygame, how many event handlers can be running at the same time?
1234A
31
25Which one is not a part of a frame?widgetControl AreaStatus AreaCanvasD
32
26Which of the following are valid calls to create_frame?
f = simplegui.create_Frame("My Frame", 100, 100)f = simplegui.create_frames("My Frame", 100, 100)frame = simplegui.create_frame(100, 100, 100)frame = simplegui.create_frame("Testing", 200, 200, 300)
B
33
27Which of the following are valid ways of making a canvas with a red background?
import simplegui
frame = simplegui.Create_frame("My Frame", 100, 100)
frame.set_canvas_background("Red")
frame.start()
import simplegui
frame = simplegui.create_frame("My Frame", 100, 100)
frame.set_canvas_background("red")
frame.start()
import simplegui
frame = simplegui.create_frame( 100, 100)
frame.set_canvas_background("red")
frame.start()
import simplegui
frame = simplegui.create_frame("My Frame", 100, 100)
frame.set_canvas_background("blue")
frame.start()
A
34
28In the following code, what does the number 100 represent?
my_button = frame.add_button("My Label", button_handler, 100)
Width of the button in pixels.
Width and height of the button in pixels.
Height of the button in pixels.
Position of the button in pixels.
A
35
29How many control objects are allowed in a frame?
0 or more1 or more2 or more3 or moreB
36
30In SimpleGUI, one kind of object can be added to the control panel that doesn't allow any handler. Thus, this object can't respond to anything. What kind of object is that?buttonlabelcanvastitleC
37
31When you enter text into an input field and press enter, the text is passed to the input field's event handler. What is the data type of the text?integercharstringbytesA
38
32When does the event handler for an input field get called?
when you press enterwhen you press escape
when you press runnone of theseB
39
33When a user pushes a button, what argument is passed to the event handler?stringsNo argumentsCommandParameters
A
40
34What does the draw handler parameter represent?canvasstringwidgetpanel
B
41
35What typically calls an event handler?the code we writesome code that we don't write which generates the eventit generates automaticallynone of theseD
42
36The game programming in python follows below given sequence in alphabetical order. What is the correct order of sequence?
1. Create frames
2. Define Classes
3. Define event handlers
4. Initialize global variables
5. Define helper functions
6. Register event handlers
7. Start frame and timers




1,2,3,4,5,6,74,5,2,1,3,6,74,5,2,6,3,1,74,5,2,3,1,6,7A
43
37What is the function used to generate a random integer in Python?randint()random()uniform()shuffle()B
44
38Which of the following is used to set the seed value for random module in Python?random.random()random.seed()random.randint()random.uniform()A
45
39Which of the following methods returns a random float between 0 and 1 in Python?random.random()random.seed()random.randint()random.uniform()D
46
40Which of the following methods generates a random element from a given list in Python?random.random()random.seed()random.randint()random.choice()A
47
41What does the draw handler parameter represent?The canvasThe frameThe object to be drawnThe location of the object to be drawnA
48
42What happens if you draw text outside the canvas coordinates?Some or none of the text is shown. Conceptually, the text is drawn at whatever coordinates are given, but only whatever text fits within the canvas coordinates is shown.Causes an errorThe text appears in the frame, but some or all of the text is shown outside the canvas area.The text coordinates are implicitly “wrapped” around using modular arithmetic, so that the text appears on the canvasC
49
43On the canvas, where is the origin, (0,0) located?in the middle of the canvason the top of the canvasat the top left corner of the canvasat the bottom left corner of the canvasB
50
44Which of the following functions can be used to draw a square on the canvas by passing four points?draw_poly()draw_polygon()draw_square()draw_lines()B
51
45Which of the following functions is used to write something on the canvas?draw()draw_text()write()draw_write()A
52
46Which of the following functions can be used to draw connected lines on the canvas?draw_polyline()draw()draw_polylines()lines()D
53
47Assume we have a canvas that is 200 pixels wide and 300 pixels high. We want to draw a green line between the upper left corner of the canvas and the lower right corner of the canvas. Which of the following calls will accomplish this?canvas.draw_line((300, 0), (0, 200), 10, "Green")canvas.draw_line((200, 0), (0, 300), 10, "Green")canvas.draw_line((0, 0), (200, 300), 10, "Green")canvas.draw_line((200, 300), (0, 0), 10, "Green")C
54
48Where should your draw_text, draw_line, and similar drawing calls be?In the handlers for the control objects that create or change the drawing, or their helper functionsAnywhere in your codeIn a draw handler, or a helper function called from itNowhereD
55
49Turn the following description into a program, and run it.

1. Create a 300-by-300 canvas.

2. Draw two circles with radius 20 and white lines of width 10. One is centered at (90,200) and one at (210,200).

3. Draw a red line of width 40 from (50,180) to (250,180).

4. Draw two red lines of width 5 from (55,170) to (90,120) and from (90,120) to (130,120).

5. Draw a red line of width 140 from (180,108) to (180,160).

The resulting picture is a simple diagram of what?
A computerA houseA motorcycleAn AutomobileD
56
50When the following code is executed, how many times is timer_handler called?

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

def timer_handler():
'''

timer = simplegui.create_timer(10, timer_handler)
timer.start()
The body of timer_handler isn’t given, as it is irrelevant for this question.
0 — The code hasn’t been written correctly.110Unlimited — It is called repeatedly until you stop the program.B
57
51You want a timer to create exactly 1000 events. Which of the following solutions are possible?Specify the number of timer events when creating the timer.Have a global counter for the number of timer calls.

In the timer handler, increment the counter. In the timer handler, check the count and possibly stop the timer.
In the timer handler, have a local counter for the number of timer calls.

In the timer handler, increment the counter. In the timer handler, check the count and possibly stop the timer.
Have a global counter for the number of timer calls.

Outside the timer handler, increment the counter. Outside the timer handler, check the count and possibly stop the timer.
A
58
52How do you change the frequency of a running timer, either increasing or decreasing the frequency? E.g., in the code below, we want code at the question marks that changes the timer. …
timer = simplegui.create_timer(1000, timer_handler)
timer.start()

???
You can't. But, you can stop this timer, and start a new one with a different frequency and same handler. timer.stop()
timer = simplegui.create_timer(300, timer_handler)
timer.start()
Create and start the timer again. timer = simplegui.create_timer(300, timer_handler)
timer.start()

Just run
create_timer
create_timer. It will change the timer. timer = simplegui.create_timer(300, timer_handler)

Just use
set_timer_interval
set_timer_interval. timer.set_timer_interval(300)
C
59
53How many timers can you have running at once?01Unlimited2B
60
54The Python code below uses a timer to execute the function update() 10 times, computing a good approximation to a common mathematical function. Examine the code, and run it while varying the input value n.

What is the common name for what this computes? # Mystery computation in Python
# Takes input n and computes output named result

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

# global state

result = 1
iteration = 0
max_iterations = 10

# helper functions

def init(start):
"""Initializes n."""
global n
n = start
print("Input is", n)

def get_next(current):
"""??? Part of mystery computation."""
return 0.5 * (current + n / current)

# timer callback

def update():
"""??? Part of mystery computation."""
global iteration, result
iteration += 1
# Stop iterating after max_iterations
if iteration >= max_iterations:
timer.stop()
print("Output is", result)
else:
result = get_next(result)

# register event handlers

timer = simplegui.create_timer(1, update)

# start program

init(13)
timer.start()
Cosine of nSquare root of nMultiplication by 2:
2n

Logarithm base 2
B
61
55Which of the following illustrate how to properly structure a keydown or keyup event handler? (For more advanced Python programmers, assume that you have just imported simplegui and haven't used from.)
def keydown_handler(key):
if key == "left":
def keydown_handler(key):
if key == simplegui.KEY_MAP["left"]:
def keydown_handler(key):
if "left" == simplegui.KEY_MAP[key]:
def keydown_handler(key):
if key == KEY_MAP["left"]:
C
62
56Assume you have a program with a keydown handler. You run it, and press a single key and hold it down continuously. How many times does the keydown handler get called?
Unlimited — i.e., repeatedly until you finally release the key
2 — once at the beginning and once when you release the key10B
63
57Several keys on the keyboard, such as Shift, CapsLock, and Ctrl, typically act to modify what happens when you press other keys, rather than doing anything on their own. When using the SimpleGUI keydown handler, how are such keys treated?No effect — e.g., pressing the Shift key does not create or modify the behavior of any event.
Independent key press events — e.g., pressing Shift by itself creates an event
Modify other key presses — e.g., pressing the 'a' key creates an event with a different value than pressing Shift and 'a' together.None of these are correctD
64
58The following code will generate the what? import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

def draw_handler(canvas):
canvas.draw_text('A', (20, 20), 12, 'Red')
canvas.draw_text('B', [30, 50], 20, 'Blue')
canvas.draw_text('C', (80, 50), 12, 'Gray', 'serif')

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
linecirclepolygontextA
65
59What will be the output of the following python code? import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

def timer_handler():
pass

timer = simplegui.create_timer(100, timer_handler)
print(timer.is_running())
timer.start()
print(timer.is_running())
timer.stop()
print(timer.is_running())
False True FalseTrue True FalseFalse True TrueFalse False FalseB
66
60What will be the output of the following code if keyboard button 'up' is pressed? # control the velocity of a ball using the arrow keys
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

# Initialize globals
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20

ball_pos = [WIDTH / 2, HEIGHT / 2]
vel = [0, 0]

# define event handlers
def draw(canvas):
# Update ball position
ball_pos[0] += vel[0]
ball_pos[1] += vel[1]

# Draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")

def keydown(key):
acc = 1
if key==simplegui.KEY_MAP["left"]:
vel[0] -= acc
print(vel[0])
print(vel[1])
elif key==simplegui.KEY_MAP["right"]:
vel[0] += acc
print(vel[0])
print(vel[1])
elif key==simplegui.KEY_MAP["down"]:
vel[1] += acc
print(vel[0])
print(vel[1])
elif key==simplegui.KEY_MAP["up"]:
vel[1] -= acc
print(vel[0])
print(vel[1])
#print ball_pos

# create frame
frame = simplegui.create_frame("Velocity ball control", WIDTH, HEIGHT)

# register event handlers
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)

# start frame
frame.start()
0
0
0
-1
1
0
-1 0C
67
61Which shape the following code will generate? import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

# Global Variables

canvas_width = 600
canvas_height = 600

# Event Handlers

def draw(canvas):

a = 450
b = 450
width = 100
canvas.draw_polygon([(a, b), (a + width, b), ((2 * a + width) / 2, b + width / 2 / math.tan(math.pi / 6))], 5, "Black", "Gray")

# Frame

frame = simplegui.create_frame("Shapes", canvas_width, canvas_height)

# Register Event Handlers

frame.set_draw_handler(draw)

# Remember to start the frame
frame.start()
Right Angle TriangleIsoceles TriangleEquilateral TriangleScalene TriangleD
68
62Which global variables are to provided necessarily in order to restart the game?
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import random
# Global Variables
canvas_width = 200
canvas_height = 200
reaction_time = 0
# Used to see if the circle should be drawn
started = False
count = 0
# Event Handlers
def check_start():
global started, count
count += 1
# This makes sure that the circle won't be drawn for at
# least one second after starting the frame or clicking
# the restart button.
if count > 10:
# This increases the likelihood of starting and ensures
# that the game will start within a time limit.
if count / 500.0 > random.random():
started = True
reaction_timer.start()
circle_timer.stop()
def increment():
global reaction_time
reaction_time += 1
def stop_button():
if started:
reaction_timer.stop()
print("Your reaction time was", reaction_time, "milliseconds")
def draw(canvas):
if started:
canvas.draw_circle([canvas_width / 2, canvas_height / 2], 60, 2, "Red", "Red")
def restart():
global ?
started = False
count = 0
reaction_time = 0
circle_timer.start()
# Frame
frame = simplegui.create_frame("Reaction Time", canvas_width, canvas_height)
# Register Event Handlers
frame.set_draw_handler(draw)
# By the way, these are labels. You can check the docs for
# more info.
label = frame.add_label("Get ready...")
frame.add_label("Press 'stop' when the red circle appears.")
frame.add_button("Stop", stop_button, 75)
frame.add_button("Restart", restart, 75)
# Note that the timers do not have the same name or purpose
circle_timer = simplegui.create_timer(100, check_start)
reaction_timer = simplegui.create_timer(1, increment)
# Start Frame and circle_timer
frame.start()
circle_timer.start()
startedcountreaction_timeAll of theseA
69
63Which arithmetic operator in next_color indicated by ? will ensures that you will never go to an invalid index, and also causes the cycle to repeat again from the first color when it reaches the end of the list? import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

# Global Variables

canvas_width = 300
canvas_height = 300
colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"]
# Different rainbow colors list (uncomment to use)
#colors = ["DeepPink", "Red", "DarkOrange", "Yellow", "Lime", "Aqua", "Magenta"]
index = 0

# Event Handlers

def draw(canvas):
frame.set_canvas_background(colors[index])

def next_color():
global index
index += 1
index = index ? len(colors)

# Frame and Timer

frame = simplegui.create_frame("Rainbow Canvas", canvas_width, canvas_height)
timer = simplegui.create_timer(500, next_color)

# Register Event Handlers

frame.set_draw_handler(draw)

# Start
frame.start()
timer.start()
ModulusMultiplicationFloor DivisionGreater thanB
70
64What is the output of the following code? import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

count = 0

def on_timer():
count += 1
print("Timer count:", count)

frame = simplegui.create_frame("Timer Example", 200, 200)
frame.start()

timer_interval = 1000
timer = simplegui.create_timer(timer_interval, on_timer)
timer.start()
There is no errorThe timer callback function cannot access the count variable The timer callback function should have one argumentThe timer should be set using set_timer_handler()A
71
65Which function in SimpleGUICS2Pygame is used to handle mouse clicks?set_mouseclick_handlerset_mousemove_handlerset_keydown_handlerset_draw_handlerA
72
66What is the format of the parameter passed to the mouse click handler in SimpleGUICS2Pygame?A tuple containing the x and y coordinates of the mouse pointerA single integer representing the position of the mouse pointerA list containing the x and y coordinates of the mouse pointerA dictionary containing the x and y coordinates of the mouse pointerC
73
67What is the default behavior of the set_mouseclick_handler function in SimpleGUICS2Pygame when the user clicks the right mouse button?It calls the specified function with the position of the right button clickIt calls the specified function with the position of the left button clickIt does not call the specified functionIt raises an exceptionB
74
68What is the purpose of the set_mousedrag_handler function in SimpleGUICS2Pygame?To handle mouse button presses and releasesTo detect when the mouse is dragged across the screenTo simulate a mouse click at a specific positionTo move the mouse pointer to a specific positionD
75
69What function can be used to load an image file in SimpleGUICS2Pygame?load_imagepygame.image.loadsimplegui.load_imagesimpleguics2pygame.load_imageC
76
70How can you display a loaded image on the canvas in SimpleGUICS2Pygame?By calling the draw_image function with the loaded image and a positionBy calling the draw function with the loaded image and a positionBy calling the draw_image function with the loaded image and a rect objectBy calling the draw function with the loaded image and a rect objectB
77
71What is the purpose of using the get_width and get_height methods of an image object in SimpleGUICS2Pygame?To calculate the aspect ratio of the imageTo determine the original size of the imageTo set the size of the image on the canvasTo resize the image to a specific width and heightA
78
72What is the purpose of using the draw_image function in SimpleGUICS2Pygame?To draw a loaded image on the canvasTo create a new image objectTo resize an image objectTo rotate an image objectB
79
73Which of the following methods can be used to load a sound file in SimpleGUICS2Pygame?pygame.mixer.load()simplegui.load_sound()simplegui.load()pygame.load_sound()A
80
74How can you play a sound in SimpleGUICS2Pygame?By calling the play() method of the sound objectBy calling the play_sound() functionBy passing the sound object as an argument to the play_sound method of the pygame.mixer moduleBy passing the sound object as an argument to the pygame.mixer.music.play functionA
81
75How can you stop a playing sound in SimpleGUICS2Pygame?By calling the stop() method of the sound objectBy calling the stop_sound() functionBy passing the sound object as an argument to the pygame.mixer.music.stop functionBy calling the pause() method of the sound object
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102