输入数字 return 值输入

Input numbers return values inputted

我有一个问题要解决,是这样的:

Write a program that asks the user to input numbers and to end the program type -1, after return the sum of the numbers inputted.

这是我所做的:

num=0
i = 0

while num != -1:                          #loop to get the numbers
    i = i + num                           #this will make the sum of the inputted numbers
    num = int(input("Input a number: "))  #save the input given into "num"
    print(num)                            #this shows the number that has been inputted by the user
    print("Input -1 to terminate")

print(i)                                  #this shows the total sum of all the inputted numbers

它按要求执行,但现在我想在最后一个 print() 中给出用户输入的数字,而不是所有数字的总和。我该怎么做?

您可以将用户的号码存储在 Python 列表中:https://www.w3schools.com/python/python_lists.asp

您可以通过执行类似 numbers = [] 的操作来创建一个新列表,这将创建一个空的 Python 列表。然后,在 while 循环中的每次迭代中,您可以通过执行 numbers.append(i) 将数字添加到此列表,这会将新数字添加到此列表的末尾。准备好显示所有数字后,可以使用 for 循环显示列表中包含的所有数字:for num in numbers: print(num)