我正在编写一个简单的程序,但我无法摆脱这种循环。我想做的是,如果提款金额大于您的余额,请转到while循环。while循环应获取一个新输入,并检查新输入是否大于余额,是否重复,如果不是,则转到else,这是我打印余额的地方
class Account(object):
balance = 0
accountNumber = 0
def __init__(self, f, l, ssn, b):
self.firstName = f
self.lastName = l
self.socialSecurity = ssn
self.balance = b
self.accountNumber = randint(0, 10000)
def __str__(self):
return self.firstName + " " + self.lastName + \
"'s balance is $" + str(self.balance) + \
". Your account Number is " + str(self.accountNumber)
def deposit(self, amount):
depositAmount = amount
balance = self.balance + depositAmount
print(str(depositAmount) + " has been deposited into account "
"#" + str(
self.accountNumber) + " Your balance is "
"now " + str(balance))
return self.balance
def withdraw(self, amount):
withdrawAmount = amount
balance = self.balance - withdrawAmount
if float(withdrawAmount) > float(balance):
while float(withdrawAmount) > float(balance):
print("Insufficient Funds, Enter new amount")
withdrawAmount = raw_input(">")
else:
print(str(withdrawAmount) + " has been taken out of account "
"#" + str(
self.accountNumber) + " Your balance is "
"now " + str(balance))
testOne = Account("John", "Smith", "1111", 1000)
print(testOne)
print(testOne.accountNumber)
testOne.deposit(200)
testOne.withdraw(5000)
我的问题是,无论我说什么,输入新金额,我都会陷入while循环中
柯克是对的。
raw_input()
产生字符串,而不是数值。我怀疑这balance
也是使用创建的raw_input()
,是吗?如果是这样,则您将字符串与字符串进行比较,而您认为自己是数字。这就是为什么您陷入此循环。确保您具有预期类型的比较变量。
试试这个:
if float(withdrawAmount) > float(balance):
while float(withdrawAmount) > float(balance):
print("Insufficient Funds, Enter new amount")
withdrawAmount = raw_input(">")
else:
print
如果这行得通,我的假设可能是正确的。
但是我建议您在此片段之前检查代码,以确保balance
实际上是int
or float
,并且在输入时也将其设置withdrawAmount
为float
(or int
)类型(如Kirk所建议);这样,您将可以比较数字,并且一切正常。
编辑:
好的,我在您的代码中看到了一个问题。在比较它们之前,实际上是从余额中减去withdrawAmount 。试试这个:
def withdraw(self, amount):
withdrawAmount = amount
balance = self.balance
while withdrawAmount > balance:
print("Insufficient Funds, Enter new amount")
withdrawAmount = int(raw_input(">"))
balance = balance - withdrawAmount
print(...)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句