python - 如何使用数字 0 作为停止/中断?
问题描述
该代码需要要求用户选择输入任何数字以及他/她想要的任意数量的数字并将它们放入列表中。(这不是我要求读者关注的内容,只是对代码如何工作的介绍!)
当用户输入数字 0 时,程序需要打印列表的总和、平均值、最小值和最大值,不包括零本身。
如果可能,我不想使用任何 Python 导入库。
try:
user_list = []
print("PRESS 0 to see: \n\t 1. Sum \n\t 2. Average \n\t 3. Minimum \n\t 4. Maximum")
while True:
print("Type number by choice and hit Enter: ")
user_list.append(int(input()))
except:
print(user_list)
我尝试的是if
在 except 语句之后执行一个语句,它仍然让我有机会输入任意数量的数字,但是当输入一个字母时它停止了。
解决方案
user_list = []
print("PRESS 0 to see: \n\t 1. Sum \n\t 2. Average \n\t 3. Minimum \n\t 4. Maximum")
while True:
value = int(input('Type number by choice and hit Enter: '))
if value != 0:
user_list.append(value)
else: break
sum_of = sum(user_list)
max_of = max(user_list)
min_of = min(user_list)
avg_of = sum_of / len(user_list)
print(sum_of)
print(max_of)
print(min_of)
print(avg_of)
推荐阅读
- python - chrome_path“模块”对象不可调用
- python - pandas 和 xlsxwriter 中不同索引的问题
- javascript - 我的表单验证错误消息消失了
- java - 如何阻止我的配置覆盖新值?
- python - 如何使 sklearn 完成的 confsuion 矩阵图更大,以一种正常方式包装所有数字而不像我的结果?
- python - ImportError:无法从 Django 中的“textutils”导入名称“views”
- laravel - 如何使用 i18n 模块从 Nuxtjs 更改 Laravel 语言环境?
- javascript - 需要帮助缩短在数组中创建大量元素的函数
- asp.net - 我如何使用两种方法执行 WCF 服务:一种等待并将数据插入数据库,另一种轮询数据库?
- javascript - Videojs requestPictureInPicture() 在滚动到顶部和底部时仅工作一次