I have a global variables that I am using as a default variable. Depending on what happens in my program I need the ability to change those defaults and have the changes persist through the remaining operation of my code. I want them changed and defined everywhere hence I used a global variable. Here is some test code that shows how I am trying to modify these variables.
When I do this I have the following problems...
- The program thinks that myGlobal hasn t been defined in main. But
- When i call a subroutine after I have changed myGlobal. I didn t want that to happen.
What is the proper way to accomplish what I am trying to do here? Examples?
#!/usr/bin/python import sys myGlobal = "foo" print "********************" print "MyGlobal %s" % myGlobal print "********************" def main(argv): #UnboundLocalError: local variable myGlobal referenced before assignment print 1. Printing the global again: + myGlobal myGlobal = "bar" print "2. Change the global and print again: " + myGlobal # now call a subroutine mySub() # Checks for output file, if it doesn t exist creates one def mySub(): # Why isn t the global "bar" not "foo"? print 3. Printing the global again: + myGlobal myGlobal = "black sheep" print "4. Change the global and print again: " + myGlobal if __name__ == "__main__": main(sys.argv[1:])