Compound If Statements Using AND & OR

In the previous chapter, there was a situation where two if statements could both be true at the same time. We can make compound conditions with and or or to prevent this.

Both parts of an and condition must be true. Either part of an or condition must be true.

human-age-with-ands.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from __future__ import print_function
input = raw_input

age = float(input("How old is the human? "))
term = 'unknown'

if age < 0 or age > 150:
    print("That's unlikely.")
    term = 'improbable'

if age >= 0 and age < 1:
    term = 'baby'
if age >= 1 and age < 3:
    term = 'toddler'
if age >= 3 and age < 5:
    term = 'preschooler'
if age >= 5 and age < 9:
    term = 'child'
if age >= 9 and age < 13:
    term = 'preteen'
if age >= 13 and age < 18:
    term = 'teen'
if age >= 18 and age < 40:
    term = 'young adult'
if age >= 40 and age < 65:
    term = 'adult'
if age >= 65:
    term = 'elderly'

if term == 'unknown':
    print("You did something wrong, but I'm not sure what.")
if term != 'unknown':
    print("A human {} years old is usually called '{}'.".format(age, term))

What You Should See

How old is the human? 42
A human 42.0 years old is usually called 'adult'.

The output will depend on what you type, of course.

If they type a negative number for the age or something very old, we will complain about it.

Then if the age is at least zero but less than one, we set the variable term to the string "baby".

If the age is at least one but less than three, we set it to "toddler". And so on.

Study Drills

  1. Add another if statement in there somewhere. And make sure the if statement after the one you added gets changed, too. Test your program with ages near the range that you chose to make sure everything works correctly.



©2017 Graham Mitchell