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

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 3 08:40:40 EDT 2021


On 02/10/2021 22:27, Julius Hamilton wrote:

> 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.

That's one idea of elegance. It's also a maintainers nightmare!
There is a reason that text books recommend listing and
initializing variables at the top of a program/function - it
makes them easy to find. Python allows you to create variables
as the program runs but from a maintainers point of view that
makes finding them a pain (although modern IDEs can help with
that.)

In short, using or referencing variables before they exist
is a very, very bad idea!

> 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”?

The new walrus operator kind of allows this by creating L at the
point of the test but you still need to create a value. If the
code relies on something that does not yet exist that suggests
a flawed design. Or maybe even a non-existent design!? Poke-and-hope
programming often results in these kinds of scenarios. But
poke-and-hope never produces elegant or maintainable code!

> Another idea I have is just using a different loop type. Maybe a syntax
> like:
> 
> do:
>   l = input()
>   if l == “” break
>   g.append(l)

That is basically the common 'while True' idiom.
It's one of, if not the, most common forms of while loop in Python.
But you still need the tested variable to exist before it is tested!

> But I can picture a more elegant way I’d love to see, something like this:
> 
> do (if l == “” break):
>   g.append(l = input())

Some languages support a repeat loop construct for these
types of scenarios. For example in Pascal:

repeat
   L := readln()
   if L <> "" then g.append(L)
until L = ""

In Python we make do with

while True:
   L = input()
   if not L: break
   g.append(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.

Putting it all on one line makes it nearly impossible to debug.
Single lines of code are not usually good practice when dealing
with I/O.

> Is this possible in Python or a different language?

There are hundreds of languages, I'm sure several do what you want.
Fortunately, Python is not one of them.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list