在函数之间传递局部变量

时间:2019-05-26 16:31:33

标签: python function

我的老师分配了一个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()

0 个答案:

没有答案