Section 2.8 Planning a Program
If you were going to build a cabinet, you wouldn’t buy some pieces of wood and nails and start hammering them together. You’d start by planning: What are the cabinet’s dimensions? How many shelves should it have? How far from the top and bottom should the hinges for the cabinet doors go? Only after you made those decisions would you start building the cabinet.
In the same way, when you are writing a program to solve a problem, you don’t want to sit down at the keyboard and start hammering away at it. Instead, you want to have a step-by-step plan for solvng the problem first; then you can start to program.
Here’s the problem we want to solve: Back in
Section 2.7 we found out how many hours are in 645 minutes by evaluating
645 // 60
. We will write a similar, but slightly more complicated program: find out how many hours, minutes, and seconds are in 7468 seconds.
A good way to start a plan for this is to figure out how we would solve this problem by hand, without a computer. There are 3600 seconds in an hour, so if we took 7468 and divided it by 3600, the quotient would tell us how many hours there were, and the remainder would be the remaining seconds.
That takes care of the hours. Now we need to take the remaining seconds and split it into minutes and seconds. If we divide by 60, the quotient gives us the minutes, and the remainder gives the “final” number of seconds.
Checkpoint 2.8.1.
Here are the steps, written down one after the other in half-English, half-Python. We call this pseudo-code. The steps aren’t in the right order, however. Your job is to put them in the correct order:
Set total_seconds to 7468.
---
Set hours to the quotient of total_seconds divided by 3600.
---
Set seconds_remaining to the remainder of seconds divided by 3600.
---
Set minutes to the quotient of seconds_remaining divided by 60.
---
Set final_seconds to the remainder of seconds_remaining divided by 60.
---
Print hours, minutes, and final_seconds, properly labeled.
Now that you have a plan, see if you can translate the pseudo-code into Python:
Here’s the codelens for the calculations (but don’t peek at it unless you are really totally stuck).