Reputation: 47
I'm trying to write an if
statement that takes a float as a range.
x = 8.2
if x in range(0, 4.4):
print('one')
if x in range(4.5, 8):
print('two')
if x in range(8.1, 9.9):
print('three')
if x > 10:
print('four')
I have also tried this to no avail:
if x > 0 <= 4.4
Upvotes: 2
Views: 2717
Reputation:
For floating points you don't need to use range instead you can use comparisons operators like:
num = 4
if (num > 3.3) print("less than four")
elif (num > 3.7) print("less than four")
elif (num > 3. 9) print("less than four")
else print("Equal to four")
Upvotes: 0
Reputation: 1164
Use
if 0 < x <= 4.4:
where x
is in the middle. It's equivalent to
if 0 < x and x <= 4.4:
range
is not suitable for that task.
Upvotes: 3
Reputation: 47
x = 8.3
if 0 <= x <= 4.4:
print('one')
if 4.5 <= x <= 8:
print('two')
if 8.1 <= x <= 9.9:
print('three')
if x > 10:
print('four')
Upvotes: 1
Reputation: 781068
You don't need range()
. Just use comparisons, and use elif
so that the ranges are exclusive.
if x < 4.5:
print('one')
elif x < 8:
print('two')
elif x < 10:
print('three')
else:
print('four')
This also solves the problem that you had gaps between your ranges.
Upvotes: 4