NameError: free variable 'addcontact' referenced before assignment in enclosing scope

NameError: free variable 'addcontact' referenced before assignment in enclosing scope

请善待我的 n00b 问题,但它让我发疯,不幸的是谷歌搜索并没有太大帮助。

我正在尝试使用空字典编写一个简单的电话簿脚本作为学习练习,但由于我是自学的,没有其他人可以求助。

事情是这样的, 我想编写一个菜单功能,其中包括用于添加、删除和编辑 {name:number} 联系人的子功能

除了我尝试从编辑中调用添加函数时,它大部分都在工作

这是菜单代码的一部分,包括添加例程

def menu():
        selection = (int(input("""1:View phonebook
    2:Add contact
    3:Delete contact
    4:Search for a contact and if necessary edit it
    5:Save and Exit
    
    What would you like to to?""")))
    
        if selection == 1:
            if len(phonebook)== 0:
                print("Phonebook is empty, please add a contact first.")
                loop = input("Press Enter to continue ...")
                menu()
            else:
                print(phonebook)
                loop = input("Press Enter to continue ...")
                menu()
    
        elif selection == 2:
            def addcontact():
                first = (str(input("First name: ")))
                last = (str(input("Last name: ")))
                num = (str(input("Number? ")))
                phonebook.update({last + " " + first: num})
                loop = input("Contact saved, press Enter to continue.")
                menu()
                
                (other stuff...)

menu()

这是给我带来麻烦的更新子例程

    elif selection == 4:
    def search_and_edit():
        search = (str(input("Please type the exact name of the contact you are looking for: ")))
        if search in phonebook.keys():
            print("Name: ", search, "Number: ", phonebook[search])
            edit = (str(input("Do you wish to edit this contact? Y/N")))
            if edit == "N" or edit == "n":
                menu()
            if edit == "Y" or edit == "y":
                phonebook.pop(search)
                addcontact()
        else:
            print("Contact not found.")

        loop = input("Press Enter to continue.")
        menu()

这是来自 PyCharm

的错误消息
File "C:\Users\Derek\PycharmProjects\pythonProject\phonebook\phonebook.py", line 78, in search_and_edit
addcontact()
NameError: free variable 'addcontact' referenced before assignment in enclosing scope
    
Process finished with exit code 1

我在这里做错了什么?其他回调工作正常(例如“循环”回调到 return 到主菜单)但是 addcontact() 失败并显示可变错误消息,即使它是一个函数

欢迎加入。问题归结为 addcontact 在条件 (if...elif...else) 范围内定义,因此对 search_and_edit 不可见,后者在不同且互斥的分支中定义。因此,当您选择 4 时,程序还没有真正输入 2,addcontact 还没有被“创建”。

如果您希望使一个函数在多个位置可用,则将其定义在所有调用者范围内的位置。