赢得比赛后如何结束循环?

时间:2015-03-02 21:54:24

标签: python

在制作如何检查猜测是否正确的功能之后,我很难说出我想要的东西。

ntries = 0
while ntries < 10:
    ntries +=1
    if test_guess(code,guess)==True:
        print 'You win! You guessed the code in',ntries,'tries.'
    elif test_guess(code,guess)==False:
        guess = str(raw_input('Your guess: '))
print 'You lose!'

问题在于,当玩家成功猜到代码时,比如8次尝试,打印的结果是:

> You win! You guessed the code in 8 tries. 
> You win! You guessed the code in 9 tries. 
> You win! You guessed the code in 10 tries.
> You lose!

我意识到这是因为while循环表明当ntries仍然小于10时循环继续运行。我如何才能使它只在打赢时停止尝试次数并停在那里? / p>

2 个答案:

答案 0 :(得分:5)

使用break声明中的if关键字突破您的循环。

顺便说一句:您的if-elif块过于冗长。由于test_guess正在返回一些真实的东西,你可以这样重写它。这也会将ntries变量移到else条件中,因为只有在实际猜测时才增加它,但是失败了。

if test_guess(code, guess):
    print 'You win!  You guess the code in', ntries, 'tries.'
    break
else:
    ntries += 1
    guess = str(raw_input('Your guess: '))

答案 1 :(得分:2)

只需使用break

ntries = 0
    while ntries < 10:
    ntries +=1
    if test_guess(code,guess)==True:
        print 'You win! You guessed the code in',ntries,'tries.'
        break
    elif test_guess(code,guess)==False:
        guess = str(raw_input('Your guess: '))
print 'You lose!'