首页 > 解决方案 > 尝试从正在运行的程序添加到列表时列表不可调用

问题描述

我正在尝试创建一个函数,在该函数中,用户键入一些内容,并将他们键入的内容添加到列表中。

正如一个人所说,我尝试将 [] 放在我的代码周围。但它没有用。

def admin():
    running = False
    print('welcome to admin mode')
    adminOptions = ['Option 1', 'Option 2']
    print(adminOptions)
    selectOption = input('Please type in an option:')
    if selectOption == 'Option 1':
            adminOptions(1)

def adminOptions(opt):
    pcList1 = ['Home Basic PC - $900-$1199', 'Office Computer - $1200-$1499','Gaming PC - $1500-$2199','Studio PC - $2200+']
    if opt == 1:
         newItem = input('Please type in the new item, Admin. ')
         pcList1.append[newItem]
         print('Here is the new list')
         print(pcList1)  

#maincode
admin()

TypeError:“列表”对象不可调用

标签: pythonlist

解决方案


您使用该名称adminOptions两次,一次用于列表(第 4 和 5 行),然后用于第 10 行的函数定义。

当您尝试调用adminOptions()内部的函数admin()时,python 看到已经有一个具有该名称的局部变量(列表),并尝试调用它,而列表不可调用,您会得到您看到的 TypeError。

将里面的局部变量名修改为admin()别的:

def admin():
    running = False
    print('welcome to admin mode')
    adminOptionsList = ['Option 1', 'Option 2']
    print(adminOptionsList)
    selectOption = input('Please type in an option:')
    if selectOption == 'Option 1':
        adminOptions(1)

def adminOptions(opt):
    pcList1 = ['Home Basic PC - $900-$1199', 'Office Computer - $1200-$1499','Gaming PC - $1500-$2199','Studio PC - $2200+']
    if opt == 1:
        newItem = input('Please type in the new item, Admin. ')
        pcList1.append(newItem)
        print('Here is the new list')
        print(pcList1)  

#maincode
admin()

希望这有帮助。


推荐阅读