首页 > 解决方案 > while 条件或条件循环的问题(初学者)

问题描述

我很难理解为什么我的 while/or 循环在满足第二个条件后没有被切断

## Guess the word game
import random
secret_word = "computer"
guess = ""
vclueinput, vclueletter , vcluepos = "", "", ""
vtries, vlimit = 0, 5
while guess != secret_word or vlimit > 0: ## I've also tried with vlimit != 0 and fliping the condition's order
    print("You have " + str(vlimit) + " guesses left")
    guess = input("Guess the word: ")
    if guess != secret_word and vlimit > 0:
        vtries += 1
        vlimit -= 1
        vclueinput = input("Wrong! Do you want a clue? [Y/N]: ")
        if vclueinput == "Y" or vclueinput == "y":
            vcluepos = random.randint(0, int(len(secret_word)))
            vclueletter = secret_word[vcluepos]
            print((vcluepos) * "_" + vclueletter + ((int(len(secret_word))) - vcluepos - 1) * "_")
            print("")
        elif vclueinput == "N" or vclueinput == "n":
            print("")
        else:
            print("error")
            print("")
    elif guess == secret_word:
        print("Correct! The secret word is: " + secret_word )
        print("It took you " + str(vtries) + " guesses")
    elif vlimit <= 0:
        print("You are out of Guesses")

正如你所看到的,我有一个向下计数器(vlimit),它一旦达到 0 就会停止 while 循环,由于某种原因,循环会在它刚刚结束时中断,guess = secret_word但不会在vlimit = 0它刚刚结束时中断

print("You have " + str(vlimit) + " guesses left") ##vlimit being 0
guess = input("Guess the word: ")
print("You are out of Guesses")

我希望你能帮助我

标签: pythonwhile-loop

解决方案


如果您使用or,则只需其中一个条件为真,循环即可继续。
如果您想在一个条件为假时中断循环,请使用and. 喜欢
while guess != secret_word and vlimit > 0:


推荐阅读