LearnFrenzy
Sign in Take a free test

Tricky Python Output Questions · Exercise 4 of 4

Tricky Python Output Questions Find the Error

  • 10 questions
  • Page 1 of 1
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

Ten programs whose output surprises their authors: an UnboundLocalError, unhashable keys, a dict that changes size, a shared default, skipped list items, tuple assignment, a None from sort(), shallow copies, a recursive __str__ and a missing self. Choose the option that names the real problem.

Question 1 Medium

The program below stops with an error. Which statement correctly describes the problem?

main.py
price = 100
def apply_offer():
    print("Old price:", price)
    price = 80
    return price

apply_offer()
A UnboundLocalError: the assignment later in the function makes price local everywhere in it, so the first print reads a local with no value
B It prints Old price: 100
C NameError
D SyntaxError
Question page & discussion
Question 2 Easy

The program below stops with an error. Which statement correctly describes the problem?

main.py
visited = {}
visited[[0, 0]] = True
print(visited)
A It prints {[0, 0]: True}
B KeyError
C TypeError: lists are unhashable and cannot be keys; use the tuple (0, 0)
D ValueError
Question page & discussion
Question 3 Medium

The program below stops with an error. Which statement correctly describes the problem?

main.py
prices = {"tea": 20, "coffee": 35}
for item in prices:
    prices[item + "_large"] = prices[item] + 10
print(prices)
A It prints the four prices
B KeyError
C RuntimeError: the dictionary changed size during iteration; loop over list(prices) instead
D It loops forever
Question page & discussion
Question 4 Medium

Each student should start with no subjects. Which statement correctly identifies the bug?

main.py
def enrol(name, subjects=[]):
    subjects.append("Python")
    return {name: subjects}

print(enrol("Asha"))
print(enrol("Ravi"))
A The default list is created once and shared by both calls; use subjects=None and create a new list inside
B append() adds the item twice
C Dictionaries copy lists
D print shows a cached result
Question page & discussion
Question 5 Medium

All negative readings should be removed. Which statement correctly identifies the bug?

main.py
readings = [5, -1, -2, 7, -3]
for r in readings:
    if r < 0:
        readings.remove(r)
print(readings)
A remove() deletes the wrong value
B < 0 does not match -2
C Removing an item shifts the rest left while the loop index moves on, so -2 is skipped; build a new list: [r for r in readings if r >= 0]
D Lists cannot hold negative numbers
Question page & discussion
Question 6 Easy

The program below stops with an error. Which statement correctly describes the problem?

main.py
rgb = (255, 128, 0)
rgb[2] = 64
print(rgb)
A It prints (255, 128, 64)
B TypeError: tuples are immutable; build a new tuple, e.g. rgb = rgb[:2] + (64,)
C IndexError
D AttributeError
Question page & discussion
Question 7 Medium

The program below stops with an error. Which statement correctly describes the problem?

main.py
scores = [72, 95, 58]
ranked = scores.sort(reverse=True)
ranked.append(60)
A It appends 60 to the sorted list
B AttributeError: sort() returns None, so ranked is None and has no append(); use ranked = sorted(scores, reverse=True)
C TypeError
D IndexError
Question page & discussion
Question 8 Hard

Only the copy of the board should change. Which statement correctly identifies the bug?

main.py
board = [["-", "-"], ["-", "-"]]
trial = board.copy()
trial[0][0] = "X"
print(board)
A copy() returns the same list object
B copy() is shallow: the rows (inner lists) are shared; use copy.deepcopy(board) or [row[:] for row in board]
C Strings cannot be replaced in lists
D print shows trial instead of board
Question page & discussion
Question 9 Hard

The program below stops with an error. Which statement correctly describes the problem?

main.py
class Product:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return f"Product: {self}"

print(Product("Pen"))
A It prints Product: Pen
B TypeError
C RecursionError: {self} in the f-string calls __str__ again, endlessly; use {self.name}
D It prints Product: <Product object>
Question page & discussion
Question 10 Medium

The program below stops with an error. Which statement correctly describes the problem?

main.py
class Greeter:
    def hello(self):
        return "Hello!"

print(Greeter.hello())
A It prints Hello!
B AttributeError
C TypeError: hello needs an instance as self; call Greeter().hello() (or make it a @staticmethod)
D NameError
Question page & discussion
All exercises doneBack to Tricky Python Output QuestionsRevise the concepts or pick another topic

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links