# 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.
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.
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. count > 10
is met. The break will terminate the loop and the next command ( input ...
) is executed. 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!
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.