如何制作一个可以输入和总结+的chatbot,然后在终止和打印结果之前计算平均值?

问题描述:

我对编程非常陌生,刚开始通过Python课程工作。我一直在浏览课程资料和在线,看看是否有我错过的东西,但无法找到任何东西。如何制作一个可以输入和总结+的chatbot,然后在终止和打印结果之前计算平均值?

我的任务是制作一个聊天机器人,该机器人需要输入和总结输入,并计算平均值。它应该采取所有的输入,直到用户写入“完成”,然后终止并打印结果。

当我尝试运行此:

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 =”赋值。这将避免该ValueError。还要添加一个break语句,以便在有人键入“完成”时跳出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