NameError: Variable name is not defined

NameError: Variable name is not defined

我在使用嵌套循环和函数的学校作业代码中遇到一些未定义变量的问题。另外,如果您碰巧发现任何其他错误,请lmk。

代码:

shopping_lists = [
['toothpaste', 'q-tips', 'milk'],
['milk', 'candy', 'apples'],
['planner', 'pencils', 'q-tips']
]

customer_input = ''

#prints shopping lists
print(shopping_lists)
print ('')

print("Press '1' to update an item, '2' to view an item, or '3' to view a list")
customer_input = input("What do you want to do? ")
if customer_input == '1':
  def update_list(List, Item, newItem):
    list = int(input('What list would you like to update? Answer using 1, 2, or 3. ')-1)
    print (shopping_lists[list])
    
    itm = int(input('What item would you like to view? ')-1)
    print (shopping_lists[list][itm])
    
    newItm = input('What would you like to change the item to? ')
    shopping_lists[list][itm] = newItm
    
    update_list(list, itm, newItm)

def view_item():
  pass

def view_list():
  pass

#While loop
while 'stop' not in customer_input:
  update_list(list, itm, newItm)

我会重新安排你的执行流程如下。

shopping_lists = [
    ['toothpaste', 'q-tips', 'milk'],
    ['milk', 'candy', 'apples'],
    ['planner', 'pencils', 'q-tips']
]

def handle_action(action):
    if action == '1':
        update_list()
    elif action == '2':
        view_item()
    elif action == '3':
        view_list() 
    else:
        pass
        # What if an unrecognized action is used?

def update_list():
    list_number = int(input('What list would you like to update? Answer using 1, 2, or 3. ')) - 1
    print(shopping_lists[list_number])
    
    itm = int(input('What item would you like to view? ')) - 1
    print(shopping_lists[list_number][itm])
    
    newItm = input('What would you like to change the item to? ')
    shopping_lists[list_number][itm] = newItm

    
def view_item():
    pass


def view_list():
    pass


#While loop
customer_input = ''
while customer_input != 'stop':
    print(shopping_lists)
    print("Press 1 to update an item, 2 to view an item, or 3 to view a list")
    customer_input = input("What do you want to do? ")
    handle_action(customer_input)

注意使用 stop 作为循环中断词的区别。还有 handle_action 函数来控制你正在做的事情的开关。

我也将 list 重命名为 list_number 因为 list 是 python 中的类型名称。