gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:55:54 25 4
gpt4 key购买 nike

这里是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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com