1
def test(a):
    if a>1:
        x=0
    elif a<1:
        y=1
    else:
        x=2
    print(x)
    return 0

Why test(2) is ok but test(0) will raise the following error?

local variable 'x' referenced before assignment

I guess when test(2) x was defined, but run test(0) x was not defined, but also want to know more about the cause

3 Answers 3

1

You pretty much answered it yourself. If a is 0, then the elif a<1 is true, so only y gets defined.

Sign up to request clarification or add additional context in comments.

Comments

0

Because with test(0) the function test() only sets variable y but not variable x, and yet you are unconditionally printing x in the end, causing an UnboundLocalError exception.

Since you are not using y at all, it appears that it is actually a typo, and that you mean to set x to 1 there, so change your code to:

def test(a):
    if a>1:
        x=0
    elif a<1:
        x=1
    else:
        x=2
    print(x)
    return 0

Comments

0

That's because you're not initiating your variables in the function.

When the you have test(0), the second condition elif a<1: y=1 is satisfied. but then you try to print x which is not even defined and the interpreter doesn't know what it is.

def test(a):
...:     if a>1:
...:         x=0
...:     elif a<1:
...:         x=1
...:     else:
...:         x=2
...:     print(x)
...:     return 0

This will not raise the error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.