0
# Finicky Counter
# Demonstrates the break and continue statements

count = 0
while True:
  count += 1
  # end loop if count greater than 10
  if count > 10:
   break
  # skip 5
  if count == 5:
    continue
  print(count)

input("\n\nPress the enter key to exit.")

Why does the while True loop apply to count in this circumstance? I dont understand why the boolean is gauging the result of count. Wouldn't the correct syntax be:

while count:

Any help clarifying this would be appreciated.

Zack
  • 661
  • 2
  • 11
  • 27
  • 4
    Simply: It isn't. `while True:` loops forever. The `break` is the only thing that will stop that loop. – Gareth Latty Sep 19 '13 at 20:29
  • Why does it loop forever if the while loop isn't gauging count? What is true then? – Zack Sep 19 '13 at 20:31
  • 4
    `True` is a boolean value that is built into Python. `while x:` looks at `x` on each iteration, and if `bool(X)` is `True`, then it continues to loop, otherwise it stops. As `x` is `True` here, `bool(True)` is always `True`, and so the loop will never stop (well, except for something else stopping it - an exception or a `break` statement). – Gareth Latty Sep 19 '13 at 20:33

3 Answers3

0

count is 0, so while count would never even enter the loop, since 0 is False in a boolean context.

Python doesn't have a construct similar to the repeat ... until (condition) found in some other languages. So if you want a loop to always start, but only end when a condition becomes true, the usual way to do it is to set the condition to just True - which, obviously, is always true - and then explicitly test the condition inside the loop, and break out using break.

To answer your comment, the thing that's true here is simply the value True, which as I say will always be the case.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

It helps if you follow the code step-by-step in a debugger (a simple ide which allows this is PyScripter).

Just a few remarks:

  • while True is an endless loop. It can only be left by a break or return statement.
  • therefore the loop will run until the condition count > 10 is met. The break will terminate the loop and the next command (input ...) is executed.
  • if count == 5, continue tells python to jump immediately to the beginning of the loop without executing the following statement (therefore the "5" ist not printed).

But: follow the code in a debugger!

OBu
  • 4,977
  • 3
  • 29
  • 45
0

The syntax for a while loop is "while condition." The block beneath the while loop executes until either condition evaluates to False or a break command is executed. "while True" means the condition always is True and the loop won't stop unless a break is execute. It's a frequent python idiom used since python doesn't have a do while loop.

Community
  • 1
  • 1
Greg Whittier
  • 3,105
  • 1
  • 19
  • 14