简体   繁体   English

我怎样才能总结一个数字列表?

[英]How can I sum a list of numbers?

My program needs to read a set of integers from the user and store them in a list.我的程序需要从用户那里读取一组整数并将它们存储在一个列表中。 It should read numbers from the user until the user enters 0 to quit.它应该从用户那里读取数字,直到用户输入 0 退出。 Then it needs to add them up and display the sum to the user.然后它需要将它们相加并向用户显示总和。 If the user types anything that is not an integer, it needs to display an error to the user.如果用户键入任何不是整数的内容,则需要向用户显示错误。

I'm having a hard time figuring out how to make a list that the user can infinitely input numbers into.我很难弄清楚如何制作一个用户可以无限输入数字的列表。

From what I have tried to do and looked up, I've only been able to make a defined list and make a program that takes in a specific amount of inputs.从我尝试做和查找的内容来看,我只能制作一个定义的列表并制作一个接受特定数量输入的程序。

This is what I have.这就是我所拥有的。 Obviously, it doesn't work, but it shows what I'm going for.显然,它不起作用,但它显示了我要做什么。

n, ns = 0, 0  # count of numbers, sum of numbers
print("Enter numbers or any other 0 to quit.")

while(1):
     grades = input("enter = ")
     if (int):
          ns += int
          n += 1
     else:
          if (0):
               print(ns)
          break

Use this:用这个:

list_of_nums = []
loop = True
while loop == True:
    try: num = int(input("Enter Integer: "))
    except ValueError: num = "invalid"
    if num == "invalid": print("\nPlease Print A Valid Integer!\n");
    elif num != 0: list_of_nums.append(num)
    else: loop = False
print("\nSum of Inputed Integers: " + str(sum(list_of_nums)) + "\n")

Python 3蟒蛇 3

lists=[]
while(True):
    i=int(input("Enter The Input"))
    if i==0:
        break
    else:
        lists.append(i)
print(lists)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM