python - 中断而不是停止简单的 While 循环 Python

标签 python while-loop break

这里是Python菜鸟。我试图创建一个包含用户输入的数字的列表,然后在 while 循环中对列表末尾的数字进行一些简单的计算。当输入“done”时,While 循环不会中断。它只是打印“无效输入”。

list = []
while True:
    try:
        n = int(input('Enter a number: '))
        list.append(n)
    except:
        print('Invalid input') 
    if n == 'done':
        break

print(sum.list())
print(len.list())
print(mean.list())

最佳答案

您必须将接收用户输入并检查“完成”与转换为数字并附加到列表分开。在将输入转换为整数之前,您必须检查“完成”。

尝试这样的事情:

list_of_numbers = []

while True:
    user_input = input("Enter a number or 'done' to end: ")

    if user_input == "done":
        break

    try:
        number = int(user_input)

    except ValueError:
        print("invalid number")
        continue

    list_of_numbers.append(number)

print(list_of_numbers)

# further processing of the list here

关于python - 中断而不是停止简单的 While 循环 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55643255/

相关文章:

python - 有界/极限的编辑距离

python - 将 Python 列表导出到 Excel

arrays - 如何从数组中获取所有数据并将其存储在新变量或常量中?

c++ - Code Endless 写入文本文件的第一行

javascript - 如何在 JavaScript 中找到换行符并替换为 <br> 元素?

javascript - 跳出替换全局循环

python - PyDev 使用模块共享 fixture 运行 pytest 单元测试失败

python - 如何使用 numpy 的 pv 函数在没有 pmt 的情况下计算现值?

python:使用不正确的导入语句导入模块=>来自生成的 ImportError 的不详尽信息

java - 我的 for 循环出了什么问题?