[Tutor] Condition for variable which doesn’t exist yet

dn PyTutor at DancesWithMice.info
Sat Oct 2 22:46:22 EDT 2021


On 03/10/2021 10.27, Julius Hamilton wrote:
> Hey,
> 
> I’d like to make a while-loop stop on a condition related to an equivalence
> statement on a variable (while L != “”). However, I’d prefer to not declare
> this variable before the while loop, for the sake of elegance.
> 
> Is there any syntax or idea that comes to mind that would allow me to say “
> while L!=“” “ and for the program to understand, “L doesn’t exist yet so
> this is fine, the only issue is if it exists and it’s a blank string”?
> 
> Another idea I have is just using a different loop type. Maybe a syntax
> like:
> 
> do:
>   l = input()
>   if l == “” break
>   g.append(l)
> 
> What would be the Python for this?
> 
> But I can picture a more elegant way I’d love to see, something like this:
> 
> do (if l == “” break):
>   g.append(l = input())
> 
> This hopefully says to check at all times if l is ever “”. If it ever
> happens, break the loop. Meanwhile, the input is getting passed to the
> variable l, and then appended straight to the list g, in one line of code.
> 
> Is this possible in Python or a different language?
I started a thread about the repeat ... until condition construct, for
"elegance" and because I consider the while+forever...break construct be
(a) ugly, (b) higher complexity, and (c) contrary to the Zen of Python,
over on the [main] Python List, a few weeks back.

In this case you might be able to sneak under-the-wire with:

>>> l = list()
>>> while i := input( "? " ):
...     l.append( i )
...
? a
? b
? c
? d
?
>>> l
['a', 'b', 'c', 'd']

-- 
Regards,
=dn


More information about the Tutor mailing list