Bird
0
0

Find the error in this code that tries to update an object's attribute:

medium📝 Debug Q14 of 15
Python - Methods and Behavior Definition
Find the error in this code that tries to update an object's attribute:
class Car:
    def __init__(self):
        self.speed = 0

    def accelerate(self):
        speed += 10

c = Car()
c.accelerate()
print(c.speed)
AUsing speed without self inside accelerate method
BMissing self in accelerate method parameter
CIncorrect print statement syntax
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Check method parameter

    accelerate has self parameter, so it can access attributes.
  2. Step 2: Identify attribute update

    Inside accelerate, speed += 10 tries to update speed but misses self. It should be self.speed += 10.
  3. Final Answer:

    Using speed without self inside accelerate method -> Option A
  4. Quick Check:

    Use self.speed to modify attribute [OK]
Quick Trick: Always use self.attribute to change object state inside methods [OK]
Common Mistakes:
  • Forgetting self. before attribute inside methods
  • Thinking print syntax is wrong
  • Assuming missing self parameter causes error here

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes