简体   繁体   English

如何 append 并永久地从全局或局部变量中减去值并在没有 oop 的情况下更新其值

[英]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.我试图在不使用 oop 的情况下从 if-else 创建一个简单的 atm ui,我很难弄清楚如何在运行它时永久地从变量“bal”中添加和减去一个值并显示更新的结果当我“取款”和“存款”时它会加减,但当我选择“余额”时它仍然给我初始值。

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.解决方法是否仍然可行,我需要永久地从我的“bal”变量中添加和减去值并显示更新的结果。

You use a second, redundant variable ( balance ) and don't update your main variable ( bal ) after deposit/withdraw operations.您使用第二个冗余变量 ( balance ),并且在存款/取款操作后不更新您的主要变量 ( bal )。 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")
   ...

your variable is global if you re run the code than it will reassign the value of bal如果您重新运行代码,您的变量是全局变量,它将重新分配 bal 的值

bal = 737000
if pin == pwd:

it is reassigning the variable that is why you variable still giving you previous value它正在重新分配变量,这就是为什么你的变量仍然给你以前的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM