global variable

define global variable


Syntax: global var
Description: Define a variable as global
Parameters var Name of a variable
Returns:
Related:  def interrupt_setup


The global command is used only inside a function to define a variable as being  global.  It means you can modify a toplevel variable from inside a function.

Using a global variable  in a function allows the function to change toplevel variables.

When a function returns a value using the return statement, it can only return one value. Using a  global variable inside a function means that the function can change multiple variables.

The rules by which variables can be seen by functions in the program is called the variable scope rules

mpy variable scope rules

  • A variable which is assigned a value at the toplevel (e.g. a=3) can be seen inside all lower level functions,  but only if that function does not assign a variable of the same name
  • A variable which is assigned a value at the toplevel can be modified at the toplevel,  and can be modified in a lower level function only if the global command is used in that function.
  • A variable which is assigned a value inside a function is called a local variable, it can only be seen and modified inside that function.  However if the variable defined as global in the function then it can also be modified in the toplevel, but it cannot be modified inside other functions (not unless those functions also declare the same variable as global)

Variables inside functions are local variables, their values are not remembered when you run the function a second time. However if you declare the variable as a global variable then its value will be remembered.

Note that there is no need to use the global command for variables in the toplevel, toplevel variables are always global

Example:

def get_switch_values():
    global start_motor
    global turn_left
    global turn_right
    start_motor = inp(P1_3)
    turn_left   = inp(P1_4)
    turn_right  = inp(P1_5)
pindir(P1_3, INPU)
pindir(P1_4, INPU)
pindir(P1_5, INPU)

while 1:
    get_switch_values()
    if start_motor == 0:
        print 'Off we go' 
    if turn_left == 0:
        print '  hold tight we are turning left' 
    if turn_right == 0:
        print '  hold tight we are turning right'
    wait(1000)

This example shows the use of the global command. Variables start_motor, turn_left, and turn_right  are defined as global meaning that those variables can be modified inside the function get_switch_values()  and then be used at the top level program to show which switch has been pressed.