[Tutor] Do loop in Python

Steven D'Aprano steve at pearwood.info
Tue Nov 29 14:00:45 CET 2011

stm atoc wrote:
> Thank you so much for your reply. It was very helpful information and
> I used it in order to improve the program....
> Here is the new version of the program:
> zvalues = [-200]  # starting value
> hvalues = [10]  # starting value
> increments = [1, 1, 1, 1, 1, 1, 1, 1]
> for N in increments:
>        h = hvalues[-1] - N
>        hvalues.append(h)
>        z = zvalues[-1] + h
>        zvalues.append(z)
>        height = arange((z)*dz,0,dz)
>        for z,when in enumerate(height):
>            nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence
> diffusivity m**2/s
>            nu.append(num + nuh[z])

I'm afraid I still don't know what the arange function is. Is that a function 
you have written yourself? However, I can see that it doesn't actually get used!

You create an arange object, and call it "height".

     height = arange((z)*dz,0,dz)

You should insert a print statement after this line to see what value height 
is given, and check that it is what you expect it to be.

Presumably height is some sort of list or sequence of values, because you next 
use it in a for-loop:

     for z,when in enumerate(height):

So now we know that z takes on the values 0, 1, 2, 3, ... and when takes on 
the values from height, whatever they are. But in the rest of your code, you 
don't use when at all:

         nuh.append(0.001 * exp(-0.005*(z+200.0))*dz)
         nu.append(num + nuh[z])

No when, hence the values from height aren't actually used. Strange.

Also, what are dz and num? You use them both, but I can't see where they are 
defined or what value they have. Likewise nuh and nu, although I can guess 
they are probably lists because you append to them.

Because I don't know what values to use, and I don't know what arange is, I 
can't run your code to see what it does. So I'm reduced to guessing.

If I take a wild stab in the dark that dz is a small number, say, 0.01, I can 
see what values nuh gets:

py> from math import exp
py> dz = 0.01
py> nuh = []
py> for z in range(10):
...     nuh.append(0.001 * exp(-0.005*(z+200.0))*dz)
py> from pprint import pprint
py> pprint(nuh)

Is that the sort of behaviour you expect for nuh?

Since the nuh values are changing, num+nuh[z] should also be changing, which 
implies nu should be changing.

Unless num is so large that rounding error wipes out the nuh values.


More information about the Tutor mailing list