In: Computer Science
Write a program that calculates the balance of a savings account at the end of a period of time. It should ask the user for the annual interest rate, the starting balance, and the number of months that have passed since the account was established. A loop should then iterate once for every month, performing the following:
After the last iteration, the program should display the ending balance, the total amount of deposits, the total amount of withdrawals, and the total interest earned.
NOTE: If a negative balance is calculated at any point, a message should be displayed indicating the account has been closed, and the loop should terminate.
CODE:
#A function to do necessary calculation on user's account.
def calculate():
#Asking user for annual interest rate, starting balance and
months.
annual_interest = float(input("Enter the annual interest rate:
"))
start_balance = float(input("Enter the starting balance: "))
months = int(input("Enter the number of months: "))
#Variables to store monthly interest rate, total deposit, total
withdrawl and total interest earned.
monthly_interest_rate = annual_interest/12
total_deposit = 0
total_withdrawl = 0
total_interest = 0
#Looping through months one by one.
for i in range(0,months):
#Intitializing amount deposit to -1 to check for negative
inputs.
amount_deposit = -1
#It only consider positive input format amount deposit.
while(amount_deposit<0):
amount_deposit = float(input("Amount deposited in " + str(i+1) + "
month: "))
#Adding the depoisted amount to account balance.
start_balance += amount_deposit
#Adding to total deposit.
total_deposit += amount_deposit
#Same as amount deposit.
amount_withdrawn = -1
while(amount_withdrawn<0):
amount_withdrawn = float(input("Amount withdrawn in " + str(i+1) +
" month: "))
start_balance -= amount_withdrawn
#Checking for negative balance.
if(start_balance<0):
print("Account has been closed")
return
total_withdrawl += amount_withdrawn
#Calculating the monthly interest.
monthly_interest = (start_balance*monthly_interest_rate)/100
#Adding to total interest.
total_interest += monthly_interest
#Adding the interest earned to account balance.
start_balance += monthly_interest
#Printing the required information at the end of the loop.
print("Ending balance: ", round(start_balance))
print("Total deposit: ",total_deposit)
print("Total withdrawl: ",total_withdrawl)
print("Total interest earned: ",round(total_interest))
calculate()
CODE SCREENSHOT:
CODE OUTPUT: