pythonif-statementlogic-error

How to append and subtract values from a global or local var permanently and update its values without oop


I am trying to create a simple atm ui from if-else without using oop, I'm having a hard time figuring out how can I permanently add and subtract a value from my variable "bal" and show updated results, when I run it it does add and subtract when I "Withdraw" and "Deposit" but when i choose "Balance" it still gives me the initial value.

bal = 737000
if pin == pwd:
    print("""
                1) Balance
                2) Withdraw
                3) Deposit
                4) Cancel Transaction       
        
        
        
        
        """)
    try:
        opt = int(input("Please choose your transaction "))
    except:
        print("Invalid input, input must be an integer.")

    if opt == 1:
        print(f"Your current balance is ₱{bal}.00")

    if opt == 2:
        withdraw = int(input("Please enter amount: "))
        balance = bal - withdraw
        print(f"₱{bal}.00 is withdrawn from your account...")
        print(f"Your updated balance is ₱{balance}.00")

    if opt == 3:
        deposit = int(input("How much money would you like to deposit?: "))
        balance = bal + deposit
        print(f"₱{deposit}.00 is deposited unto your account...")
        print(f"Your updated balance is ₱{balance}.00")

    if opt == 4:
        break
else:
    print("Please enter a valid pin and try again.")

Is a workaround still possible, I need to add and subtract values from my "bal" variable permanently and show updated results.


Solution

  • You use a second, redundant variable (balance) and don't update your main variable (bal) after deposit/withdraw operations. Try this:

       ...
       if opt == 2:
          withdraw = int(input("Please enter amount: "))
          bal = bal - withdraw
          print(f"₱{withdraw}.00 is withdrawn from your account...")
          print(f"Your updated balance is ₱{bal}.00")
       if opt == 3:
          deposit = int(input("How much money would you like to deposit?: "))
          bal = bal + deposit
          print(f"₱{deposit}.00 is deposited unto your account...")
          print(f"Your updated balance is ₱{bal}.00")
       ...