Question

In: Computer Science

This Python assignment will involve implementing a ​bank program that manages bank accounts​ and allows for...

This Python assignment will involve implementing a ​bank program that manages bank accounts​ and allows for deposits, withdrawals, and purchases. USE THE PREASSIGNED CODE BELOW:

The program will initially load a list of accounts from a .txt file, and deposits and withdrawals from additional .csv files. Then it will parse and combine all of the data and store it in a dictionary.

Steps

  1. Complete the required functions

    1. Implement all of the functions defined in the ​bank_accounts.py

      1. Docstrings have already been provided

      2. You can create any number of helper functions (with docstrings)

      3. The ​main​ function has already been implemented for you

      4. Add ​brief​ comments to all non-trivial lines of code

def init_bank_accounts(accounts, deposits, withdrawals):
'''
Loads the given 3 files, stores the information for individual bank accounts in a dictionary,
and calculates the account balance.

Accounts file contains information about bank accounts.
Each row contains an account number, a first name, and a last name, separated by vertical pipe (|).
Example:
1|Brandon|Krakowsky

Deposits file contains a list of deposits for a given account number.
Each row contains an account number, and a list of deposit amounts, separated by a comma (,).
Example:
1,234.5,6352.89,1,97.60

Withdrawals file contains a list of withdrawals for a given account number.
Each row contains an account number, and a list of withdrawal amounts, separated by a comma (,).
Example:
1,56.3,72.1

Stores all of the account information in a dictionary named 'bank_accounts', where the account number is the key,
and the value is a nested dictionary. The keys in the nested dictionary are first_name, last_name, and balance,
with the corresponding values.
Example:
{'1': {'first_name': 'Brandon', 'last_name': 'Krakowsky', 'balance': 6557.59}}

This function calculates the total balance for each account by taking the total deposit amount
and subtracting the total withdrawal amount.
'''

bank_accounts = {}

#insert code

return bank_accounts

def round_balance(bank_accounts, account_number):
'''Rounds the given account balance.'''

pass

def get_account_info(bank_accounts, account_number):
'''Returns the account information for the given account_number as a dictionary.
Example:
{'first_name': 'Brandon', 'last_name': 'Krakowsky', 'balance': 6557.59}
If the account doesn't exist, returns None.
'''

pass

def withdraw(bank_accounts, account_number, amount):
'''Withdraws the given amount from the account with the given account_number.
Raises a RuntimeError if the given amount is greater than the available balance.
If the account doesn't exist, prints a friendly message.
Rounds and prints the new balance.
'''

pass

def deposit(bank_accounts, account_number, amount):
'''Deposits the given amount into the account with the given account_number.
If the account doesn't exist, prints a friendly message.
Rounds and prints the new balance.
'''

pass

def purchase(bank_accounts, account_number, amounts):
'''Makes a purchase with the total of the given amounts from the account with the given account_number.
Raises a RuntimeError if the total purchase, plus the sales tax (6%), is greater than the available balance.
If the account doesn't exist, prints a friendly message.
Rounds and prints the new balance.
'''

pass

def calculate_sales_tax(amount):
'''Calculates and returns a 6% sales tax for the given amount.'''

pass

def main():

#load and get all account info
bank_accounts = init_bank_accounts('accounts.txt', 'deposits.csv', 'withdrawals.csv')

#for testing
#print(bank_accounts)

while True:

#print welcome and options
print('\nWelcome to the bank! What would you like to do?')
print('1: Get account info')
print('2: Make a deposit')
print('3: Make a withdrawal')
print('4: Make a purchase')
print('0: Leave the bank')

# get user input
option_input = input('\n')

# try to cast to int
try:
option = int(option_input)

# catch ValueError
except ValueError:
print("Invalid option.")

else:

#check options
if (option == 1):

#get account number and print account info
account_number = input('Account number? ')
print(get_account_info(bank_accounts, account_number))

elif (option == 2):

# get account number and amount and make deposit
account_number = input('Account number? ')

# input cast to float
amount = float(input('Amount? '))

deposit(bank_accounts, account_number, amount)

elif (option == 3):

# get account number and amount and make withdrawal
account_number = input('Account number? ')

#input cast to float
amount = float(input('Amount? '))

withdraw(bank_accounts, account_number, amount)

elif (option == 4):

# get account number and amounts and make purchase
account_number = input('Account number? ')
amounts = input('Amounts (as comma separated list)? ')

# convert given amounts to list
amount_list = amounts.split(',')
amount_list = [float(i) for i in amount_list]

purchase(bank_accounts, account_number, amount_list)

elif (option == 0):

# print message and leave the bank
print('Goodbye!')
break


if __name__ == "__main__":
main()

Solutions

Expert Solution

Here is the solution to your question. I tried my best to solve your doubt, however, if you find it is not as good as expected by you. Please do write your further doubts regarding this question in the comment section, I will try to resolve your doubts regarding the submitted solution as soon as possible.

Please give proper indentation as shown in the screenshot

If you think, the solution provided by me is helpful to you please do an upvote.

def init_bank_accounts(accounts, deposits, withdrawals):
  '''
  Loads the given 3 files, stores the information
  for individual bank accounts in a dictionary,
    and calculates the account balance.

  Accounts file contains information about bank accounts.
  Each row contains an account number, a first name, and a last name, separated by vertical pipe( | ).
  Example:
    1 | Brandon | Krakowsky

  Deposits file contains a list of deposits
  for a given account number.
  Each row contains an account number, and a list of deposit amounts, separated by a comma(, ).
  Example:
    1, 234.5, 6352.89, 1, 97.60

  Withdrawals file contains a list of withdrawals
  for a given account number.
  Each row contains an account number, and a list of withdrawal amounts, separated by a comma(, ).
  Example:
    1, 56.3, 72.1

  Stores all of the account information in a dictionary named 'bank_accounts', where the account number is the key,
    and the value is a nested dictionary.The keys in the nested dictionary are first_name, last_name, and balance,
    with the corresponding values.
  Example: {
    '1': {
      'first_name': 'Brandon',
      'last_name': 'Krakowsky',
      'balance': 6557.59
    }
  }

  This
  function calculates the total balance
  for each account by taking the total deposit amount
  and subtracting the total withdrawal amount.
  '''

  bank_accounts = {}

  #insert code

  f = open(accounts, "r")
  for x in f:
    data=list(x.split(' | ')) # assuming seperated by ' | '
    temp={}
    temp['first_name']=data[1]
    temp['last_name']=data[2]
    temp['balance']=0
    bank_accounts[data[0]]=temp

  f.close()
  f = open(deposits, "r")
  for x in f:
    data=list(map(float,x.split(', '))) # assuming seperated by ', '
    amount=sum(data[1:])
    bank_accounts[str(int(data[0]))]['balance']+=amount

  f.close()

  f = open(withdrawals, "r")
  for x in f:
    data=list(map(float,x.split(', '))) # assuming seperated by ', '
    amount=sum(data[1:])

    bank_accounts[str(int(data[0]))]['balance']-=amount
    round_balance(bank_accounts, str(int(data[0])))

  f.close()



  return bank_accounts

def round_balance(bank_accounts, account_number):
  '''
  Rounds the given account balance.
  '''
  bank_accounts[account_number]['balance']=round(bank_accounts[account_number]['balance'])

  pass

def get_account_info(bank_accounts, account_number):
  '''
  Returns the account information for the given account_number as a dictionary.
  Example: {
    'first_name': 'Brandon',
    'last_name': 'Krakowsky',
    'balance': 6557.59
  }
  If the account doesn 't exist, returns None.
  '''

  if account_number not in bank_accounts:
    return None
  else:
    return bank_accounts[account_number]

  pass

def withdraw(bank_accounts, account_number, amount):
  '''
  Withdraws the given amount from the account with the given account_number.
  Raises a RuntimeError
  if the given amount is greater than the available balance.
  If the account doesn 't exist, prints a friendly message.
  Rounds and prints the new balance.
  '''
  if account_number not in bank_accounts:
    print("This account doesn 't exist")
  else:
    if bank_accounts[account_number]['balance']<amount:
      raise RuntimeError("Given amount is greater than the available balance")
    else:
      bank_accounts[account_number]['balance']-=amount
      round_balance(bank_accounts,account_number)
      print("New Balance is :",bank_accounts[account_number]['balance'])

  pass

def deposit(bank_accounts, account_number, amount):
  '''
  Deposits the given amount into the account with the given account_number.
  If the account doesn 't exist, prints a friendly message.
  Rounds and prints the new balance.
  '''
  if account_number not in bank_accounts:
    print("This account doesn 't exist")
  else:
    bank_accounts[account_number]['balance']+=amount
    round_balance(bank_accounts,account_number)
    print("New Balance is :",bank_accounts[account_number]['balance'])

  pass

def purchase(bank_accounts, account_number, amounts):
  '''
  Makes a purchase with the total of the given amounts from the account with the given account_number.
  Raises a RuntimeError
  if the total purchase, plus the sales tax(6 % ), is greater than the available balance.
  If the account doesn 't exist, prints a friendly message.
  Rounds and prints the new balance.
  '''
  if account_number not in bank_accounts:
    print("This account doesn 't exist")
  else:
    amount=sum(amounts)
    if bank_accounts[account_number]['balance']<(amount+calculate_sales_tax(amount)):
      raise RuntimeError("Given purchase amount is greater than the available balance")
    else:
      bank_accounts[account_number]['balance']-=(amount+calculate_sales_tax(amount))
      round_balance(bank_accounts,account_number)
      print("New Balance is :",bank_accounts[account_number]['balance'])


  pass

def calculate_sales_tax(amount):
  '''
  Calculates and returns a 6% sales tax for the given amount.
  '''
  return amount*0.06;

  pass

def main():
  #load and get all account info
  bank_accounts = init_bank_accounts('accounts.txt', 'deposits.csv', 'withdrawals.csv')

  #for testing
  #print(bank_accounts)

  while True:

    #print welcome and options
    print('\nWelcome to the bank! What would you like to do?')
    print('1: Get account info')
    print('2: Make a deposit')
    print('3: Make a withdrawal')
    print('4: Make a purchase')
    print('0: Leave the bank')

    # get user input
    option_input = input('\n')

    #    try to cast to int
    try:
      option = int(option_input)

    #catch ValueError
    except ValueError:
      print("Invalid option.")

    else :
      #check options
      if (option == 1):

        #get account number and print account info
        account_number = input('Account number? ')
        print(get_account_info(bank_accounts, account_number))

      elif(option == 2):

        # get account number and amount and make deposit
        account_number = input('Account number? ')

        # input cast to float
        amount = float(input('Amount? '))

        deposit(bank_accounts, account_number, amount)

      elif(option == 3):

        # get account number and amount and make withdrawal
        account_number = input('Account number? ')

        #input cast to float
        amount = float(input('Amount? '))

        withdraw(bank_accounts, account_number, amount)

      elif(option == 4):

        # get account number and amounts and make purchase
        account_number = input('Account number? ')
        amounts = input('Amounts (as comma separated list)? ')

        # convert given amounts to list
        amount_list = amounts.split(',')
        amount_list = [float(i) for i in amount_list]

        purchase(bank_accounts, account_number, amount_list)

      elif(option == 0):

        # print message and leave the bank
        print('Goodbye!')
        break

if __name__ == "__main__":
  main()

Related Solutions

This writing assignment will involve implementing and analyzing a behavior modification program on yourself. The behavior...
This writing assignment will involve implementing and analyzing a behavior modification program on yourself. The behavior is ANXIETY OF MEETING NEW PEOPLE. This assignment is to develop your own functional behavior assessment. A minimum of 3 paragraphs per question is required. Modification Plan: In this section, you need to describe your assessment and intervention plan. How will you collect data on the behavior in order to evaluate whether or not it is changing? Describe any forms or graphs you plan...
Create a Python program that: Allows the user to enter a phrase or sentence. The program...
Create a Python program that: Allows the user to enter a phrase or sentence. The program should then take the phrase or sentence entered Separate out the individual words entered Each individual word should then be added to a list After all of the words have been place in a list Sort the contents of the list Display the contents of the sorted list with each individual word displayed on a separate line Display a message to the user indicating...
For Python: In this assignment you are asked to write a Python program to determine the...
For Python: In this assignment you are asked to write a Python program to determine the Academic Standing of a studentbased on their CGPA. The program should do the following: Prompt the user to enter his name. Prompt the user to enter his major. Prompt the user to enter grades for 3 subjects (A, B, C, D, F). Calculate the CGPA of the student. To calculate CGPA use the formula: CGPA = (quality points * credit hours) / credit hours...
Use Visual Python or equivalent, to write a program that allows the user to observe the...
Use Visual Python or equivalent, to write a program that allows the user to observe the following: Damped and forced harmonic oscillators. The program should be user friendly and have default values for the initial velocities, positions, masses, and spring constants as well as damping constants. Values and frequencies for the forced oscillators should also be given. It should allow the user to input values for the velocities, positions, spring constants, and masses. The program should determine automatically the scale...
9) This is in Python Code a program that allows the user to manage its expenses...
9) This is in Python Code a program that allows the user to manage its expenses accepting the following commands: - Add <player_name> -> This command adds a new player to the system. Assume there can’t be repeated names. If a name already exists then an error is shown to the user. - Score <player_name> <score> -> This command adds the score to the player with the name player-name. Each score needs to be added individually - Report -> This...
Python Add a command to this chapter’s case study program that allows the user to view...
Python Add a command to this chapter’s case study program that allows the user to view the contents of a file in the current working directory. When the command is selected, the program should display a list of filenames and a prompt for the name of the file to be viewed. Be sure to include error recovery in the program. If the user enters a filename that does not exist they should be prompted to enter a filename that does...
In Python, write a program that allows the user to enter a number between 1-5 and...
In Python, write a program that allows the user to enter a number between 1-5 and returns the vitamins benefits based on what the user entered. The program should: Continue to run until the user quits and Validate the user’s input (the only acceptable input is 0, 1, 2, 3, 4, or 5), If the user enters zero “0” the program should terminate You can use the following facts: 1- Vitamin A protects eyes from night blindness and age-related decline...
In Python, write a program that allows the user to enter a number between 1-5 and...
In Python, write a program that allows the user to enter a number between 1-5 and returns the vitamins benefits based on what the user entered. The program should: Continue to run until the user quits and Validate the user’s input (the only acceptable input is 0, 1, 2, 3, 4, or 5), If the user enters zero “0” the program should terminate You can use the following facts: 1- Vitamin A protects eyes from night blindness and age-related decline...
USING PYTHON. Thank you in advance Write a program that allows the user to enter a...
USING PYTHON. Thank you in advance Write a program that allows the user to enter a series of string values into a list. When the user enters the string ‘done’, stop prompting for values. Once the user is done entering strings, create a new list containing a palindrome by combining the original list with the content of the original list in a reversed order. Sample interaction: Enter string: My Enter string: name Enter string: is Enter string: Sue Enter string:...
The assignment is to build a program in Python that can take a string as input...
The assignment is to build a program in Python that can take a string as input and produce a “frequency list” of all of the wordsin the string (see the definition of a word below.)  For the purposes of this assignment, the input strings can be assumed not to contain escape characters (\n, \t, …) and to be readable with a single input() statement. When your program ends, it prints the list of words.  In the output, each line contains of a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT