-4

in the following program:

count = 0
while True:
    count += 1
    if count>10:
         break
    if count==5:
        continue
    print(count)

what exactly is while True testing? And can there ever be a while false condition, if so what would that be testing?

Justin
  • 1,329
  • 3
  • 16
  • 25
  • Not what you want, but... on Python 2.x you could set `True` or `False` to anything... Apart from that it is a infinite loop until something breaks it – JBernardo Feb 02 '14 at 02:31
  • Yes, you can have `while False`. It wouldn't never execute the loop body, so it's not really useful. – Felix Kling Feb 02 '14 at 02:33
  • The 'while true' construct is extremely important in programming. Think of any big program or video game you have ever used. If a program runs for more than a fraction of a second, it probably uses a loop like this. e.g. 'while true: accept user input, move character's position, redraw screen' – Kevin Feb 02 '14 at 02:33

3 Answers3

2

It is an infinite loop. It tests if True is.. true, which it always is.

It is the conditions in the loop that end it; the break statement breaks out of the infinite loop here, not the while condition.

Note that the continue statement merely skips the remainder of the loop iteration and skips to the next.

Other events that'd end the loop are a return (provided the loop is part of a function), or an if an exception was raised.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

while True: is an infinite loop. It will only ever be broken by break, return, or an exception being raised (in your case the first).

Mike Graham
  • 73,987
  • 14
  • 101
  • 130
0

This will create an infinite loop, most likely causing your program to crash. If you would like to stop the loop, use return. You're code is pretty much counting up to 10, then stopping, as seen in

if count>10:
     break

a better way of doing this would be to use a for loop

for count in range(0, 10):
Jojodmo
  • 23,357
  • 13
  • 65
  • 107
  • Why would this cause a program to crash? – Wooble Feb 02 '14 at 02:43
  • @Wooble not in the code that he's using, but an infinite loop will cause a program to crash if there is no stop within it – Jojodmo Feb 02 '14 at 02:45
  • That's a ridiculous assertion. Infinite loops don't cause crashes unless you're using a language with a horribly buggy interpreter or compiler. – Wooble Feb 02 '14 at 14:46