Leo
Leo

Reputation: 123

If statement with negative condition

I want to prepare my data for a histogram. My data (in the following code described with D) contains values between [-200,1000] and with an if statement I want to allocate them to bins of the range [0,20]. My code looks like this:

for t in range(0,731):
     if(D[t]<(-130)):
        xbin[t]=0
     if(D[t]>=(-130) and D[t]<=(-120)):
        xbin[t]=1
     if(D[t]>=(-120) and D[t]<=(-110)):
        xbin[t]=2
     if(D[t]>=(-110) and D[t]<=(-100)):
        xbin[t]=3
     if(D[t]>=(-100) and D[t]<=(-50)):
        xbin[t]=4
     if(D[t]>=(-50) and D[t]<=0):
        xbin[t]=5
     if(D[t]>=0 and D[t]<=50):
        xbin[t]=6

and so on. But it seems as the program does not understand the negative condition in the if statement. So it allocate all values <0 to xbin=6 doesn't matter if the value is < -120, < -130 or something else. How can I fix this? Thank you!

Upvotes: 0

Views: 3209

Answers (1)

Kasravnd
Kasravnd

Reputation: 107297

Python understands the negative comparison. The problem is with your conditions that some of then conflict to each other. For refusing that problem you need to use elif rather than multiple if which makes it check all the conditions. Also you don't need to explicitly write and between your conditions, python will chain the them automatically and they have same precedence.

for t in range(0,731):
     if D[t] < -130 :
        xbin[t]=0
     elif -110 <= D[t]<= -120:
        xbin[t]=1
     elif -120 <= D[t] <= -110:
        xbin[t]=2
     elif -110 <= D[t] <= -100:
        xbin[t]=3
     elif -100 <= D[t] <= -50:
        xbin[t]=4
     elif -50 <= D[t] <= 0:
        xbin[t]=5
     elif 0 <= D[t]<= 50:
        xbin[t]=6

Upvotes: 0

Related Questions