我用python提交了一个简单的自动取款机程序的代码。我得到了充分的信任,但被告知不要使用全局变量,因为它们被认为是糟糕的编程。我已经试着重写这个函数一百万次了,但是当我重写的时候,我的余额没有更新。有人能告诉我我哪里做错了吗?我自己也搞不清楚这件事,这让我很困扰!
我的原创:
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())发布于 2014-12-16 08:30:14
您从不使用从withdraw返回的数量来更新“全局”balance ...
试试这个:
# 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确保您了解程序中不同参数的作用域。
发布于 2014-12-16 08:39:10
在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())https://stackoverflow.com/questions/27495627
复制相似问题