如何在函数 2 中使用函数 1 而不会出现错误?

How do I use function 1 inside function 2 without getting an error?

我声明了我想单独使用的 view_songs() 函数,我还想在另一个函数 add_songs() 中使用它,在执行将歌曲添加到集合。

user_input = input('Enter "a" to add songs,"f" to find existing songs,"v" to view entire collection and "q" to quit :')

while user_input != "q":

    if user_input == "v":

        def view_songs():
            for song in enumerate(Songs_collection, 1):
                print(song)
        view_songs()

    elif user_input == "a":

        def add_songs():
            elements_in_list = len(Songs_collection)
            song_name = input('Enter the name of the song to be added to the collection: ')
            song_artist = input('Enter the name of the artist of the song which was added previously :')
            Songs_collection.insert(elements_in_list, ({elements_in_list + 101: f'{song_name}', f'{elements_in_list + 101}_Artist': f'{song_artist}'}))
            print('Song added to the collection!')
            post_add_input = input('Press "v" to print whole collection or "q" to quit:')
            if post_add_input == "v":
                view_songs()
            elif post_add_input == "q":
                print('Quitting loop...')
            else:
                print('Invalid Input')

        add_songs()

它给了我一个错误 free variable view_songs referenced before assignment in the enclosing scope。我怎样才能在 add_Songs() 中使用这个函数?

根据我上面的评论,这应该有望解决您遇到的问题?

def view_songs():
            for song in enumerate(Songs_collection, 1):
                print(song)

def add_songs():
            elements_in_list = len(Songs_collection)
            song_name = input('Enter the name of the song to be added to the collection: ')
            song_artist = input('Enter the name of the artist of the song which was added previously :')
            Songs_collection.insert(elements_in_list, ({elements_in_list + 101: f'{song_name}', f'{elements_in_list + 101}_Artist': f'{song_artist}'}))
            print('Song added to the collection!')
            post_add_input = input('Press "v" to print whole collection or "q" to quit:')
            if post_add_input == "v":
                view_songs()
            elif post_add_input == "q":
                print('Quitting loop...')
            else:
                print('Invalid Input')

while user_input != "q":
    if user_input == "v":
        view_songs()
    elif user_input == "a":
        add_songs()

    #Some way to redefine user_input?
    #user_input = input()