我正在编写一个简单的程序,我无法摆脱这个循环。我想要做的是如果提款金额大于您的余额,请转到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循环答案 0 :(得分:4)
raw_input()
返回一个字符串。您需要将其转换为float
或int
,例如:
withdrawAmount = float(raw_input(">"))
答案 1 :(得分:3)
Kirk是对的。
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
或float
,并将withdrawAmount
设置为float
输入时输入(或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(...)
答案 2 :(得分:0)
试试这个:
if withdrawAmount > balance:
while withdrawAmount > balance:
print "Insufficient Funds, Enter new amount"
withdrawAmount = int(raw_input())
这给了我(余额= 50):
...
Try again
60
Try again
30
>>>
您不需要else语句,因为代码将在退出while循环后退出该块。
答案 3 :(得分:0)
这是一种方法:
balance = 100
withdrawAmount = float(raw_input(">"))
while withdrawAmount > balance:
withdrawAmount = float(raw_input("Insufficient Funds, Enter new amount: "))
print "Thank You"