如何找到输入的数字列表的总和

How to find the sum of an entered list of numbers

我对 python 还是很陌生,正在做一项学校作业。该程序应该是一个循环,允许用户输入一系列数字,只要输入的数字为 0 或更大,该循环就会继续。输入负数后,程序应创建所有输入数字的总和。非常感谢您的帮助,谢谢!

#This program calculates the sum of multiple numbers

#Initialize accumulator
total = 0

#Calculate the sum of numbers
while keep_going >= 0:
    keep_going = int(input('Enter a number: '))
    total += keep_going
print(total)
#Calculate the sum of numbers
saved_numbers = [] # A list of numbers to fill up. 
while True: # A way to write 'keep doing this until I stop ('break' in this case...)'
    number = int(input('Enter a number: '))
    if number < 0: # If the number is negative
        break # Exits the current while loop for us. 
    else: # Otherwise, save the number.
        saved_numbers.append(number) 

sum = sum(saved_numbers) # Getting the sum of the numbers the user entered!
print(sum)

你可以让它更简单。您不需要 keep_going 变量。如果输入的数字为 0 或大于 0,则使用 total 变量并添加到变量。如果数字小于 0,则退出 while 循环:

#Initialize accumulator
total = 0

#Calculate the sum of numbers
while(True):
    num = int(input('Enter a number: '))
    if num < 0:
        break
    else:
        total = total + num

print(total)

只需跟踪输入的数字,稍后使用 python in-built sum 函数计算总和。

keep_going = int(input('Enter a number: '))
entered_nums = []
while keep_going >= 0:
    entered_nums.append(keep_going)
    keep_going = int(input('Enter a number: '))

print('Entered numbers : ', entered_nums)
print('Entered numbers sum : ', sum(entered_nums))

这也可以用 recursion 而不是 while 来完成。即:

def count_total(total=0):
    keep_going = int(input('Enter a number: '))
    if keep_going >= 0:
        total += keep_going
        count_total(total)
    else:
        print('Total : %d' % total)


count_total()

欢迎来到 Whosebug Christian,欢迎进入编程的伟大世界 =)

关于您的代码的一些评论:

  • keep_going = >-0 没有意义。 > 是一个比较运算符,你必须用它来比较两个表达式,例如var1 > var2,它将 return 一个布尔值。
  • while keep_going == 0: 是一个不错的开始,但不会如您所愿。如果输入的数字大于或等于零,则循环必须继续进行,而不仅仅是 keep_going 等于零。将 == 更改为 >=
  • int(input('Enter a number: ')) 是要走的路,但你为什么要用它两次?附带说明一下,您只是在第二次将输入数字存储在变量中。
  • 最后,您需要在循环中实际使用 total 来存储用户输入。

祝你好运!

PS:虽然 Whosebug 非常适合快速获得解决方案,但我真的建议您真正理解为什么您的代码错误,以及为什么提供的解决方案有效。它将极大地帮助你成为一名优秀的程序员 ;)

您可以试试这个解决方案:

def func():
    i = 0
    while i >= 0:
        i = int(input('Enter a number: '))
        yield (i >= 0) * i

print(sum(func()))

请记住,在 Python 中,True 等于 1False 等于 0