0

I'm currently using the while True loop, but if the same error is repeated 3 times, please tell me how to exit the while True statement. I use python.

skw0314
  • 107
  • 7

2 Answers2

3

You can add a variable keeping track of the last error's type, and a counter for the how many of those occurred, which resets if an error of a different type appeared. If the counter hits 3, then exit accordingly.

last_exception, counter = None, 0
while True:
   try:
      # some error here
      raise ValueError
   except Exception as e:
      if type(e) is not last_exception:
         last_exception, counter = type(e), 0
      counter += 1
      if counter == 3:
         break
kwkt
  • 1,058
  • 3
  • 10
  • 19
  • What should I do to break if the same error occurs three times in a row? – skw0314 Dec 30 '20 at 06:55
  • Then just reset the counter if it doesn't occur continuously: in the `try` block, after the error-prone code, add `counter = 0`. If the code runs successfully, the consecutive error counter resets. Edit: Unless you mean that your code may throw different errors, and you would want the loop to terminate if the last 3 errors are identical, then please edit your question and I'll answer accordingly. It'll only involve some extra keeping track of things. – kwkt Dec 30 '20 at 06:56
  • As you said, if the last three errors are the same, I want to break it. – skw0314 Dec 30 '20 at 07:04
  • @skw0314 Updated my answer to accommodate that. – kwkt Dec 30 '20 at 07:08
1

You just declare a variable outside your loop and initialize to 0, increment it by one each time the loop iterates, and your while loop iterates while it's less than 3

i = 0
while i < 3:
  print(i)
  i += 1

Edit: I just realised you said while true Take a look at this What does "while True" mean in Python?

If you have to use a while true then use an if statement to check if i >=3 and then use a break statement to exit the loop if that's true

Neve
  • 367
  • 2
  • 9