条件计数循环Python

时间:2015-05-19 13:24:36

标签: python

我正试图找出我的错误在下面的代码中,这是关于猜一个字。

如果我输入缺失的单词"ghost",它应该结束游戏,但它会继续要求它。

我的错误在哪里?

number = 0
missword = "ghost"
while number < 3:
    guess = input("What is the missing word? ")
    if guess != "ghost":
        print("Try again")
        number = number + 1
    elif guess == missword:
        print("Game Over")
    else:
        print("Game over")

1 个答案:

答案 0 :(得分:6)

你所有的循环都是打印,你需要一个中断声明:

number=0
missword="ghost"
while number<3:
    guess = input("What is the missing word? ")
    if guess!="ghost": # Assuming you actually want this to be missword?
        print("Try again")
        number += 1 # Changed to a unary operator, slightly faster.
    elif guess==missword:
        print("Game Over")
        break
    else:
        print("Game over")
        # Is this ever useful?

break在满足退出条件之前退出循环。另一方面,Print只是将文本输出到stdout,而不是其他任何内容。