循环值在elif中的列表中

时间:2014-06-08 14:43:56

标签: python python-3.x

我正试图让elif工作,我已经尝试了各种各样,现在有点生气。

基本上如果猜测不等于来自randomwordslist的条目,那么它应该说明它而不是减少猜测而不是去else语句。

错误是" NameError:name' word'未定义"

我是不是错了?

while guess > 0:
    guessed = input("Guess ({} attempts left):".format(guess))
    guess = guess -1
    if guessed == answer:
        print("+++++  You have won  ++++++")
        break

    elif guessed != word in randomwordslist:
        print("Only words from above count as valid entries")
        continue

    else:
        match = 0
        for i in range(len(guessed)):
            if guessed[i].lower() == answer[i].lower():
                match += 1

2 个答案:

答案 0 :(得分:4)

您要求Python测试两件事:

guessed != word and word in randomwordslist

因为Python比较是链接的。但是,您没有word定义,这就是您获得例外的原因。

只测试guessed中是否有randomwordslist

if guessed not in randomwordslist:

如果您想验证字符串不是列表的一部分。 not inin相反,后者测试值是第二个操作数的成员。

如果您不希望受到影响的猜测数量,请先将测试向上移动,然后再进行检查:

while guess > 0:
    guessed = input("Guess ({} attempts left):".format(guess))

    if guessed not in randomwordslist:
        print("Only words from above count as valid entries")
        continue

    # valid guess, so it counts.
    guess = guess - 1

    if guessed == answer:
        print("+++++  You have won  ++++++")
        break

答案 1 :(得分:3)

将此elif块替换为:

elif guessed not in randomwordslist:
    print("Only words from above count as valid entries")
    continue