Search code examples
pythonvariableserror-handlingprocedure

Procedure issues


So I created a procedure which would ask the user the amount of money they want to with draw from their checking account. And if do the procedure the checking should subtracted by the amount withdrawed. But when I used global it did not change the value of the variable even after the procedure.I already have established the all the variables

my code is here:

checking = 10000
savings = 10000
user_ammount_w = 0
user_currency_w = ""
def withdraw_saving (amount, country):
    global checking
    if country == "HKD":
        if checking >= amount:
            checking = checking - amount
            print("The amount of money left in your checking is", checking)
        else:
            print("Your request of", "$"+ str(amount), country, "is greater than the amount in your 
            checking account this withdraw will not work")

user_choice = input("Welcome to the ATM. Type 1 for withdrawing")
    if user_choice == "1":
        user_currency_w= input("Which currency would you like to withdraw from. For testing purposes 
        its only HKD")
        user_amount_w= int(input("How much money do you want to withdraw"))
        withdraw_saving (user_ammount_w, user_currency_w)

Solution

  • When you call your function again recursivly you are allwyas passing the amount to be subtracted as 0 as you are passing in user_ammount_w which you set globally as 0. instead i suspect you want to pass in user_amount_w which is the variable name which you have used to capture the user input.

    checking = 10000
    savings = 10000
    user_ammount_w = 0   #<----this is the value you passing to your function
    user_currency_w = ""
    def withdraw_saving (amount, country):
        global checking
        if country == "HKD":
            if checking >= amount:
                checking = checking - amount
                print("The amount of money left in your checking is", checking)
            else:
                print("Your request of", "$"+ str(amount), country, "is greater than the amount in your checking account this withdraw will not work")
    
        user_choice = input("Welcome to the ATM. Type 1 for withdrawing")
        if user_choice == "1":
            user_currency_w= input("Which currency would you like to withdraw from. For testing purposes its only HKD")
            user_amount_w= int(input("How much money do you want to withdraw")) #<--you never pass this value.
            withdraw_saving (user_ammount_w, user_currency_w)
    
    withdraw_saving(20, 'HKD')
    

    However using globals is not a good idea and there is probably a better way to design this.