Computer scienceProgramming languagesPythonObject-oriented programmingMethods

Methods and attributes

Piggy bank

Report a typo

You are given a class PiggyBankthat represents an old-school moneybox in the shape of a pig. The class has two attributes: dollars and cents, their initial values are passed to the constructor.

Your goal is to implement an .add_money() method that:

  1. Accepts two parameters: deposit_dollars and deposit_cents

  2. Increases the money in the piggy bank by the deposited amount (increases the values of dollars and cents by deposit_dollars and deposit_cents, respectively)

  3. Ensures that the cents attribute never exceeds 99 (parameters deposit_dollars and deposit_cents of the add_money method can have any value)

Some considerations:

  • The PiggyBank constructor initializes dollars and cents with given values

  • The .add_money() method should handle any positive deposit amount

  • If adding cents results in 100 or more cents, convert the excess to dollars

For example, starting with PiggyBank(0, 50) (50 cents): adding 50 cents should result in 1 dollar and 0 cents (we will have to update the values of both dollars and cents because the attribute cents cannot be equal to 100).

Note:

  • Do not implement input processing

  • The class should work with any valid initial values and deposit amounts

Sample Input 1:

0 99

Sample Output 1:

2 0

Sample Input 2:

0 88

Sample Output 2:

1 89

Sample Input 3:

500 500

Sample Output 3:

506 1
Write a program in Python 3
class PiggyBank:
# create __init__ and add_money methods
___

Create a free account to access the full topic