Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

UnboundLocalError when trying Code Challenge: Squared [Answered]

I am trying the Code Challenge: Squared at the moment. I can pass the test but I was trying the code on my own IDE and ran into an odd problem. My code is as follows:

def square(A):
    try:
        num = int(A)
    except ValueError:
        print(A * len(A))
    print (num **2)

square("two")

When I put in

square(5)

I get the appropriate answer of 25

When I put in

square("two")

I get the appropriate answer of twotwotwo

However when I put in "two" I also get an error message. It says

"in square print (num **2) UnboundLocalError: local variable 'num' referenced before assignment".

Even prior to running my IDE highlights the "num" of the "print (num **2)" bit of code. I am not sure why or how to prevent this.

3 Answers

It's because the variable num is defined in the try block. When you enter a non-number variable in the argument (such as "two"), it would go in the block, try to define the num variable but fails because it breaks at int("two"). Because you caught this error using except, it will abort (leaving num undefined) and print(A * len(A)). However, after exiting the try/except block (having printed "twotwotwo"), it will attempt to print (num **2) but num is undefined, which is why it's throwing the error.

You should move the last print command inside the try block, so that it only tries to use num when it is successfully defined.

i.e.

def square(A):
    try:
        num = int(A)
        print (num **2) #HERE!!!
    except ValueError:
        print(A * len(A))

square("two")

Ah! That makes sense! For some reason I got it into my head that I needed that second PRINT command to be on the same line as the TRY command in order to work. It wasn't clicking in my head that it could of course just be nestled into the TRY block immediately.

Thanks for the help!!!

Sorry, I wasn't up to grips with Python syntax.

Try/Except is accompanied by Else afterwards. So instead of moving the second print up inside Try, it's probably better to keep it below except but inside an else clause.

i.e.

def square(A):
    try:
        num = int(A)
    except ValueError:
        print(A * len(A))
    else:
        print (num **2)

square("two")