繁体   English   中英

如何修复:全局变量正在所有函数中更新,除了一个

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

创建一个小型、简单的类似 ATM 的软件。 我已经为各种可用的操作提供了功能。 但是在 output 中,我的全局变量“余额”没有更新。 下面是相关的代码片段。

经过一些测试,我意识到该值被理解为在 function 内发生变化,因为当我存入一个值时,我能够提取的金额大于初始余额。 所以这意味着至少要为函数更新变量。

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")

所以所有的output都是正则的,除了余额的值。

当您在代码顶部定义变量菜单时,您使用初始余额定义它。 当您在存款或取款后打印菜单时,显示例程仍在打印使用初始余额定义的菜单。

您可能正在处理应该使用全局变量的赋值,但这似乎不是一个很好的用例。 您的取款 function 返回一个字符串,说明您当前的余额,但您不使用它。 你可以很容易地用balance = withdraw(balance)调用取款 function 并将余额视为参数和返回。 不管怎样,继续努力,继续学习!

暂无
暂无

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

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