提问人:RylieAnya 提问时间:11/8/2023 更新时间:11/8/2023 访问量:45
如何通过我正在构建的程序获得平均值和总值
How to get average and total with the program I am building
问:
我需要用 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 行,在 总计 = sum(数字) TypeError:“int”对象不可迭代
答:
0赞
JNevill
11/8/2023
#1
与其循环 AND 循环,不如单独使用循环,因为我们不知道需要循环多少次。
range
while
while
验证可以使用模式而不是嵌套的 if 语句进行。我已经在下面的代码中解开了其中一个级别。
if/elif/else
结果应收集到某种集合中。我在下面的代码中调用了它
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)
评论
Number
是一个数字。 需要一个可迭代对象,例如列表。sum
Number = int(InputValue)
Number
sum
min
max