在函数之间传递局部变量

2024-05-08 22:04:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我的老师分配了一个ATM银行程序,我们必须使用一些函数来创建,我们不允许使用全局变量来创建。唯一的问题是我不知道如何传递变量,这样我就可以有一个更新的平衡

当我运行这个程序时,它运行得很好,只是当它打印余额时,它会打印刚刚存入或取出的任何东西

balance = 0.0
# welcome the user to the program
def welcome():
    print("Welcome to the ATM program!\nThis program allows you to deposit, withdraw, or view your balance!")
def goodbye():
    print("Thank-you for using the ATM!")
def main():
    # print options menu
    def menu():
        userChoice = 0
        while userChoice != 4:
            print("1...Deposit\n2...Withdraw\n3...View Balance\n4...Quit")
            userChoice = int(input("Please enter your choice now: "))
            # deposit function

            def deposit(balance):
                print("\n1...Deposit\n")
                deposit = float(input("Please enter the amount you would like to deposit: "))
                # update balance

                balance = balance + deposit
                print("Your balance is now $"+str(balance)+".")
                return balance
            # withdraw function
            def withdraw(balance):
                print("\n2...Withdraw\n")
                withdraw = float(input("Please enter the amount you would like to withdraw: "))
                # update balance
                balance = balance - withdraw
                print("Your balance is now $"+str(balance)+".")
                return balance, withdraw
            def viewBalance(balance):
                print("\n3...View Balance\n")
                print("Your balance is", balance)

            if userChoice == 1:
                print(deposit(balance))
            elif userChoice == 2:
                withdraw(balance = 0.0)
            elif userChoice == 3:
                viewBalance(balance)
            else:
                return


    menu()

welcome()
main()
goodbye()

Tags: thetoyouinputdefprogrammenuprint