在制定了如何检查猜测是否正确的功能后,我很难说出我想要的东西.
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!'
Run Code Online (Sandbox Code Playgroud)
问题是,当玩家成功猜测代码时,例如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!
Run Code Online (Sandbox Code Playgroud)
我意识到这是因为while循环表明当ntries仍然小于10时循环继续运行.我如何才能使它只打印赢得的尝试次数并停在那里?
使用语句中的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: '))
Run Code Online (Sandbox Code Playgroud)