欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python报错:AttributeError: 'NoneType' object has no attribute 'append'

程序员文章站 2022-03-26 19:31:58
...

源程序:

'''
Rewrite the program that prompts the user for a list of numbers
and prints out the maximum and minimum of the numbers at the end when the user enters "done".
 Write the program to store the numbers the user enters in a list
 and use the max() and min() functions
to compute the maximum and minimum numbers after the loop completes.
'''

list = list() #建立一个空列表
while True:
    str = input('Enter a number: ')
    if str == 'Done':
        break
    try:
        num = float(str)
    except:
        print('You enter the wrong number!')
        quit()
    #print(num)
    list = list.append(num)
print(list)

报错:
Traceback (most recent call last):
File “E:/TESTS/PYTHON/list_ex_03/list_ex_03.py”, line 20, in
list = list.append(num)
AttributeError: ‘NoneType’ object has no attribute ‘append’

原因:
list = list.append(num),由于列表本身是可以被改变的,append()改变了列表并且返回None,list = None会报错。

解决方法:
修改为:

list.append(num)

即可。