我正在完成这项家庭作业,我坚持认为这是一个非常简单的问题。代码的前提是一个小额现金系统,用户可以在其中存款,取款和获得当前余额。 我的问题是提款和存款似乎没有通过我的账户类。这是全局变量问题吗?我稍后会添加时间戳。提前谢谢。
import datetime
import time
class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
def yesno(prompt):
ans = raw_input(prompt)
return (ans[0]=='y' or ans[0]=='Y')
def run():
done = 0
while not done:
user_options()
print
done = not yesno("Do another? ")
print
def user_options():
print ("Here are your options:")
print
print (" (a) Deposit cash")
print (" (b) Withdraw cash")
print (" (c) Print Balance")
print
u = raw_input("Please select a letter option: ").lower()
user_input(u)
def user_input(choice):
account = Account(0.00)
if choice == "a" or choice == "b" or choice == "c":
if choice == "a":
d = input("Enter Deposit Amount: $")
account.deposit(d)
if choice == "b":
w = input ("Enter Withdraw Amount: $")
account.withdraw(w)
if choice == "c":
print ("Balance Amount: $"),
print account.getbalance()
else:
print ("Not a correct option")
run()
#now = datetime.datetime.now()
Python版本:2.7.2
答案 0 :(得分:1)
问题是:
account = Account(0.00)
每次调用user_input
时,您都会创建一个新的空帐户。由于user_input
是从user_options
调用的,它在运行中的while
循环内调用,所以这发生在每次事务之前。
您需要将该行移出循环,例如:
def run():
done = 0
global account # just showing you one way, not recommending this
account = Account(0.00)
while not done:
user_options()
print
done = not yesno("Do another? ")
print
答案 1 :(得分:0)
您不需要全局变量,只需稍微重构代码
def run():
account = Account(0.00)
done = 0
while not done:
user_option = user_options()
user_input(user_option, account)
print
done = not yesno("Do another? ")
print
def user_options():
print ("Here are your options:")
print
print (" (a) Deposit cash")
print (" (b) Withdraw cash")
print (" (c) Print Balance")
print
return raw_input("Please select a letter option: ").lower()
def user_input(choice, account):
if choice == "a" or choice == "b" or choice == "c":
if choice == "a":
d = input("Enter Deposit Amount: $")
account.deposit(d)
if choice == "b":
w = input ("Enter Withdraw Amount: $")
account.withdraw(w)
if choice == "c":
print ("Balance Amount: $"),
print account.getbalance()
else:
print ("Not a correct option")
run()
你仍然可以做更多的事情来使代码更好,这足以使帐户部分工作