Python 代码有问题,我不知道在哪里

时间:2021-06-12 11:55:22

标签: python json python-3.x

这是我的代码的样子,问题是这个程序我的意思是我的代码没有将用户输入保存在 user_info.json 文件中。没有保存的程序本身可以正常工作,但是每当要保存文件时,它就不会。如果此描述或代码混乱等,请告诉我,我将对其进行编辑。 导入json

def make_album(album_title, artist, songs=None):
    """Shows info about artist and an album."""
    info = {'album': album_title.title(),
        'artist': artist.title(),
        }       
    if songs:
        info['songs'] = songs
    return info 

title_prompt = "\nWhat's the name of the album? "
artist_prompt = "Who is the artist? "
song_prompt = "If you know the number of songs on album, write it down,"
song_prompt += " otherwise press 'enter'. "


print("(if you want to shut the program, press 'q')")

def input_album():
    """Accepts user data."""
    while True:
        album = input(title_prompt)
        if album == 'q':
             break

        art = input(artist_prompt)
        if art == 'q':
             break

        song = input(song_prompt)
        if song == 'q':
             break
   
        whole_info = make_album(album, art, song)
    
def save_album():
    """Saves user info in user_info.json."""
    user_info = input_album()
    filename = 'user_info.json'

    with open(filename, 'w') as f:
        json.dump(user_info, f)
    return user_info

1 个答案:

答案 0 :(得分:1)

您的问题是,如 Scratch'N'Purr 的评论中所述,您没有从 input_album() 返回任何内容

尽管假设您直接返回 whole_info 甚至调用:

whole_info = make_album(album, art, song)
return whole_info

return make_album(album, art, song)

这意味着您的程序将在第一次迭代后退出。 也许你需要的是在迭代之前设置一个空列表,并将你的用户输入的所有专辑信息添加到这个列表中,最后返回它。就像这样:

def input_album():
    """Accepts user data."""
    albums = []
    while True:
        album = input(title_prompt)
        if album == 'q':
             break

        art = input(artist_prompt)
        if art == 'q':
             break

        song = input(song_prompt)
        if song == 'q':
             break
   
        new_album = make_album(album, art, song)
        albums.append(new_album)
    return albums