Question

In: Computer Science

Python 3.5: Consider the Account class that we developed previously. Task 1: Review the code in...

Python 3.5:

Consider the Account class that we developed previously.

Task 1:

Review the code in the constructor in the Account class. What happens if we attempt to make a new account with a negative balance? Use exception handling to raise an exception if a balance less that 0 is given. Add a message to the constructor saying "Warning! Your balance is equal to or less than 0!".

Task 2:

Next, in the Account class's withdraw() method, add code to check if the amount given exceeds the account's balance. If it does, then raise a ValueError. Add a message to the withdraw() method saying "ERROR: Insufficient funds!". The balance in the account should remain unchanged.

Also, add code to check if the amount of withdrawal is zero. You should raise a ValueError if the amount is less than or equal to zero.

Note: you must submit the entire class definition.

For example:

Test Output
try:
account1 = Account(1122, 0, 3.35)
except ValueError as x:
print (x)
Warning! Your balance is equal to or less than 0.
try:
account2 = Account(1122, 100, 3.35)
account2.withdraw(200)
except ValueError as x:
print (x)
print(account2.get_balance())
ERROR: Insufficient funds!
100
try:
account2 = Account(1122, 100, 3.35)
account2.withdraw(0)
except ValueError as x:
print (x)
print(account2.get_balance())
ERROR: Invalid amount!
100

Account Code:

------------------------------------------------------

class Account:

def __init__(self, id, balance: int=None, annual_interest_rate: int=None):
if balance > 0:
self.__id = id
if balance == None:
self.__balance = 100
else:
self.__balance = balance
if annual_interest_rate == None:
self.__annualInterest = 0
else:
self.__annualInterest = annual_interest_rate
else:
raise ("Warning! Your balance is equal to or less than 0!")
def get_id(self):
return self.__id
def get_balance(self):
return self.__balance
def get_annual_interest_rate(self):
return self.__annualInterest
def get_monthly_interest_rate(self):
return (self.__annualInterest/12)
def get_monthly_interest(self):
return (self.__balance * (self.__annualInterest/12)/100)
def deposit(self, amount: int=None):
if amount == None:
deposit = 0
else:
deposit = amount
self.__balance = self.__balance + amount
return
def withdraw(self, amount: int=None):
if amount == None:
withdraw = 0
else:
withdraw = amount
self.__balance = self.__balance - withdraw
return
def get_balance(self):
return self.__balance

Solutions

Expert Solution

# link for code in case indentation mess up: https://repl.it/Gp0u/11

class Account:
def __init__(self, id, balance: int=None, annual_interest_rate: int=None):
if balance > 0:
self.__id = id
if balance == None:
self.__balance = 100
else:
self.__balance = balance
if annual_interest_rate == None:
self.__annualInterest = 0
else:
self.__annualInterest = annual_interest_rate
else:
raise ValueError("Warning! Your balance is equal to or less than 0!")
def get_id(self):
return self.__id
def get_balance(self):
return self.__balance
def get_annual_interest_rate(self):
return self.__annualInterest
def get_monthly_interest_rate(self):
return (self.__annualInterest/12)
def get_monthly_interest(self):
return (self.__balance * (self.__annualInterest/12)/100)
def deposit(self, amount: int=None):
if amount == None:
deposit = 0
else:
deposit = amount
self.__balance = self.__balance + amount
return
def withdraw(self, amount: int=None):
if amount == None:
withdraw = 0
elif amount <= 0:
raise ValueError("ERROR: Invalid amount!")
elif amount > self.__balance:
raise ValueError("ERROR: Insufficient funds!")
withdraw = amount
self.__balance = self.__balance - withdraw
return
def get_balance(self):
return self.__balance

try:
account1 = Account(1122, 0, 3.35)
except ValueError as x:
print (x)


Related Solutions

Python Explain Code #Python program class TreeNode:
Python Explain Code   #Python program class TreeNode:    def __init__(self, key):        self.key = key        self.left = None        self.right = Nonedef findMaxDifference(root, diff=float('-inf')):    if root is None:        return float('inf'), diff    leftVal, diff = findMaxDifference(root.left, diff)    rightVal, diff = findMaxDifference(root.right, diff)    currentDiff = root.key - min(leftVal, rightVal)    diff = max(diff, currentDiff)     return min(min(leftVal, rightVal), root.key), diff root = TreeNode(6)root.left = TreeNode(3)root.right = TreeNode(8)root.right.left = TreeNode(2)root.right.right = TreeNode(4)root.right.left.left = TreeNode(1)root.right.left.right = TreeNode(7)print(findMaxDifference(root)[1])
Task 1. to be completed. 1.1 - Write a small Python snippet code that can revert...
Task 1. to be completed. 1.1 - Write a small Python snippet code that can revert an array of N element (Please do not use the default function “reverse()). 1.2 - There is a famous programming (algorithm) concept that can vastly reduce the complexity of Recursive Fibonacci Algorithm. 2 .a) What is the name of this concept 2.b) Write the execution time and memory complexity of Fibonacci sequences, once this concept is applied 2.c) Explain the main idea behind this...
Using python class: Design a class called Account CLASS NAME:    Account ATTRIBUTES: -nextAcctID: int    #NOTE-...
Using python class: Design a class called Account CLASS NAME:    Account ATTRIBUTES: -nextAcctID: int    #NOTE- class-level attribute initialized to 1000 -acctID: int -bank: String -acctType: String (ex: checking, savings) -balance: Float METHODS: <<Constructor>>Account(id:int, bank: String, type:String, bal:float) +getAcctID(void): int                        NOTE: retrieving a CLASS-LEVEL attribute! -setAcctID(newID: int): void           NOTE: PRIVATE method +getBank(void): String +setBank(newBank: String): void +getBalance(void): float +setBalance(newBal: float): void +str(void): String NOTE: Description: prints the information for the account one item per line. For example: Account #:        ...
Modify the Fraction class created previously as follows. Read the entire description (Code at the bottom...
Modify the Fraction class created previously as follows. Read the entire description (Code at the bottom also using C++ on visual studios) Avoid redundant code member variables numerator & denominator only do not add any member variables Set functions set numerator set denominator set fraction with one argument set fraction with two arguments set fractions with three arguments (whole, numerator, denominator) to avoid redundancy and have error checking in one place only, call setFractions with three arguments in all other...
So previously in my class I had to write a python program where the user would...
So previously in my class I had to write a python program where the user would enter the price for 5 different items, and it would calculate the subtotal, total tax owed and the total amount owed. Now I need to write a program that would do the same but would be done using modules in the code, I am having a hard time figuring modules out. Below is the code from the original program not using modules: # Enter...
I need this code in java. Task (1) Create two files to submit: ItemToPurchase.java - Class...
I need this code in java. Task (1) Create two files to submit: ItemToPurchase.java - Class definition ShoppingCartPrinter.java - Contains main() method Build the ItemToPurchase class with the following specifications: Private fields String itemName - Initialized in default constructor to "none" int itemPrice - Initialized in default constructor to 0 int itemQuantity - Initialized in default constructor to 0 Default constructor Public member methods (mutators & accessors) setName() & getName() (2 pts) setPrice() & getPrice() (2 pts) setQuantity() & getQuantity()...
LOOK over code Python The task aims to develop a Kalman filter that is able to...
LOOK over code Python The task aims to develop a Kalman filter that is able to hit the moving target (the pink box) in as many situations as possible. However, there are some limitations: IT IS NOT PERMITTED TO CHANGE THE PRODEIL AND TARGET CODE IT IS ALSO NOT ALLOWED TO CHANGE THE GAME LOOP, OTHER THAN WHAT HAS BEEN COMMENTS SHALL BE CHANGED WHEN THE Kalman CLASS IS IMPLEMENTED I have made the callman class, but my question is;...
CODE IN PYTHON: Your task is to write a simple program that would allow a user...
CODE IN PYTHON: Your task is to write a simple program that would allow a user to compute the cost of a road trip with a car. User will enter the total distance to be traveled in miles along with the miles per gallon (MPG) information of the car he drives and the per gallon cost of gas. Using these 3 pieces of information you can compute the gas cost of the trip. User will also enter the number of...
This task is about classes and objects, and is solved in Python 3. We will look...
This task is about classes and objects, and is solved in Python 3. We will look at two different ways to represent a succession of monarchs, e.g. the series of Norwegian kings from Haakon VII to Harald V, and print it out like this: King Haakon VII of Norway, accession: 1905 King Olav V of Norway, accession: 1957 King Harald V of Norway, accession: 1991 >>> Make a class Monarch with three attributes: the name of the monarch, the nation...
This needs to be in Python and each code needs to be separated. Design a class...
This needs to be in Python and each code needs to be separated. Design a class for a fast food restaurant meals that should have 3 attributes; Meal Type (e.g., Burger, Salad, Taco, Pizza); Meal size (e.g., small, medium, large); Meal Drink (e.g., Coke, Dr. Pepper, Fanta); and 2 methods to set and get the attributes. Write a program that ask the user to input the meal type, meal size, and meal drinks. This data should be stored as the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT