Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用户在列表中输入的总数_Python - Fatal编程技术网

Python 用户在列表中输入的总数

Python 用户在列表中输入的总数,python,Python,我必须编写一个程序,计算用户输入的数字总和,直到用户键入“完成”并显示:用户输入的数字(元素)数量、这些数字的总和和平均值。到目前为止,我设法计算了数字计数,但我的程序没有显示输入的数字之和。相反,它显示最后输入的数字。有人知道我做错了什么吗?怎么做 count = 0 while True: n=input('enter a number: ') if n== 'done': break count=count + 1 if int(n) &g

我必须编写一个程序,计算用户输入的数字总和,直到用户键入“完成”并显示:用户输入的数字(元素)数量、这些数字的总和和平均值。到目前为止,我设法计算了数字计数,但我的程序没有显示输入的数字之和。相反,它显示最后输入的数字。有人知道我做错了什么吗?怎么做

count = 0

while True:
    n=input('enter a number: ')
    if n== 'done':
        break
    count=count + 1
    if int(n) >= 0:
        s=0 + int(n)






print(count)
print(s)

这是因为在进入循环之前没有初始化总和。 在循环之前添加s=0,就像count=0一样 更改s=0+int(n)=>s+=int(n)


这应该有效

当您用输入的每个新数字重置
s
时,您没有累计您的总和。 只需将您的新号码添加到
s

if int(n) >= 0:
    s += int(n)
s
应与循环前的
计数一起初始化。

最后一行:

 s=0 + int(n)
应该是:

 s=s + int(n)
您应该在
之前初始化
s
,而
循环:

s = 0

这将适用于在开头添加s=0,然后将s=0+int(n)更改为s+=int(n)

解决方案

Sum = 0
Count = 0
Input = input("enter a number: ")
while Input != "Done":
    Sum = Sum + int(Input)
    Count = Count + 1
    Input = input("enter a number: ")

print(Sum)
print(Count)

问题是这一行
s=0+int(n)
。这意味着它将在每个循环中将
s
重置为
n
。您想将其替换为
s=s+int(n)
s+=int(n)

我还做了一些更改,以避免出现其他错误

这意味着
DONE
也将注册为
DONE

if n.lower() == 'done':
    break
要在输入非整数时停止抛出错误,需要使用一些错误处理

try:
    n = int(n)

except ValueError as e:
    continue
最后一件

count, s = 0, 0

while True:
    n = input('Enter a number: ')
    
    if n.lower() == 'done':
        break
    
    count += 1

    try:
        n = int(n)

    except ValueError:
        continue

    if n >= 0:
        s += n

print(count, s)
s=0+int(n)
替换为
s+=int(n)。
count, s = 0, 0

while True:
    n = input('Enter a number: ')
    
    if n.lower() == 'done':
        break
    
    count += 1

    try:
        n = int(n)

    except ValueError:
        continue

    if n >= 0:
        s += n

print(count, s)