The global name "X" is not defined

I looked through all the similar questions, but could not find the one that corresponded to my situation (or maybe one, but I'm new to programming).

The Python version I'm using is 2.7.4, and I get an error in my program on line 11: NameError: global name 'opp' is not defined

I wanted to make a calculator for floor sizes. 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 got an answer, I want to share it with you, 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 
+6
source share
1 answer

You must call your function, otherwise opp will not be defined.

 oppervlakte() print opp 

But the best way to return opp from a function and assign a variable in the 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 have to assign the return 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 
+9
source

Source: https://habr.com/ru/post/957769/


All Articles