我是编程的新手,刚刚开始在Python课程中工作。我一直在浏览课程材料和网上,看看是否有我错过的东西,但找不到任何东西。
我的作业是制作一个聊天机器人,该聊天机器人获取输入并汇总输入,但也计算了平均值。它应该获取所有输入,直到用户写入"完成",然后终止并打印结果。
当我尝试运行此操作时:
total = 0
amount = 0
average = 0
inp = input("Enter your number and press enter for each number. When you are finished write, Done:")
while inp:
inp = input("Enter your numbers and press enter for each number. When you are finished write, Done:")
amount += 1
numbers = inp
total + int(numbers)
average = total / amount
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
我得到此错误:
Traceback (most recent call last):
File "ex.py", line 46, in <module>
total + int(numbers)
ValueError: invalid literal for int() with base 10: 'Done'
通过在论坛上搜索我需要将STR转换为INT或类似线的其他内容?如果还有其他需要修复的东西,请让我知道!
似乎问题是当用户类型"完成"时,该行 int(numbers)
试图将"完成"转换为无法正常工作的整数。解决方案是移动您的条件
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
更高的向上,就在" INP ="分配下方。这将避免这种价值。还要添加一个休息声明,因此它会在某人"完成"
时立即循环时断开。最后,我认为您添加到Total变量时缺少AN =符号。
我认为这就是您想要的:
while inp:
inp = input("Enter your numbers and press enter for each number. When you are finished write, Done:")
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
break
amount += 1
numbers = inp
total += int(numbers)
average = total / amount