How Do You Troubleshoot the Python Problem “NameError: global name ‘var2’ is not defined”?

Problem scenario
You have a Python program that works, but you get an error when you run it. You get a message like this: "NameError: global name 'var2' is not defined"

Here is your source code:

def fun1(var1):
   print("this is how it works")
   var1 = var2
   return var2 
b = fun1("check it out")
 print(b)

What should you do about this error?

Solution
A variable inside a function must be defined. You can either define var2 locally or globally. But you have to define it.

Here is an example of using a global variable inside a function:

var2 = "" 
def fun1(var1):
   print("this is how it works")
   global var2
   var1 = var2
   return var2
 b = fun1("check it out")
 print(b) 

Here is an example of using a local variable inside a function:

def fun1(var1):
   print("this is how it works")
   var2 = "33333"
   var1 = var2
   return var2
 b = fun1("check it out")
 print(b)

Leave a comment

Your email address will not be published. Required fields are marked *