Search code examples
pythonfunction-call

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


I declared the view_songs() function which I want to use separately and I also want to use it inside another function add_songs() with a conditional, after the code which does the part of adding songs to the collection.

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()

It gives me an error which says free variable view_songs referenced before assignment in the enclosing scope. How can I go about to using this function inside add_Songs()?


Solution

  • As per my comment above this should hopefully solve the issues you're having?

    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()