我在python中为一个简单的ATM程序提交了这段代码。我得到了充分的信任,但被告知不要使用全局变量,因为它们被认为是糟糕的编程。我已尝试重写此功能一百万次,但当我做我的余额不更新。有人能告诉我我做错了什么吗?让我感到困扰的是我自己无法理解!
我原来的:
name=input("Name on your bank account? ")
balance=float(input("Your current balance? "))
def printMenu():
print(name,"Welcome to the Lots of Money Bank")
print("Enter 'b'(balance), 'd'(deposit), 'w'(withdraw), or'q'(quit)")
def getTransaction():
transaction=str(input("What would you like to do? "))
return transaction
def withdraw(bal,amt):
global balance
balance=bal-amt
if balance<0:
balance=balance-10
def formatCurrency(amt):
return "$%.2f" %amt
###MAIN PROGRAM###
printMenu()
command=str(getTransaction())
while command!="q":
if (command=="b"):
print(name,"Your current balance is",formatCurrency(balance))
printMenu()
command=str(getTransaction())
elif (command=="d"):
amount=float(input("Amount to deposit? "))
balance=balance+amount
printMenu()
command=str(getTransaction())
elif (command=="w"):
amount=float(input("Amount to withdraw? "))
withdraw(balance,amount)
printMenu()
command=str(getTransaction())
else:
print("Incorrect command. Please try again.")
printMenu()
command=str(getTransaction())
print(name,"Goodbye! See you again soon")
我编辑的退出功能:
def withdraw(bal,amt):
bal=balance
amt=amount
if(bal<0):
bal=bal-10
else:
bal=bal-amt
return bal
and my edited elif
elif (command=="w"):
amount=float(input("Amount to withdraw? "))
withdraw(balance,amount)
printMenu()
command=str(getTransaction())
答案 0 :(得分:1)
你永远不会更新&#34;全球&#34; balance
使用withdraw
...
试试这个:
# and my edited elif
elif (command=="w"):
amount=float(input("Amount to withdraw? "))
# update balance!
balance = withdraw(balance,amount)
printMenu()
command=str(getTransaction())
此外,
def withdraw(bal,amt):
# 'balance' is bound to global balance - we don't want to use that
# this is why we have 'bal' (passed through parameters)
# bal = balance # no need, bal=balance when function is called
# amt=amount # same as balance
if(bal<0):
bal=bal-10
else:
bal=bal-amt
return bal
确保您了解程序中不同参数的范围。
答案 1 :(得分:1)
在withdraw()
函数中,您不应该引用全局变量balance
和amount
。调用函数时,只需要更新balance
,所以我们有:
def withdraw(bal,amt):
if(bal<0):
bal=bal-10
else:
bal=bal-amt
return bal
和
elif (command=="w"):
amount=float(input("Amount to withdraw? "))
balance = withdraw(balance,amount)
printMenu()
command=str(getTransaction())