如何制作一个接收输入和汇总的聊天机器人+在终止和打印结果之前计算平均值?

时间:2017-09-04 20:27:10

标签: python python-3.x cygwin

我是编程新手,刚开始学习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或者其他类似的东西?如果还有其他需要修复的东西,请告诉我们!

1 个答案:

答案 0 :(得分:0)

似乎问题在于当用户键入&#34;完成&#34;那条线 int(numbers)正在尝试转换&#34;完成&#34;成为一个刚刚胜利的整数。解决方法是移动条件

if inp == "Done": print("the sum is {0} and the average is {1}.". format(total, average))

更高,正好低于&#34; inp =&#34;分配。这将避免ValueError。还要添加一个break语句,这样一旦有人输入&#34; Done&#34;

,它就会在while循环中突破

最后,我认为你在添加到总变量时缺少一个=符号。

我认为这就是你想要的:

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