Videos
https://pastebin.com/NWkKQc1P
It's from Automate the Boring Stuff. I tried running it through the python tutor and it didn't clarify. Is the basic point that there actually isn't anything it's checking to be True, so it's an infinite loop until you trigger the `break`?
PS I figure this is something simple from much earlier that I didn't internalize. I plan to go through all the basic curriculum again to make sure there aren't any gaps in super basic knowledge.
while True means loop forever. The while statement takes an expression and executes the loop body while the expression evaluates to (boolean) "true". True always evaluates to boolean "true" and thus executes the loop body indefinitely. It's an idiom that you'll just get used to eventually! Most languages you're likely to encounter have equivalent idioms.
Note that most languages usually have some mechanism for breaking out of the loop early. In the case of Python it's the break statement in the cmd == 'e' case of the sample in your question.
my question: while WHAT is True?
While True is True.
The while loop will run as long as the conditional expression evaluates to True.
Since True always evaluates to True, the loop will run indefinitely, until something within the loop returns or breaks.
You can try wrapping that code in a try/except block, because keyboard interrupts are just exceptions:
try:
while True:
IDs2=UpdatePoints(value,IDs2)
time.sleep(10)
except KeyboardInterrupt:
print('interrupted!')
Then you can exit the loop with CTRL-C.
You could use exceptions. But you only should use exceptions for stuff that isn't supposed to happen. So not for this.
That is why I recommand signals:
import sys, signal
def signal_handler(signal, frame):
print("\nprogram exiting gracefully")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
you should put this on the beginning of your program and when you press ctrl+c wherever in your program it will shut down gracefully
Code explanation:
You import sys and signals.
Then you make a function that executes on exit. sys.exit(0) stops the programming with exit code 0 (the code that says, everything went good).
When the program get the SIGINT either by ctrl-c or by a kill command in the terminal you program will shutdown gracefully.
what does the True refer to?
eg if i write:
while True:
print("hi")i know that "hi" will be repeated infinitely, but what is it thats True thats making "hi" get printed?
also, whatever it is thats True, im assuming its always true, so is that why if i typed 'while False', none of the code below would ever run?
sorry if this is a stupid question
edit: also, besides adding an if statement, is there anything else that would break this infinite while loop?
and how would i break the loop, lets say after "hi" has been printed 10 times, using an if statement or whatever else there is that can break it. thanks!