How to make a chatbot that takes input and summarizes + calculates the average before terminating and printing the results?
我是编程新手,刚开始学习Python课程。 我一直在查看课程资料和在线,看看是否有我错过但却找不到任何东西。
我的任务是制作一个聊天机器人,它接受输入并总结输入,但也计算平均值。 它应该采取所有输入,直到用户写"完成",然后终止并打印结果。
当我尝试运行时:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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)) |
我收到此错误:
1 2 3 4 | 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或者沿着那些行转换的东西? 如果还有其他需要修复的东西,请告诉我!
似乎问题是,当用户键入"完成"然后该行
print("the sum is {0} and the average is {1}.". format(total, average))
更高,在"inp ="赋值之下。 这将避免ValueError。 还要添加一个break语句,以便在有人输入"Done"时它会在while循环中突破
最后,我认为在添加到total变量时你缺少一个=符号。
我想这就是你想要的:
1 2 3 4 5 6 7 8 9 | 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 |