如何向while循环添加计数器? [英] How to add a counter to a while loop?

查看:59
本文介绍了如何向while循环添加计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码要求用户猜测计算的答案,然后要么告诉他们他们是正确的,要么试图找出他们哪里出错了.我在这里使用了一个 while 循环,但有时它会卡住,有没有办法为所采取的猜测添加一个计数器,并在 5 次错误猜测后中断 while 循环?

I have some code which asks the user to guess the answer to a calculation, and then either tells them they are correct or tries to identify where they went wrong. I have used a while loop in this but sometimes it gets stuck, is there a way to add a counter to the guesses taken, and to break the while loop after 5 incorrect guesses?

推荐答案

Pythonic方式是

max_guesses = 5
guessed = False
for wrong_guesses in range(max_guesses):
    if A==round(Ac,2):
      print("correct")
      guessed = True
      break 
    ...
else:
  print("You have exceeded the maximum of {} guesses".format(max_guesses)) 
if not guessed:
  wrong_guesses += 1

这样循环最多执行 max_guesses 次.else 块仅在循环由于 break 语句而没有结束时才执行,即没有正确的猜测.

This way the loop is executed at most max_guesses times. The else block is only executed if the loop did not end because of a break statement i.e. when there was no correct guess.

请注意,最后的 if not guessed 是为了计算最后一个不正确的猜测,因为循环以 wrong_guesses ==(在这种情况下为 max_guesses - 1)结束.这是因为 range 是区间 [0, max_guesses) 上的迭代器(不包括上限).

Note the if not guessed at the end is to cater for counting the last incorrect guess because the loop ends with wrong_guesses == (max_guesses - 1 in that case). This is because range is an iterator over the interval [0, max_guesses) (excluding the upper limit).

这篇关于如何向while循环添加计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆