0

I am new to python, and I'm trying to understand difference between these hello world examples

def hello(hi):

    def world(obj):
        return hi + ', ' + obj + '!'

    return world


world = hello('Hello')
print(world('World'))

Hello, World!
def hello(hi):

    def world(obj):
        hi = hi + ', ' + obj + '!'
        return hi

    return world


world = hello('Hello')
print(world('World'))

      2 
      3     def world(obj):
----> 4         hi = hi + ', ' + obj + '!'
      5         return hi
      6 

UnboundLocalError: local variable 'hi' referenced before assignment

Why does the second example fail?

1 Answers1

1

The second chunk of code fails because hi is a parameter in the scope of the hello function, yet it is assigned again in the world function

Ironkey
  • 2,568
  • 1
  • 8
  • 30