如何调用函数而不导致循环

时间:2018-06-20 03:09:45

标签: python python-3.x

我有此代码:

def make_album():
    album1 = {}
    album2 = {}
    album3 = {}
    for x in range(3):
        album_nm = input("Album name: ")
        artist_nm = input("Artist name: ")
        if x == 0:
            album1[album_nm] = artist_nm
        elif x == 1:
            album2[album_nm] = artist_nm
        elif x == 2:
            album3[album_nm] = artist_nm
    return album1, album2, album3
make_album()
print(make_album())

当我通过终端启动代码时,即使我在artist_name中要求仅被调用3次,它仍要求我输入专辑名称和range 6次。我发现此错误是由于for循环启动的,即使我没有调用它属于make_album()的函数也是如此。我不希望调用make_album()函数内的循环,因此它将要求我仅在range(3)中输入要求输入的数据三次。

2 个答案:

答案 0 :(得分:0)

查看代码的最后两行

make_album()
print(make_album())

您两次调用了函数make_album(),这就是为什么您获得6次输入的原因。只需更改为:

result = make_album()
print(result)

或者,只需删除倒数第二行:

print(make_album())

祝你好运

答案 1 :(得分:0)

更多pythonic代码:

def make_album():
    albums = []
    for x in range(3):
        print(x+1)
        album_nm = input("Album name: ")
        artist_nm = input("Artist name: ")
        albums.append({album_nm: artist_nm})
    return albums
albums = make_album()
print(albums)