如何制作一个接受输入并总结+在终止和打印结果之前计算平均值的聊天机器人?
How to make a chatbot that takes input and summarizes + calculates the average before terminating and printing the results?
我是编程新手,刚开始学习 Python 课程。我一直在浏览课程 material 和在线查看是否有我遗漏的东西,但找不到任何东西。
我的任务是制作一个聊天机器人,它接受输入并汇总输入,同时计算平均值。它应该接受所有输入,直到用户写入 "Done",然后终止并打印结果。
当我尝试 运行 时:
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 或类似的东西?如果还有其他问题需要修复,请告诉我!
似乎问题是当用户键入 "Done" 然后行
int(numbers)
正试图将 "Done" 转换为一个整数,但这是行不通的。一个解决方案是移动您的条件
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
更高,就在 "inp = " 作业下方。这将避免 ValueError。还要添加一个 break 语句,以便在有人键入 "Done"
时立即跳出 while 循环
最后我认为你在添加到 total 变量时缺少一个 = 符号。
我想这就是你想要的:
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
我是编程新手,刚开始学习 Python 课程。我一直在浏览课程 material 和在线查看是否有我遗漏的东西,但找不到任何东西。
我的任务是制作一个聊天机器人,它接受输入并汇总输入,同时计算平均值。它应该接受所有输入,直到用户写入 "Done",然后终止并打印结果。
当我尝试 运行 时:
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 或类似的东西?如果还有其他问题需要修复,请告诉我!
似乎问题是当用户键入 "Done" 然后行
int(numbers)
正试图将 "Done" 转换为一个整数,但这是行不通的。一个解决方案是移动您的条件
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
更高,就在 "inp = " 作业下方。这将避免 ValueError。还要添加一个 break 语句,以便在有人键入 "Done"
时立即跳出 while 循环最后我认为你在添加到 total 变量时缺少一个 = 符号。
我想这就是你想要的:
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