gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:42:14 24 4
gpt4 key购买 nike

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

正如一个人所说,我尝试将 [] 放在我的代码中。但没有成功。

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

类型错误:“列表”对象不可调用

最佳答案

您使用名称 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()

希望这有帮助。

关于python - 尝试从正在运行的程序添加到列表时列表不可调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56639519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com