Assigning Variables

Hey all,

Still a pretty new user here, but getting more and more comfortable with Python. Just a question about when/where variables should be assigned. I remember from high school Java that in many cases, variables could be assigned at the beginning of the code but as I continue to learn Python, it seems more common that variables are assigned as you use them (ie. instead of in a single block at the beginning, they come in the middle of code as they’re needed, in if blocks, etc.)

Is there a “right” way to do this with Python? Is the right way to create them as they’re needed?

Thanks,
Ryan

As you need them is often fine. But remember also that (a) globals are
largely discouraged (they bring many limitations and can leave you open
to easy mistakes) and (b) that functions should generally be fairly
short.

The result of (b) is that “as you go” is generally not far from the top
anyway.

There’s little point to assigning things dummy values purely to have the
assignments at the top. Look at this:

def f(a, b):
    c = None
    print("blah")
    for c in range(3):
        print(c)

That “c = None” isn’t doing you any good. You’re just discarding the
value later and not using it before then. Worse, it might suggest to
someone that “c=None” is a meaningful thing. It also removes a degree of
protection. Example:

def f(a, b):
    # some totally made up logic
    for i in range(3):
        c += a * i
        c += b

Here we’re using “c” before it is defined. A logic bug t be sure. But if
you had a dummy “c = 0” at the top of the function you might not have
Python tell you this - you’d just have wrong results which you would
have to debug.

I say “generally”; of course there are exceptions to everything.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like