我声明了要单独使用的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()
中使用此功能?
答案 0 :(得分:0)
根据我上面的评论,这有望解决您遇到的问题吗?
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()