我刚开始学习python,正在编写一个程序,该程序不断接受用户的数字输入并将其添加到列表中。但是,当用户输入X时,它应该打印出已输入的数字及其总数。我已经重写了无数次代码,但是这就是我一直坚持的地方。
list = []
number = int(input("Enter numbers: "))
while number != "x" or "X":
list.append(number)
break
print(list)
print("The length of the list is:",len.list)
print("The sum of the list is:",sum(list))
我似乎缺少了一些东西,因为它只会造成无限循环
在您的原始帖子之后,请考虑以下内容(包括评论)
# 1. Don't use `list` since it is a built-in ctor (list())
lst = []
# 2. Loop forever
while True:
# 3. Ask the user and keep the input as string!
number_str = input("Enter number: ")
# 4. Check if we need to bail!
if number_str in {"x", "X"}:
break
# 5. ... and if not append it to the list
lst.append(int(number_str))
print(lst)
print("The length of the list is:",len(lst))
print("The sum of the list is:",sum(lst))
输出:
$ python3 ~/tmp/so.py
Enter number: 1
Enter number: 2
Enter number: 3
Enter number: X
[1, 2, 3]
另外,如果您希望用户一次输入所有内容,则可以执行以下操作:
numbers_str = input("Enter numbers (space-separated): ")
lst = []
for str_num in numbers_str.split(" "):
if str_num in {'x', 'X'}:
break
lst.append(int(str_num))
print(lst)
print("The length of the list is:",len(lst))
print("The sum of the list is:",sum(lst))
输出:
$ python3 ~/tmp/so2.py
Enter numbers (space-separated): 1 2 3 X 4 5
[1, 2, 3]
The length of the list is: 3
The sum of the list is: 6
请注意,与其他答案一样,您将不得不处理错误的用户输入!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句