以下是我到目前为止的代码以及我得到的错误。我试过玩,但显然我不明白循环应该如何工作
我试图循环,以便输入错误的输入,即字母和1000英镑以下的错误并重新输入问题。我有大部分工作,但它循环到初始问题而不是字母输入的错误问题,但给出错误信息然后继续使用数字但低于1000英镑。
print ("Welcome to Trustees Investment Bank Compoud Interest Calculator") #Title
print ("Interest is calculated at 3.15% per annum")
while True:
try:
deposit2 = float(input("\nEnter initial deposit above £1000? ")) # Initial deposit amount
rate = 0.0315 # interest rate
if deposit2<1000:
deposit2 = float(input("\nEnter initial deposit above £1000? ")) #loop
except ValueError:
continue
else:
break
for year in range(1,9):
amount = deposit2 * (1.0 + rate) ** year
print ("%4d%21.2f" % (year, amount))
这是我的输出
Welcome to Trustees Investment Bank Compound Interest Calculator
Interest is calculated at 3.15% per annum
Enter initial deposit above £1000? jj
Enter initial deposit above £1000? hgh
Enter initial deposit above £1000? 500
Not valid amount,
please enter deposit above £1000 500
1 515.75
2 532.00
3 548.75
4 566.04
5 583.87
6 602.26
7 621.23
8 640.80
答案 0 :(得分:0)
您处于暂停状态,因此您不需要两次请求用户输入。如果不满足条件,则会发生另一次迭代,无论如何都会要求您输入另一个输入。此外,您的else
位置错误。
print ("Welcome to Trustees Investment Bank Compoud Interest Calculator")
print ("Interest is calculated at 3.15% per annum")
while True:
try:
deposit2 = float(input("\nEnter initial deposit above £1000? "))
rate = 0.0315
if deposit2<1000:
print ("Not a valid amount, please try again.")
else:
break
except ValueError:
print ("You have not entered a number. Please enter a valid number")
for year in range(1,9):
amount = deposit2 * (1.0 + rate) ** year
print ("%4d%21.2f" % (year, amount))
这有输出:
Welcome to Trustees Investment Bank Compoud Interest Calculator
Interest is calculated at 3.15% per annum
Enter initial deposit above £1000? 50
Not a valid amount, please try again.
Enter initial deposit above £1000? abcdefg
You have not entered a number. Please enter a valid number
Enter initial deposit above £1000? 1500
1 1547.25
2 1595.99
3 1646.26
4 1698.12
5 1751.61
6 1806.79
7 1863.70
8 1922.41