Redhwan
Redhwan

Reputation: 967

How to run for loop with float-number in range

I tried running my long code but the idea in these short lines.

My issue needs two conditions. The first one which i is within range. The second one uses all values in the list

m = [181.452, 147.0213, 480.33, 1000.05]
for i in m:
    if i in range(0 , 200):
        print ('Red')
    if i in range(201 , 500):
        print ('white')
    if i in range(501 , 1000):
        print ('green')
    if i in range(1000 , 1500):
        print ('blue')

you can see when values in list int:

m = [181, 147.0213, 480.33, 1000.05]
for i in m:
    if i in range(0 , 200):
        print ('Red')
    if i in range(201 , 500):
        print ('white')
    if i in range(501 , 1000):
        print ('green')
    if i in range(1000 , 1500):
        print ('blue')

output to second code: Red

Upvotes: 0

Views: 252

Answers (1)

Kamal Nayan
Kamal Nayan

Reputation: 1940

You are using range() which returns an iterator of int values, so your code is not working. It means if you have written

if i in range(0,5)

then it will translate to:

if i in (0, 1, 2, 3, 4)

So your float values didn't got captured here. Also it's not a good practice to use iterator for comparison, when you have comparison operators.

Use below code:

m = [181.452, 147.0213, 480.33, 1000.05]

for i in m:
    if 0 <= i <= 200:     # this is pythonic way to write "if i >= 0 and i <= 200"
        print('Red')
    elif 200 < i <= 500:
        print ('white')
    elif 500 < i <= 1000:
        print ('green')
    elif 1000 < i <= 1500:
        print ('blue')

Output:

Red
Red
white
blue

Upvotes: 1

Related Questions