Книга: Practical Programming, Fourth Edition
Назад: Nested if Statements
Дальше: You Learned About Booleans: True or Fa lse?

Memorizing 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):

Age<45

Age45

BMI<22

Low

Medium

BMI22

Medium

High

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, you 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'

You 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.

Назад: Nested if Statements
Дальше: You Learned About Booleans: True or Fa lse?