Как использовать функцию 1 внутри функции 2, не получая ошибки? - PullRequest
0 голосов
/ 20 января 2019

Я объявил функцию 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()?

1 Ответ

0 голосов
/ 20 января 2019

В соответствии с моим комментарием выше, это, мы надеемся, решит ваши проблемы?

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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...