Bird
Raised Fist0

Which code correctly implements this?

hard🚀 Application Q15 of Q15
Python - Object-Oriented Programming Foundations
You want to create a class BankAccount that stores an account holder's name and balance. It should have a method deposit(amount) that adds money to the balance only if the amount is positive. Which code correctly implements this?
Aclass BankAccount(): def __init__(self, name, balance=0): self.name = name self.balance = balance def deposit(self, amount): if amount > 0: self.balance += amount
Bclass BankAccount(): def __init__(self, name): self.name = name balance = 0 def deposit(self, amount): self.balance = self.balance + amount
Cclass BankAccount(): def __init__(self, name, balance=0): self.name = name self.balance = balance def deposit(self, amount): self.balance += amount
Dclass BankAccount(): def __init__(self, name): self.name = name self.balance = 0 def deposit(self, amount): if amount >= 0: self.balance = amount
Step-by-Step Solution
Solution:
  1. Step 1: Check __init__ method for attributes

    class BankAccount(): def __init__(self, name, balance=0): self.name = name self.balance = balance def deposit(self, amount): if amount > 0: self.balance += amount correctly sets self.name and self.balance with a default balance of 0.
  2. Step 2: Verify deposit method logic

    class BankAccount(): def __init__(self, name, balance=0): self.name = name self.balance = balance def deposit(self, amount): if amount > 0: self.balance += amount adds amount to self.balance only if amount > 0, which matches the requirement.
  3. Final Answer:

    Correctly implements the class with proper attribute initialization and deposit validation -> Option A
  4. Quick Check:

    Check attribute setup and positive amount condition [OK]
Quick Trick: Check attribute setup and validate input in methods [OK]
Common Mistakes:
MISTAKES
  • Not using self.balance to store balance
  • Adding amount without checking if positive
  • Overwriting balance instead of adding
  • Missing default balance initialization

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes