-1

I got some trouble when write some code like this

def wrapper(v):
    v() 
def abc():
    b=1 
    c=2 
def bc():
    b=b+c
    wrapper(bc)
    return b
print(abc())

The result is UnboundLocalError: local variable 'b' referenced before assignment

for some reason I must write code like that way. So I change my code like that way to get rid of that dame problem

def wrapper(v):
    v() 
def abc():
    b=[1,2]
def bc():
    b[0]=b[1]+b[0]
    wrapper(bc)
    return b[0]
print(abc())

It's Unbelievable to got 3 when I run this script. I want to know a rational explanation about that phenomenon. Why I can't get 3 at the first?

yero
  • 29
  • 1
  • 5

1 Answers1

0

It really is a strange way to write code. But if you need this structure for whatever reason: the main problem with your first code is that you forgot the return statement at the end of each function. This code reproduces 3 and is close to your version:

def wrapper(v):
    return v()


def abc():
    b = 1
    c = 2

    def bc():
        return b + c

    return wrapper(bc)


print(abc())
mrCarnivore
  • 4,638
  • 2
  • 12
  • 29