Decomposition: the actual job
Nobody can write a big program in one go. Engineers practice decomposition: splitting a problem into steps so small that each one is obviously codeable.
Take "compute the average of three test scores typed by a user". Decomposed:
- Read the first score and convert it to a number (lessons 1-3 and 2-3)
- Same for the second and third
- Add the three, divide by 3 (lesson 2-2), store it in a well-named variable (unit 3)
- Print the result
Every step is something you already know how to write. That is the feeling to chase: decompose until each piece is boring.
first = int(input()) second = int(input()) third = int(input()) average = (first + second + third) / 3 print(average)
Note the parentheses forcing the addition before the division, exactly the precedence rule from lesson 2-2.
Code exercise · python
The Input box holds three scores on three lines: 10, 20, 30. Run the decomposed program. (Dividing with / gives a float, hence 20.0.)
Quiz
You are asked to build "a program that quizzes the user with 10 math questions and reports a score". What is the best FIRST move?
Code exercise · python
Your turn. The Input box has two numbers: 8 then 3. Decompose and write: read both numbers, then print their sum on the first line and their difference (first minus second) on the second line.
Code exercise · python
One more decomposition rep. The Input box holds a restaurant bill (50) and a tip percent (20) on two lines. Read both, compute the tip (bill times percent divided by 100), then print the tip on the first line and the bill-plus-tip total on the second. Expected: 10.0 then 60.0.