Global name 'X' not defined

Noah Laster picture Noah Laster · Nov 10, 2013 · Viewed 48.2k times · Source

I looked in all kind of similar questions, but just couldn't find one that fitted my situation (or maybe there is one, but I'm new to programming).

The version of Python that I use is 2.7.4, and I get in my program the error on line 11: NameError: global name 'opp' is not defined

I wanted to make a calculator for dimensions of floors. Here is my code:

def oppervlakte():
    global lengte
    global br
    global opp

    lengte = raw_input("Voer de lengte in: ") # Put in the length
    br = raw_input("Voer de breedte in: ") # Put in the width
    opp = lengte * br # Calculates the dimension of the floor
    return int(lengte), int(br) # Makes the variables lengte & br an integer

print opp

Since I now got the answer, I want to share it with you, so here it is:

def oppervlakte():
    lengte = raw_input("Voer de lengte in: ") # Asks for the length
    br = raw_input("Voer de breedte in: ") # Asks for the width

    lengte = int(lengte) # String lengte --> int lengte 
    br = int(br) # String br --> int br

    opp = lengte * br # Calculates the dimensions of the floor

    return opp, lengte, br

opp, lengte, br = oppervlakte()
print "De oppervlakte is", opp # Prints the dimension

Answer

Ashwini Chaudhary picture Ashwini Chaudhary · Nov 10, 2013

You should call your function, otherwise opp will not get defined.

oppervlakte()
print opp

But a better way would to return opp from the function and assign to a variable in global namespace.

def oppervlakte():
    lengte = int(raw_input("Voer de lengte in: ")) #call int() here
    br = int(raw_input("Voer de breedte in: ")) # call int() here
    opp = lengte * br # Calculates the dimension of the floor
    return opp, lengte, br 

opp, lengte, br = oppervlakte()

And just calling int() on a string will not make it an integer, you should assign the returned value to a variable.

>>> x = '123'
>>> int(x)       #returns a new value, doesn't affects `x`
123
>>> x            #x is still unchanged
'123'
>>> x = int(x)   #re-assign the returned value from int() to `x`
>>> x
123