Remembering Results of a Boolean Expression Evaluation

Take a look at the following line of code and guess what value is assigned to x:

 >>>​​ ​​x​​ ​​=​​ ​​15​​ ​​>​​ ​​5

If you said True, you were right: 15 is greater than 5, so the comparison produces True, and since that’s a value like any other, it can be assigned to a variable.

The most common situation in which you would want to do this comes up when translating decision tables into software. For example, suppose you want to calculate someone’s risk of heart disease using the following rules based on age and body mass index (BMI):

images/cond/AgeBMI.png

One way to implement this would be to use nested if statements:

 if​ age < 45:
 if​ bmi < 22.0:
  risk = ​'low'
 else​:
  risk = ​'medium'
 else​:
 if​ bmi < 22.0:
  risk = ​'medium'
 else​:
  risk = ​'high'

The expression bmi < 22.0 is used multiple times. To simplify this code, we can evaluate each of the Boolean expressions once, create variables that refer to the values produced by those expressions, and use those variables multiple times:

 young = age < 45
 slim = bmi < 22.0
 if​ young:
 if​ slim:
  risk = ​'low'
 else​:
  risk = ​'medium'
 else​:
 if​ slim:
  risk = ​'medium'
 else​:
  risk = ​'high'

We could also write this without nesting as follows:

 young = age < 45
 slim = bmi < 22.0
 if​ young ​and​ slim:
  risk = ​'low'
 elif​ young ​and​ ​not​ slim:
  risk = ​'medium'
 elif​ ​not​ young ​and​ slim:
  risk = ​'medium'
 elif​ ​not​ young ​and​ ​not​ slim:
  risk = ​'high'

Whether you use nesting or not, giving meaningful names to the Boolean variables (young and slim) helps make the code easier to understand.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.27.74