PDA

View Full Version : Scope of global variable limited to function


bvldtiger
05-12-2014, 02:16 PM
I have the following code:

def enterEnd(e):
end = time.clock()
position = viz.MainView.getPosition()
ZpositionEnd = position[2]
global elapsedTime
global deltaZpos
elapsedTime = end - start
deltaZpos = ZpositionEnd - ZpositionStart
print 'Final speed', deltaZpos/elapsedTime

This works with a sensor and provides head location data for a motion capture experiment. However, when I try to access the deltaZpos variable in another function I get the following error:


Traceback (most recent call last):
File "C:\Program Files (x86)\WorldViz\Vizard4\python\viztask.py", line 779, in updateAndKillOnException
return self.update()
File "C:\Program Files (x86)\WorldViz\Vizard4\python\viztask.py", line 749, in update
val = self._stack[-1].send(sendData)
File "C:\Users\jorge_leon\Jorge_VR\Fajen_Sequence_Offici al.py", line 252, in experiment_Fajen
yield testPhase()
File "C:\Users\jorge_leon\Jorge_VR\Fajen_Sequence_Offici al.py", line 235, in testPhase
speed = deltaZpos/elapsedTime
NameError: global name 'deltaZpos' is not defined

I checked and the scope limits itself to the function definition but I want to make sure that any other function can access it, and other variables in other functions do the same.

bvldtiger
05-13-2014, 03:32 PM
The other function's code:

# Output all data to file here
def testPhase():
speed = deltaZpos/elapsedTime

Jeff
05-15-2014, 01:14 AM
Is testPhase called before enterEnd? If so then the variables will not be defined and you'll get that error message.