Nested If Statements

Here is a relatively complicated program using if statements inside other if statements.

numberword.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from __future__ import print_function, division
import sys
input = raw_input

n = int(input("Enter a number under a hundred: "))

if n >= 100:
    print("Well, you didn't follow directions.")
    sys.exit(1)

word = ""

if n == 10:
    word += 'ten'
elif n == 11:
    word += 'eleven'
elif n == 12:
    word += 'twelve'
elif n == 13:
    word += 'thirteen'
elif n == 14:
    word += 'fourteen'
elif n == 15:
    word += 'fifteen'
elif n == 16:
    word += 'sixteen'
elif n == 17:
    word += 'seventeen'
elif n == 18:
    word += 'eighteen'
elif n == 19:
    word += 'nineteen'
else:
    ones = n%10
    tens = n//10
    if tens == 2:
        word += "twenty"
    elif tens == 3:
        word += "thirty"
    elif tens == 4:
        word += "fourty"
    elif tens == 5:
        word += "fifty"
    elif tens == 6:
        word += "sixty"
    elif tens == 7:
        word += "seventy"
    elif tens == 8:
        word += "eighty"
    elif tens == 9:
        word += "ninety"

    if tens > 0 and ones > 0:
        word += '-'

    if ones == 1:
        word += 'one'
    elif ones == 2:
        word += 'two'
    elif ones == 3:
        word += 'three'
    elif ones == 4:
        word += 'four'
    elif ones == 5:
        word += 'five'
    elif ones == 6:
        word += 'six'
    elif ones == 7:
        word += 'seven'
    elif ones == 8:
        word += 'eight'
    elif ones == 9:
        word += 'nine'

print("{} -> {}".format(n, word))

What You Should See

Enter a number under a hundred: 21
21 -> twenty-one

Pretty cool, huh? Notice that everything from line 34 through 73 is inside an else.

Also, we import the sys module so that we can call the function sys.exit(). It quits a program immediately. The 1 is an error code, since exiting with a code of 0 usually means that everything is fine.

Study Drills

  1. Add code so that the program will print out the correct word for any number up to 999. This is a little tricky.
Enter a number under a thousand: 321
321 -> three hundred twenty-one

Enter a number under a thousand: 21
21 -> twenty-one

Enter a number under a thousand: 500
500 -> five hundred



©2017 Graham Mitchell