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:“列表”对象不可调用
解决方案
您使用该名称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()
希望这有帮助。
推荐阅读
- javascript - 使用 ReactTS 中已选择的选项创建选择组合
- javascript - 反应中的多级道具
- laravel - Laravel - 动作未定义但已定义
- javascript - Google Apps 脚本 - 如何打破循环以防止出现错误消息
- laravel - Laravel 协议错误
- android - 动态创建的选项卡之一的内容未显示
- php - php - curl查询到后端,混合数据
- gitlab - Gitlab CI 环境 lint 语法不正确
- android - Android Wear 通知总是在前面
- xamarin - 使用页脚销毁 MvxListView 时出现异常