Python未正确求和列表

2024-06-28 11:37:08 发布

您现在位置:Python中文网/ 问答频道 /正文

Python没有对列表中的所有项求和。我做错了什么?你知道吗

我正在尝试制作一个程序来计算输入数字的平均值,看起来len()工作正常,但sum()只是对一些数字求和。你知道吗

numbers = []
More = True

while More:
    xInp = input('Number: ')
    yInp = input('Again?(y/n) ')
    if yInp == 'y':
        numbers.append(int(xInp))
    elif yInp == 'n':
        break

print(sum(numbers))
print(len(numbers) + 1)
print(sum(numbers) / int(len(numbers) + 1))

Tags: 程序true列表inputlenmore数字int
3条回答

您错过了多个值中的最后一个值。你知道吗

numbers = []
More = True

while More:
    xInp = input('Number: ')
    yInp = input('Again?(y/n) ')
    if yInp == 'y':
        numbers.append(int(xInp))
    elif yInp == 'n':
        if xInp:
            numbers.append(int(xInp))
        break

print(sum(numbers))
print(len(numbers))
print(sum(numbers) / int(len(numbers)))

如果用户在下一次提示时选择y,则代码只会将最近输入的数字添加到数组中。一旦输入n,最后输入的数字就不会追加到列表中。你知道吗

您需要在输入数字后立即添加数字,然后检查用户是否要添加更多。你知道吗

numbers = []

while True: # No need for a variable here
    xInp = input("Number: ")
    numbers.append(int(xInp))
    yInp = input("Again? (y/n): ")
    if yInp == "y":
       pass
    elif yInp == "n":
        break

print(sum(numbers))

按照惯例,变量以小写字母开头。大写的第一个字母用于类定义(不是实例)。我最初把More改成了more,但正如在评论中提到的,甚至没有必要,所以我用while True代替了它。你知道吗

问题在于顺序,您退出程序时没有考虑最后输入的值。稍微改变一下顺序将有助于你解决这个问题。此外,请注意撇号和doble撇号,我也在答案中编辑了它,因为它将返回SyntaxError否则:

numbers = []

while True:
    xInp = input('Number: ')
    numbers.append(int(xInp))
    yInp = input('Again?(y/n) ')
    if yInp == 'y':
        pass
    elif yInp == 'n':
        break

print(sum(numbers))
print(len(numbers))
print(sum(numbers) / int(len(numbers)))

相关问题 更多 >