0
What does this actually mean "while True:" in while loop?
THIS MEKE ME CONFUSED WHEN ENCOUNTING SUCH PROBLEM IN ANY PROGRAM. I WOULD LIKE TO KNOW THE ACTUAL SENSE OF IT.
4 Antworten
+ 4
It creates an infinite loop. If you use it, you need to provide a terminating condition in the body of the while loop. E.g. with a break command.
while True:
do_stuff()
if x:
break
+ 2
A typical "while" statement works this way:
while (condition):
#some code
The condition in brackets is basically...a condition, which is either true or false. Like:
while a == 1:
a += 1
Which means add 1 to a while a has the value of 1. So, the code will only execute when the condition, a equals to one, is true. Only then will you add one.
Coming back to your question, while True is pretty simple. The condition, in this case True, is... True. Hence as there is no way True is False, (i.e. True is always True), this statement basically creates an infinite loop (ooh, dangerous stuff). If you have an infinite loop, you must (or should) have a break statement. Like so:
while True:
a += 1
This code will execute forever, adding 1 to a to infinity. Well, that's no good! How do you stop that?
while True:
a += 1
break
Well, just put a break. Now this code well only execute once. But what if you want it to stop when a is 10? You guessed it --
while True:
a += 1
if a == 10:
break
But there's only so much you know when you are being taught by someone. The best way to learn -- try it yourself! I probably have you more than you asked for - hope this helped in any case. 😉
0
basically it's saying that the code in that loop is to be executed as long as the condition evaluates to true. when de condition becomes false, the loop ends and the program continues from the next line after the loop.
0
You could use it in a game for example as a means to keep playing until the winning score is reached.