How to change global variables in Python

To update global variables you could use

global ID
ID="Yes"

before assigning variable to ID = "YES"

But changing ID will be no effect on project variable, project = ("Yep"+ID), because project is already a string

you need to make a function like

def getprojectname(ID):
    return project+ID

The whole program may be like this

UPDATE: ... removed


Beware, you're doing it wrong multiple times.

Even though you could use the global statement to change a global (it is discouraged since it's better to use function parameters and return values), that would NOT change other already assigned values. E.g. even though you reassign ID, you would NOT reassign project. Also: your functions return nothing, there's no point in assigning a name to their return value, and it's a BAD habit using an all-uppercase name (ID) for a variable since it's a convention to use them for constants.

This should clarify you the way global works:

myid = ''
project = ("Yep"+myid) #ID added with no value which I later want to change

def mutate_id():
    global myid
    myid = "YES"

def mutate_project():
    global project
    project = ("YEP" + myid)

if __name__ == '__main__': 
    print "myid", myid
    print "project ", project
    print

    mutate_id()

    print "myid", myid
    print "project ", project
    print

    mutate_project()

    print "myid", myid
    print "project ", project
    print

But the best way is to do WITHOUT globals:

def get_new_id(old):
    return "YES"

def get_new_project(old):
    return ("YEP" + myid)

if __name__ == '__main__': 
    myid = ''
    project = ("Yep"+myid) 

    print "myid", myid
    print "project ", project
    print

    myid = get_new_id(myid)

    print "myid", myid
    print "project ", project
    print

    project = get_new_project(project)

    print "myid", myid
    print "project ", project
    print

This will make all code interaction clear, and prevent issues related to global state change.


Use the global statement.

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals.

Example: http://www.rexx.com/~dkuhlman/python_101/python_101.html#SECTION004340000000000000000

P.S.

But don't use global too often, see http://www.youtube.com/watch?v=E_kZDvwofHY#t=10m45


In your code you have two problems. The first about changing ID variable, which could be solved by using global.

The second that your code calculate project string and after that project don't know about ID.

To avoid code duplication you can define function to calc project.

So we have:

ID = 'No'
def GetProject():
    return "Yep"+ID

def pro():
   global ID
   ID = "YES"
   print ID

print GetProject()

pro()

print GetProject()

Tags:

Python