+ 1
Is there a builtin way to reference a while loop condition without restating it?
Something like this: thing = None while not thing: thing = try_to_get_thing() if |reference loop condition|: #Same as if not thing time.sleep(TRYAGAIN_DELAY) I know I could just define the condition as a function, but this comes up often enough that I feel like there might be a builtin syntax for referencing the running loop's condition.
10 Réponses
+ 9
just for completeness:
if we are using an assigment expression in a while loop header, we can also explicitely define the break condition like this :
import random
while (n := random.randint(0, 10)) != 7:
print(n, end=", ") # all except 7
else:
print(n) # 7
we have to enclose the first part of the expression in parenthesis, otherwise bolean values will be stored in variable `n`.
+ 6
Wilbur Jaywright ,
An assignment expression using the "walrus" operator := might help.
https://docs.python.org/3/reference/expressions.html#assignment-expressions
This snippet prints random ints until it hits 0. Notice that the header of the while clause assigns a random int to n then uses the value of n as the condition, and you can reference n inside the suites of both the while clause and the else clause.
import random
while n := random.randint(-10, 10):
print(n, end=" ") # non-0
else:
print(n) # 0
+ 2
In Python, there isn't a direct built-in way to reference the condition of a while loop without restating it. But, you can achieve similar functionality by using a flag variable within the loop.
See this: https://stackoverflow.com/questions/68879241/stop-while-loop-w-variable-flag
+ 2
Rain This is really awesome.
https://sololearn.com/compiler-playground/ci2VJwy3ln86/?ref=app
+ 2
`нттp⁴⁰⁶ ,
Glad you like it. I wasn't quite done. I have a bad habit of realizing I need to edit my comments immediately after I submit them. I edited the snippet to include equal likelihoods of negative and positive ints.
+ 2
Wilbur Jaywright, OK:
import random, time
thing = None
condition = not thing
while condition:
thing = random.randint(0,9)
condition = 0<thing<5
print(thing)
if condition:
time.sleep(1)
print("TRYAGAIN_DELAY")
If it doesn't matter to you what happens after the last sleep command, then you don't need to write the "if condition" condition.
And of course this code can be shortened using the operator ":=", as other participants in the discussion have already noted.
+ 1
Solo in the given example, the delay before trying again to assign a non-nil value to “thing” is pointless if the first try was a success.
+ 1
Lothar ,
Nice. That frees it up tremendously.
+ 1
Lothar that looks like it will do what I wanted.
0
What's the point of that?
Why repeat the same condition twice?
It's like writing:
if true:
if true:
...