0

I have a very small sample of code that uses a try:except block and I'm a bit confused as to why it returns hi as not being defined:

def myFunction():
    try:
        pass
    except:
        hi = "bunk"
    print(hi)

hi = "blah"
myFunction()

I would have expected it'll remain as "blah" unless it fell in the exception, in which case it'll turn into "bunk". When debugging, the IDE returns "blah" as the value of hi, but throws an exception when it tries to print it.

It appears as though hi becomes a local variable within the function, so once it gets to the print statement, it fails with an error that it's not defined as the try statement didn't define it. Is that what is happening?

I realize that if it's not defined, it'll throw the UnboundLocalError, but the following works fine:

def myFunction():
##    try:
##        pass
##    except:
##        hi = "bunk"
    print(hi)

hi = "blah"
myFunction()
  • `hi` _is_ a local variable in the function. If that isn't what you want, you'll need to use `global` or pass it in as an argument to the function. – FamousJameous Jul 17 '17 at 22:30
  • It is throwing a error! `UnboundLocalError: local variable 'hi' referenced before assignment` – Sriram Sitharaman Jul 17 '17 at 22:31
  • 1
    The except: hi = "bunk" causes the compiler to create a local but unbound version of hi. Since hi = 'bunk' will never be evaluated, print(hi) will always throw an error. When you comment out except: hi = "bunk", the compiler no longer creates a local, unbound version of hi, so the global hi is used for print(hi). – Alan Leuthard Jul 17 '17 at 22:41
  • The error is thrown AFTER the try:except block, when it tries to execute the print statement. – Paul Cornelius Jul 17 '17 at 22:41
  • @AlanLeuthard thank you! That makes it pretty clear. – lilquinny14 Jul 17 '17 at 22:43

0 Answers0