首页 > 解决方案 > 如何使用数字 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 语句之后执行一个语句,它仍然让我有机会输入任意数量的数字,但是当输入一个字母时它停止了。

标签: pythonlistinputrangeuser-input

解决方案



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)

推荐阅读