I've got a while loop of the form:
while temp is True:
do stuff
if the outcome is what I want:
temp = False
I seem to use this construct quite often. So my question is whether there is a way I can initialise temp in the while statement itself, rather than have to precede this with temp = True
?
CodePudding user response:
You can use:
while True:
do stuff
if the outcome is what I want:
break
CodePudding user response:
There is a way.
For example:
temp = True
while temp == True:
do stuff
if the outcome is what I want:
temp = False
or
while temp == True:
do stuff
if the outcome is what I want:
break
CodePudding user response:
Starting with Python 3.8, you can use an assignment expression (AKA walrus operator):
while temp := True:
...
if ...:
temp = False