2

I have the following code in python:

board = 0

def Board1():
    global board
    board = 1

def Board2():
    global board
    board = 2

def Board3(board):
    board = 3
    print board

def ReadBoard():
    print board

I think the functions Board1 and Board2 should change the value of the global variable board. But here is what happens: When I call board it returns 0. If I call Board1, the global board value does not change, but if I call ReadBoard, it gives the value Board1 has assigned. For example (in python console):

>>> board  
0  
>>> Board1()  
>>> board  
0  
>>> ReadBoard()  
1  
>>> Board3(board)
3  
>>> board  
0  
>>> board = 4
>>> ReadBoard()
1  

I could not understand why I cannot change the global variable globally and why am I reading the changed variable in the ReadBoard function.

2
  • First please fix your indentation in your functions Commented Mar 25, 2013 at 15:11
  • -1 for not mentioning at all that you did from somemoduleididntmention import *, which you should never do and which is also your entire problem. Commented Mar 25, 2013 at 15:42

2 Answers 2

3

You have a Python module that defines board. In your console you have another, distinct object that you name board. When you output board from your console you get that object. When your module that contains your functions prints board, it prints the object defined in that module.

So the fundamental problem is that you have two things that you call board.

I expect that you imported the module like this:

from MyModule import *

Having done that you've no way to distinguish between the two board objects. So instead use:

import MyModule

Then you can use MyModule.board to refer to the global board defined in the module.

Sign up to request clarification or add additional context in comments.

Comments

1

After you import the global variable board into your Python console once, it doesn't change. Try putting that code into your file (as print statements) rather than executing it in the console and it should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.