python-AttributeError报错解决办法

  • Post author:
  • Post category:python


报错内容为:AttributeError: ‘NoneType’ object has no attribute ‘append’


源程序:

'''
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)

即可。



版权声明:本文为weixin_43593303原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。