Welcome to the Bank of CS

Where we work hard not to lose any of your money!

(At least...not on purpose.)

All money stored as integers (Ex: 123 cents)
All input/output shown as floats (Ex: "$1.23")

Starter Code

Download: jmu_bank.py

Functions defined so far:

  • money()
  • open_account()
  • deposit()
  • withdraw()

Exercise 1

Fix the bug in money()

  • This function is used to format money for output
  • Ex: money(1234500) should return "$12,345.00"
  • Hint #1: Assign the variables dollars and cents
  • Hint #2: Format with :,d and :02d (in an f-string)

Global Variables

import random

accounts = []  # account numbers
balances = []  # money, in cents

numbers = list(range(10000, 100000))
random.shuffle(numbers)

  • range is a built-in sequence type
  • numbers is a list of all 5-digit positive integers
  • Can you guess what random.shuffle() does?

Using the Bank

>>> open_account()
  Opening new account
  Opened account #81017
81017

>>> deposit(81017, 123.4)
  Depositing $123.40 into account #81017
  New balance is $123.40
123.4

>>> withdraw(81017, 23.4)
  Withdrawing $23.40 from account #81017
  New balance is $100.00
100.0

Exercise 2

Define a test_bank() function:

  • Open an account
  • Deposit into account
  • Withdraw from account

Add these lines at the very end:

if __name__ == "__main__":
    test_bank()

Exercise 3

Run with Thonny's debugger:

  • Set a breakpoint on the line that calls test_bank()
  • Step through the entire program, one line at a time
  • Pay attention to variables when functions are called

If you haven't already, enable View > Variables (for globals)

Local Variables

  • When a function is called, a new "frame" is created
  • New variables are created/visible within that frame
  • When a function returns, the variables are deleted
def deposit(acct, amount):
    amount = int(round(amount * 100))
    index = accounts.index(acct)
    balances[index] += amount
    return balances[index] / 100

  • Parameters: acct and amount
  • Local variable: index

Modifying Global list

Global variables in jmu_bank.py

  • numbers (list): available account numbers
  • accounts (list): numbers of open accounts
  • balances (list): balances of open accounts
def open_account():
    acct = numbers.pop(0)
    accounts.append(acct)
    balances.append(0)
    return acct

Exercise 4

Write a close_account(acct) function

Ex: Account 12345 has a balance of $6.78

  • At the start, print "Closing account #12345"
  • Get the index for the account (and balance)
  • Pop the index from accounts and balances
  • Print "Closed account #12345 with $6.78"
  • Return the account's balance (as a float)

Hint: Look at the use of index in deposit()