Python中的函数和局部变量

2024-06-17 01:49:53 发布

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

我正在为一个类项目编写一个ATM程序,我们不允许使用全局变量。我在程序中只使用了局部变量,但它不起作用

def welcome():
    print("Welcome to the ATM program!\nThis program allows you to deposit, withdraw, or view your balance!")

def menu():
    print("1...Deposit\n2...Withdraw\n3...View Balance")
    userChoice = int(input("Please enter your choice now: "))
    if userChoice == 1:
        def deposit(balance):
            deposit = float(input("Please enter the amount you would like to deposit: "))
            balance = balance + deposit
    elif userChoice == 2:
        def withdraw(balance):
            withdraw = float(input("Please enter the amount you would like to withdraw: "))
            balance = balance + withdraw
    else:
        def balance(balance):
            print("Your balance is", balance)

        deposit()
        withdraw()
        balance()
welcome()
menu()

当我运行它时,在我从菜单中输入一个选项后,它就结束了,没有任何错误消息


Tags: theto程序youinputdefprintenter
1条回答
网友
1楼 · 发布于 2024-06-17 01:49:53

没有理由在这里定义函数-只需在if语句中执行该代码即可:

def menu(balance):
    print("1...Deposit\n2...Withdraw\n3...View Balance")
    userChoice = int(input("Please enter your choice now: "))
    if userChoice == 1:
        deposit = float(input("Please enter the amount you would like to deposit: "))
        balance = balance + deposit
    elif userChoice == 2:
        withdraw = float(input("Please enter the amount you would like to withdraw: "))
        balance = balance + withdraw
    else:
        print("Your balance is", balance)
    return balance

...
balance = 0
balance = menu(balance)

没有发生任何事情的原因是,按照代码现在的方式,您正在定义函数,而不是调用函数。查看缩进-对withdraw()deposit()balance()的调用仅在else块内执行。在没有任何参数的情况下,启动,如果执行它们,将导致错误

相关问题 更多 >