尝试从正在运行的程序添加到列表时,列表不可调用

2024-06-28 19:03:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数,在这个函数中,用户键入一些内容,然后将他们键入的内容添加到列表中

正如一个人所说,我试着在我的代码中加入[]。但它不起作用

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:“列表”对象不可调用


Tags: 函数内容列表input键入admindeftype
2条回答

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

当您尝试在admin()内调用函数adminOptions()时,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()

希望这有帮助

除了需要更改adminOption之外,在尝试附加到pcList1时还遇到了一个错误:

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)   #Parentheses are needed, not brackets
        print('Here is the new list')
        print(pcList1)  

#maincode
admin()

append()是一个方法,因此需要括号

相关问题 更多 >