Python 8.20 Develop a class BankAccount that supports these methods: _ _init_ _(
ID: 3763499 • Letter: P
Question
Python 8.20 Develop a class BankAccount that supports these methods:
_ _init_ _(): Initializes the bank account balance to the value of the input argument, or to 0 if no input argument is given.
withdraw(): Takes an amount as input and withdraws it from the balance.
deposit(): Takes an amount as input and adds it to the balance.
balance(): Returns the balance on the account.
Example:
>>> x = BankAccount(700)
>>> x.balance()
700.00
>>> x.withdraw(70)
>>> x.balance()
630.00
>>> x.deposit(7)
>>> x.balance()
637.00
8.40 In Problem 8.20, there are some problems with the implementation of the class BankAccount, and they are illustrated here:
>>> x = BankAccount(-700)
>>> x.balance()
-700
>>> x.withdraw(70)
>>> x.balance()
-770
>>> x. deposit(-7)
>>> x.balance()
Balance: -777
The problems are: (1) a bank account with a negative balance can be created, (2) the withdrawal amount is greater than the balance, and (3) the deposit amount is negative. Modify the code for the BankAccount class so that a ValueError exception is thrown for any of these violations, together with an appropriate message: 'Illegal balance', 'Overdraft', or 'Negative deposit'.
Example:
>>> x = BankAccount2(-700)
Traceback (most recent call last):
...
ValueError: Illegal balance
Explanation / Answer
working python code for first part.
# your code goes here
class BankAccount:
def __init__(self, init_bal):
"""Creates an account with the given balance."""
self.init_bal = init_bal
self.account = init_bal
def deposit(self, amount):
"""Deposits the amount into the account."""
self.amount = amount
self.account += amount
def withdraw(self, amount):
self.account -= amount
def balance(self):
print self.account
x = BankAccount(700)
x.balance()
x.withdraw(70)
x.balance()
x.deposit(7)
x.balance()
output:
700
630
637
working python code for part 2
# your code goes here
class BankAccount:
def __init__(self, init_bal):
if(init_bal >=0):
self.init_bal = init_bal
self.account = init_bal
else:
raise ValueError('a bank account with a negative balance can be created')
def deposit(self, amount):
"""Deposits the amount into the account."""
self.amount = amount
self.account += amount
def withdraw(self, amount):
if(amount>=0):
self.account -= amount
else:
raise ValueError('Negative value')
def balance(self):
print self.account
x = BankAccount(-5)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.