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: