Python AttributeError:“str”对象没有属性“list”

Python AttributeError:“str”对象没有属性“list”,python,python-3.x,Python,Python 3.x,我们必须找出通过键盘输入的数字列表的平均值 您没有保存输入的号码。尝试: n = [] while True: a=input("Enter number: ") try: #Checks if entered data is an int a = int(a) except: print('Entered data not an int') continue

我们必须找出通过键盘输入的数字列表的平均值


您没有保存输入的号码。尝试:

n = []
while True:
    a=input("Enter number: ")
    try:                     #Checks if entered data is an int
        a = int(a)
    except:
        print('Entered data not an int')
        continue
    if a == 0:
        break
    n.append(a)
print(sum(n)/len(n))

如果列表n将输入的数字保存为一个数字,则需要有一个实际的列表,在其中附加输入的值:

lst = []
while True:
    a = int(input("Enter number: "))
    if a == 0:
        break
    else:
        lst.append(a)
print(sum(lst) / len(lst))

这种方法还没有任何错误管理——用户在第一次运行时输入浮点数或无意义或零,等等。。您还需要实现这一点。

a需要是要使用sum的对象列表,在您的情况下不是。这就是为什么列表不起作用。在您的情况下,您需要将输入作为int,可以这样做:a=intinpunter a number;然后获取整数用户输入并附加到一个列表中,假设其名称为ListNamelistName.appenda,然后您可以这样做来计算平均值:


平均值=sumlistName/lenlistName

您可以循环、监听输入并更新s sum和c count变量:

   s, c = 0, 0
while c >= 0:
    a = int(input("Enter number: "))
    if a == 0:
        break
    else:
        s += a
    c += 1
avg = s/c
print(avg)

成功了,谢谢!但是我们还没有学会这里使用的很多术语,所以我们的老师不会接受。我将尝试在这里进行一些更改,看看它是否有效:除了引起关注的原因?
def calc_avg():
     count = 0
     sum = 0
     while True:
         try:
             new = int(input("Enter a number: "))
             if new < 0:
                 print(f'average: {sum/count}')
                 return
             sum += new
             count += 1
             print(f'sum: {sum}, numbers given: {count}')
         except ValueError:
             print("That was not a number")

calc_avg()
   s, c = 0, 0
while c >= 0:
    a = int(input("Enter number: "))
    if a == 0:
        break
    else:
        s += a
    c += 1
avg = s/c
print(avg)