Reputation: 559
Is there a way to specify bounds for a float variable in Python? For example, when I import data, I would like to either check if it within certain range such that min <= variable <=max
. Further, if possible, I would like assign a specific value to such variable if the imported value is outside of these bounds (or even missing).
I can perhaps do the first part if the variable was a float.
def var_check(x,lower_bound=3,upper_bound=30):
rng = range(lower_bound,upper_bound+1)
if x not in rng:
return (upper_bound-lower_bound)/2
else:
return x
x = var_check(5)
returns 5, while x = var_check(50)
returns 13.
Any ideas on how to do this for a float variable?
Upvotes: 2
Views: 9461
Reputation: 5666
You can define a class and override its __float__
class MyFloat:
def __init__(self, num, upper=20, lower=10):
self.num = num
self.upper = upper
self.lower = lower
def __float__(self):
if self.lower <= self.num <= self.upper:
return float(self.num)
else:
return (self.upper - self.lower) / 2
Then while importing your data you can do
>>> data = [1,2,3,10,11,12,21,22,23]
>>> [float(MyFloat(d)) for d in data]
>>> [5.0, 5.0, 5.0, 10.0, 11.0, 12.0, 5.0, 5.0, 5.0]
Upvotes: 0
Reputation: 1419
A solution could look like this:
def var_check(x, lower_bound=3, upper_bound=30):
if x >= lower_bound and x <= upper_bound:
return x
return (upper_bound-lower_bound)/2
print(var_check(2.5))
print(var_check(15.5))
print(var_check(33.5))
Output
13.5
15.5
13.5
Upvotes: 0
Reputation: 27333
You can do almost exactly what you wrote in your question:
def var_check(x, lower_bound=3, upper_bound=30):
if lower_bound <= x <= upper_bound:
return x
else:
return (upper_bound - lower_bound) / 2
You should do the same with integers, by the way, at least in Python 2. In Python 3 (or with xrange
in Python 2), it doesn't matter so much.
Upvotes: 7