Search code examples
pythonglobal-variables

How to fix: Global variable is being updated in all functions except one


Creating a small, simple ATM-like software. I've made functions for the various actions available. However in the output my global variable 'balance' isn't being updated. Below is the relevant snippet of code.

After some testing I realized that the value is understood to be changed within the function as when I deposit a value, I'm able to withdraw greater than the initial balance. So that means the variable is being updated for the functions at least.

global menu
balance = float(input("Please enter your current balance: "))
menu = "Current balance is: {}\n Press 1 to withdraw\n Press 2 to deposit\n Press 3 to exit".format(balance)
def display():
    global choice
    global balance
    print(menu)
    choice = input("Please select a number: ")
    return balance
def deposit():
    global balance
    global choice
    amount_dep = float(input("Please enter the amount you'd like to deposit: "))
    balance += amount_dep
    return "Your current balance is{}".format(balance)
def withdraw():
    global balance
    global choice
    amount_with = float(input("Please enter the amount you'd like to withdraw: "))
    if amount_with > balance:
        print("Sorry, but your balance is less than the amount you'd like to withdraw.")
    else:
        balance -= amount_with
        return "Your current balance is{}".format(balance)
while finished == False:
    display()
    global choice
    if choice == '1':
        withdraw()
    elif choice == '2':
        deposit()
    elif choice == '3':
        finished = True
        print("Thank you for using our service.")
    else:
        print("You entered an invalid number, please retry")

So all the output is regular, except the value of balance.


Solution

  • When you define the variable menu at the top of the code, you define it with the initial balance. When you print the menu after a deposit or withdrawl, the display routine is still printing the menu defined with the initial balance.

    You may be working on an assignment where you are supposed to use global variables, but this doesn't seem like a great use case. Your withdrawl function returns a string stating your current balance, but you don't use it. You could as easily call the withdrawl function with balance = withdraw(balance) and treat the balance as an argument and a return. Anyway, keep working it and keep learning!