0

I have a code like this

ten=(1,7,8,10)
ten=np.array(ten)
nine=(3,6,9)
nine=np.array(nine)
lat=range(1,11)
p_new1=[]
H2O_vmr_new1=[]
level=range(1,91)
row=range(0,6)
for j in lat:
    if j in ten:
        print j
        for a in level:
            if((H2O_vmr[a]-H2O_vmr[a+1])/(p[a]-p[a+1]))-((H2O_vmr[a-1]-
        H2O_vmr[a])/(p[a-1]-p[a]))>.000001:
                p_new1.append(p[a])
                H2O_vmr_new1.append(H2O_vmr[a])
    elif j in nine:
        for a in level:
            if((H2O_vmr[a]-H2O_vmr[a+1])/(p[a]-p[a+1]))-((H2O_vmr[a-1]-
                H2O_vmr[a])/(p[a-1]-p[a]))>.000001:
                p_new1.append(p[a])
                H2O_vmr_new1.append(H2O_vmr[a])

only the first if loop is working that too it takes only the last value of 'j'(i tried printing 'j').second loop-'elif'(I tried 'if' instead of 'elif' also) is not working even.I'm really new to this.Any help will be appreciated.

Note:I have not posted the full code,since it is very long.I have only posted the part which is showing errors.

caty
  • 121
  • 12

1 Answers1

1

Your for loop works, there is no issue there. You haven't posted the values of H2O_vmr and p so I don't know what you're trying to do exactly.

If I was to make an assumption, I would say you're trying to access the loop index, and that might be the problem.

H2O_vmr[a+1]

I assume you're using a+1 in an attempt to access the next index and using a-1 in an attempt to access the previous index. This may be the reason for the confusion. a+1 is not accessing the next index, instead it takes the value of a and adds 1 to it. In order to get the index in a for loop, you can:

for idx, val in enumerate(ints):
    print(idx, val)

Accessing the index in Python 'for' loops

Let me know if my assumption is correct, otherwise provide contents of the two arrays being used in your formula.

To prove that your for loop works:

import numpy as np
ten=(1,7,8,10)
ten=np.array(ten)
nine=(3,6,9)
nine=np.array(nine)
lat=range(1,11)
p_new1=[]
H2O_vmr_new1=[]
level=range(1,91)
row=range(0,6)
for j in lat:
    if j in ten:
        print("j in ten: ", end="")
        print(j)
    elif j in nine:
      print("j in nine: ", end="")
      print(j)

The result for the above is:

j in ten: 1
j in nine: 3
j in nine: 6
j in ten: 7
j in ten: 8
j in nine: 9
j in ten: 10
Community
  • 1
  • 1
almost a beginner
  • 1,494
  • 1
  • 15
  • 37