Reputation: 19
I am doing a lambda school python pre-course and in the first assignment, I have to calculate a person's BMI. Well, I declared w
and h
for the weight and height of the individual and set them to some value. Then I declared
w=78
h =1.82
BMI = w/h**2
print(BMI)
Everything was fine up to this point. But the next point asks to calculate the BMI without creating the variables again, just changing their values.
I did this
h = 1.63
w = 59
print(BMI)
Does anyone know why python rescues the stored value of BMI instead of reevaluating it since I defined it as an operation?
Upvotes: 0
Views: 255
Reputation: 29600
As already explained in the other answer, BMI
is a variable and it does not get re-evaluated when you change the values originally used to set its value. The simplest solution here would be to put the BMI computation into a function, then just call that function every time w
and h
is updated.
But, if you want to make it look like the BMI value is "automatically calculated" after updating weight and height, you could also put them all in a class and then use properties to store the weight, height, and BMI values.
class Health():
def __init__(self):
self._w = 1 # set defaults
self._h = 1 # set defaults
@property
def weight(self):
return self._w
@weight.setter
def weight(self, value):
self._w = value
@property
def height(self):
return self._h
@height.setter
def height(self, value):
self._h = value
@property
def bmi(self):
return self._w / self._h ** 2
Then, use the class like this:
myhealth = Health()
myhealth.weight = 78
myhealth.height = 1.82
print(myhealth.bmi)
myhealth.weight = 59
myhealth.height = 1.63
print(myhealth.bmi)
Which outputs something like this:
23.54788069073783
22.20633068613798
This is an overkill solution over using a simple function.
I am quite not sure why you asked is there a way without using functions?
(Though, this solution still uses functions.)
For more information on properties:
property()
Upvotes: 1
Reputation: 399833
If you did
BMI = w / h**2
then that is an expression, which is immediately evaluated and the result is assigned the name BMI
. The relationship is not stored, the resulting value is.
It is quite confusing what you were supposed to achieve, perhaps using a function? That would look like:
def compute_bmi(w, h):
return w / h ** 2
and you would use it like so:
>>> print(compute_bmi(80, 1.80))
24.691358024691358
Upvotes: 2