[Tutor] Do loop in Python

Steven D'Aprano steve at pearwood.info
Fri Nov 25 12:36:21 CET 2011


stm atoc wrote:
> Hi there,
> 
> I am a new python user.
> I have  a question regarding  do loop.....
> 
> This is a simple program that I have written:
> 
> -----------------
> N=10
> h=10.0 # [micrometer]
> z=-200.0 # [micrometer]

You define N, h and z here, but later on you use them as loop variables. 
So these three values never get used: they are thrown away, and replaced 
by the values of the loops:

h -> 0, 1, 2, ... 9
N -> 0, 1, 2, ... 9

z is especially troublesome, because it gets used for TWO loop 
variables, one inside the other. The inner z loop depends on the outer z 
loop, which makes it tricky to predict what values z will take.


> num = 0.05 #m**2/s
> dz = 1.0
> nuh=[]
> tmax=3600
> dt=20.
> nu=[]height = arange(z*dz,0,dz)

What is arange?

In physics, "height" is a scalar. But later on, you seen to use height 
as if it were a collection of values.


> outfile=open('nu.dat','w')
> outfile.write('height, nu, nuh')
> 
> for z,when in enumerate(height):
>    for h in range(10):
>        for N in range(10):
>            for z in range((N-z)+(N-h)):
> 
>                nuh.append(0.01 * exp(-0.05*(z+200.0))*dz) #turbulence
> diffusivity m**2/s
>                nu.append(num + nuh[z])
> 
> -----------------------
> What I like to do with this program is do loop like the fortran
> version of  as follows:
> 
> do i = 2, N
>  z(i) = z(i-1) +h(i-1)
> 
> end do


How is z initialised? What is h?


I *think* you are trying to add a small increment to each value, based 
on the previous value. Am I close?


Does this example help?


zvalues = [1]  # starting value
increments = [0.01, 0.01, 0.02, 0.01, 0.01, 0.02, 0.01, 0.01]
for h in increments:
     z = zvalues[-1] + h
     zvalues.append(z)

print(zvalues)


(Note: beware of floating point rounding.)




-- 
Steven



More information about the Tutor mailing list