我需要用 Python 编写一个程序,利用循环从用户输入中读取一组五个值,并打印以下内容:总计、平均值、最大值、最小值和 20% 的利息。我还需要验证输入值。我正在努力了解我需要做什么来解决这个问题。我将尝试过的内容放在上面,但验证成功后失败了。我究竟做错了什么?如果我能弄清楚如何获得总数,那么我可能可以毫无问题地获得其余部分。这是我到目前为止所拥有的:
Number = 0
InputValue = ""
Total = 0
Average = 0
Interest = 0.2
Maximum = 0
Minimum = 0
for i in range(5):
while True:
InputValue = input("Enter a number: ")
if InputValue == "":
print("ERROR: Number must be supplied.")
else:
if InputValue.isdigit() == False:
print("ERROR: Number must be a number.")
else:
Number = int(InputValue)
if Number < 0 or Number > 100:
print("ERROR: Number must be between 0 and 100.")
else:
break
print("Continue to the next value...")
total = sum(Number)
minimum = min(Number)
maximum = max(Number)
average = total / 5
interest = total + (total * interest)
print("Total: ", total)
print("Average: ", average)
print("Minimum: ", minimum)
print("Maximum: ", maximum)
print("20% Interest of All Numbers Included Plus the Total: ", interest)
这些是我输入数字后收到的结果和错误:
输入数字:50 继续下一个值... 输入数字:40 继续下一个值... 输入数字:30 继续下一个值... 输入数字:20 继续下一个值... 输入数字:10 继续下一个值... 回溯(最近一次调用最后一次): 文件“C:\Users\Name\Desktop\ITS 320\TEST 2.py”,第 49 行,位于 总计 = 总和(数字) 类型错误:“int”对象不可迭代
不要循环遍历
range
和 while
循环,只需单独使用 while
循环,因为我们不知道需要循环多少次。
验证可以使用
if/elif/else
模式而不是嵌套的 if 语句进行。我在下面的代码中解开了其中一个关卡。
结果应收集到
list
或某种集合中。我在下面的代码中将其称为numbers
interest = total + (total * interest)
没有任何意义,因为变量interest
未设置,我假设是Interest
。
Number = 0
InputValue = ""
Total = 0
Average = 0
Interest = 0.2
Maximum = 0
Minimum = 0
numbers=[]
#iterate until we fill `numbers` list with 5 numbers
while True:
InputValue = input("Enter a number: ")
if InputValue == "":
print("ERROR: Number must be supplied.")
elif InputValue.isdigit() == False:
print("ERROR: Number must be a number.")
else:
Number = int(InputValue)
if Number < 0 or Number > 100:
print("ERROR: Number must be between 0 and 100.")
else:
numbers.append(Number)
print(numbers) # just for visibility sake. This line isn't necessary.
if len(numbers) == 5:
break
total = sum(numbers)
minimum = min(numbers)
maximum = max(numbers)
average = total / 5
interest = total + (total * Interest)
print("Total: ", total)
print("Average: ", average)
print("Minimum: ", minimum)
print("Maximum: ", maximum)
print("20% Interest of All Numbers Included Plus the Total: ", interest)