Why doesn't this work ? For loop variable scoping ?

Linuxguy123 linuxguy123 at gmail.com
Thu Mar 19 18:28:26 EDT 2009


Hi people. 

I've got a small piece of code that I don't understand.  Basically, a
variable inside an if statement inside a for loop doesn't seem to be
updating.  Is this a scope issue ?

Thanks

Code segment: 

<snip>

# run through the cycle and calculate the temperature and pressure at
each position, ie every 0.5 crankshaft degrees 
#global newCylinderPressure
#global newCylinderTemperature

for position in range(1,721):
    newCylinderPressure = cylinderPressure[position -1] *
(cylinderVolume[position -1] / cylinderVolume[position])**1.4
    newCylinderTemperature = (cylinderTemperature[position -1] + 459.67)
* (cylinderVolume[position -1] / cylinderVolume[position])**0.4 - 459.67
    
    # add 1.0 BTUs of heat to the combustion chamber at TDC, which is
position # 360
    if position == 360:
        #calculate the new temperature
        print newCylinderTemperature
        deltaTemp = 1.0 / (airMass * Cv)
        newCylinderTempertature = newCylinderTemperature + deltaTemp
        print deltaTemp
        print newCylinderTemperature
....        


The output from this code is:

1357.65862978 <-- newCylinderTemperature when we enter the if statement
2626.04165688 <-- deltaTemp, as it should be
1357.65862978 <-- newCylinderTemperature at the end of the if statement,
which HASN'T CHANGED.  It should be 1357 + 2626 = 3983.   Why doesn't it
change ?  Is there some sort of scope issue here ?






More information about the Python-list mailing list