为什么我一直收到这个错误:TypeError:'bool' object is not iterable?

4

我正在制作一款文字冒险游戏,这是我学习Python书籍的一部分... 无论如何,这就是我的目标:

def is_a_song(song):
    valid_sung_songs = ["song 1", "song 2", "song 3"]
    valid_unsung_songs = ["s1", "s2", "s3"]
    if song.lower() in valid_sung_songs:
        return (True, 0)
    elif song.lower() in valid_unsung_songs:
        return (True, 1)
    else:
        return False

def favorite_song():
    choice = raw_input("> ")
    is_song, has_sung = is_a_song(choice)

    if is_song and (has_sung == 0):
         print "Good Song"
    elif is_song and (has_sung == 1):
         print "Good Song, But I haven't sung it"
    else:
         print "Not a valid song"

favorite_song()

现在这只是我实际使用的代码的简化版本,当运行时,如果歌曲有效且已唱过,它可以工作,如果歌曲有效但未唱过,也可以工作,但最后一个 else 语句会导致崩溃。
else:
    print "Not a valid song"

有一个错误:

TypeError: 'bool' object is not iterable

如果您想要查看我正在使用的实际代码,可以在以下链接中找到:
1个回答

4
你需要在这里返回False, False:
def is_a_song(song):
    ...
    else:
        return False, False

你调用此函数并尝试拆包两个值:

我建议将您的代码更改为:

if song.lower() in valid_sung_songs:
    return True, False
elif song.lower() in valid_unsung_songs:
    return True, True
else:
    return False, False

然后执行以下操作:

if is_song and not has_sung:
     print "Good Song"
elif is_song and has_sung:
     print "Good Song, But I haven't sung it"
else:
     print "Not a valid song"

在我看来,似乎更干净了。

is_song, has_sung = is_a_song(choice)

3
False == 0 --> True - Mike Müller
很高兴它能帮到你。顺便说一下,如果它解决了你的问题,你可以接受一个答案。 - Mike Müller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接