In a python function, do I need to pre-allocate a value which appears conditionally under if?

Viewed 69

In a python function, do I need to pre-allocate a value which appears conditionally under if?

def func(x,y):
    if x == 1:
        z = 2
    else: pass

    if y == 1:
        print(z)
    else: pass

I see the problem here that print(z) may blow up if x != 1 and y == 1. To potentially prevent this error raiser, do I declare z = None at the beginning of the function or use try-except to print z or other ways to do? What would be the best practice?

3 Answers

The short answer is Yes.

If you want to do something like: print(z) later in the function, then z should be assigned to first.

You have some options:

def func(x, y):
    if x == 1:
        z = 2
    else:
        z = None

# or
def func(x, y):
    z = None
    if x == 1:
        z = 2

# or
def func(x, y):
    z = 2 if x == 1 else None

to prevent the "blow up" you have to define your variable at the beginning of your function or before to be used, in your case you may use:

def func(x, y):
    z = None
    if x == 1:
        z = 2

    if z and y == 1:
        print(z)

You can simply do:

def func(x,y):
    z = 2 if x == 1 else None
    print(z)

That means z will always be assigned by 2 or None if x == 1 or else respectively.

Related