How to Develop a Simple Python Program
Last Revision: July, 2010
( McCann )

Students always seem to have trouble understanding (or maybe just doing) what I expect of them when I assign a program. I make the requirements as straight-forward as I can; meeting those requirements is mostly a matter of allowing yourself plenty of time to get everything done.

To help you understand what's expected of you, in this document I'll take a simple sample programming assignment and guide you through the major steps in the program development process.

(If you are looking for details on program documentation, you will find some here but you really should visit my Programming Style page, which has my collection of style documents, including a few style pages from other people. Most of it is developed with experienced programmers in mind. This document is meant for students who are just starting to learn Python.)


Step #1: Start Early
Programming is not an activity that can be reliably scheduled to take a predetermined amount of time. Even programs that look like they should be doable in 2 hours will often take 4 or 5 hours to complete. The best thing you can do for yourself is say, "I have no idea how long this will take; I'd better get started right away."

Step #2: Read the Assignment Handout Carefully
My programming assignment handouts tend to be very detailed, if not perfectly organized. Everything that I expect from you is given in there somewhere, so read it carefully and highlight the key points so that you don't overlook any of them.

For example, let's consider this example assignment:



ISTA 130 -- Computational Thinking and Doing

(McCann)

Demo Program: Calories Due to Fat

Due Date: Smarch 32nd, 2048, before 8:00 p.m.

Overview: Any dietician will tell you that limiting your daily fat intake to be under 30% of your total calories is a good idea. But how many of the calories in your favorite foods are from fat? Nutrition labels will tell you how many grams of fat are in a serving, and how many total calories are in that serving, but you need to do the rest of the figuring on your own.

As it happens, a gram of fat has about 9 calories. Therefore, if you take the grams of fat in a serving of a particular food, multiply it by 9 and divide by the total calories in the serving, you'll get the fraction of the calories due to fat. To get the result as a percentage, just multiply by 100.

For example, consider a product that has 3 grams of fat and 170 calories per serving. There are 27 calories due to fat (3 * 9), and 27 / 170 = 0.159. Multiplying by 100 gives the final answer: 15.9 percent of the calories are due to fat.

Assignment: Write a complete, well-documented Python program that begins by asking the user to enter the grams of fat and the calories in a serving of a food product. The program will compute the percentage of the food's calories that are due to fat, and will display the input information and the percentage in the form of a complete English sentence.

Data: Here are some examples of typical input that your program is expected to handle:

      Fat (grams)     Total Calories
      -----------     --------------
           1                60
          21               480

Output: Your program's output is to appear on the screen as follows (using the second food item from above as input):

      This program will tell you what percentage of the calories
      in a serving of a food are from the food's fat content.

      How many grams of fat are in one serving?  21
      How many total calories are in one serving?  480

      A food with 21 grams of fat and 480 calories per serving
      has 39.4% of those calories from fat.

Turn In: On the due date, electronically submit your documented Python program.





This is pretty typical of my program handouts. Things to notice: In this case, you need to write a program that gets two pieces of input, computes a percentage, and outputs all three pieces of information. This is obviously very simple, and the first program or two of the semester will be about as simple as this one. After that, they'll get more complex, so that you can start using more features of the language.

Step #3: Write the `External' Documentation
I can already hear the smirking ("Write comments now? Get serious!") but I am serious: You should write your documentation as you write the program, not afterwards. In particular, the External Documentation should be almost complete before you write even a line of code.

(Aside: The block of comments at the top of a program is still often called `external' documentation, even though it's inside the program file, because it contains information that is also included in documents that describe the design of very large programs, documents that are separate from the code.)

I hand out a documentation summary page to my upper-division CS students that lists the information that I expect to see in larger programs. For an introductory programming class, I expect just these basics in external documentation:
  1. Your name, the course name/number/semester, your section leader's name, the assignment number/name, and assignment due date.
  2. The program's operational requirements: Which version of the language you used, and instructions on how to run the program.
  3. A one-paragraph description of the problem the program was written to solve.
  4. A list of any requirements of the assignment that you were not able to include, and/or information about bugs that are still known to exist.
To help you, I've created a template that you can import into your program that contains a label for each section that I want to see. All you have to do is fill in the blanks; I can't make it much easier than that. Cutting and pasting the template into your program not only saves a lot of typing, but it helps you remember to provide all of the requested information.

Here's the external documentation template:

    ##########################################################################
    #   Author:  [Your name and email address here! (w/o the brackets, please)]
    #    Class:  ISTA 130, Fall 2010
    #       SL:  [Your SL's name here]
    #
    #  Program:  [Assignment # and Name]
    # Due Date:  [Assignment Due Date and Time]
    #
    # Language:  Python 3
    #   To Run:  [Execution Instructions]
    #
    # Purpose:  [A one-paragraph description of what the program does.]
    #
    #  "Bugs":  [A list of remaining problems/omissions, or "None"]
    ##########################################################################

Note that I've included some brief comments with each label, to let you know what you need to add. Because deleting all of those comments is a pain, here's a comment-free version

    ##########################################################################
    #   Author:  
    #    Class:  ISTA 130, Fall 2010
    #       SL:  
    #
    #  Program:  
    # Due Date:  
    #
    # Language:  Python 3
    #   To Run:  
    #
    # Purpose:  
    #
    #  "Bugs":  
    ##########################################################################

You should be able to fill out all of this template except for the last section before you write the program. Here's what it might look like for our example assignment:

    ##########################################################################
    #   Author:  Keyser Soze (keyser@onestepahead.net)
    #    Class:  ISTA 130, Fall 2010
    #       SL:  A. Elpful Ooondergrod
    #
    #  Program:  #-1 (Calories from Fat)
    # Due Date:  Smarch 32nd, 2048 before 8:00 p.m.
    #
    # Language:  Python 3
    #   To Run:  python3 calories.py
    #
    # Purpose:  This program determines what percentage of the calories
    #           in a food product are due to the food's fat content, given
    #           a food item's number of grams of fat and total calories.
    #
    #  "Bugs":  
    ##########################################################################

Please understand that this amount of documentation is very minimal in the grand scheme of program commenting. As programs get more complicated, the quantity and quality of documentation both increase. Keep in mind that documentation should help the reader make sense of the program, not raise more questions than it answers.

By the way, you should never just refer the reader to the program assignment handout. Why not? First, the documentation is part of the program code; the handout isn't. Second, when you program in the 'real world', your boss is not going to go around giving you assignment handouts. Now's the time to get in the habit of including good, informative documentation for all programs you write.

Naturally, the programmer will need to revisit the documentation after the program is complete, to verify that all of the information is still correct (and to fill in the "Bugs" section). If you do a good job of planning the details of the program in advance, you won't have to change much, if any, documentation.

Step #4: Outline Your Program with Comments
When you were taught how to write research papers in grade school, you were almost certainly taught to create an outline first. This is also good advice for writing computer programs.

The outline for this program is straight-forward:
  1. Display instructions for the user
  2. Accept fat grams and calories from the user
  3. Compute the percentage of calories due to fat
  4. Echo the input data and display the percentage of calories due to fat

If you're just starting to learn to program, you could do far worse than to write a comment for each step of your outline. Later, you can write the code to accomplish those steps. Here's the program with the outline added:
    ##########################################################################
    #   Author:  Lester I. McCann
    #    Class:  ISTA 130, Fall 2010
    #       SL:  A. Elpful Ooondergrod
    #
    #  Program:  #-1 (Calories from Fat)
    # Due Date:  Smarch 32nd, 2048, before 8:00 p.m.
    #
    # Language:  Python 3
    #   To Run:  python3 calories.py
    #
    # Purpose:  This program determines what percentage of the calories
    #           in a food product are due to the food's fat content, given
    #           a food item's number of grams of fat and total calories.
    #
    #  "Bugs":
    ##########################################################################

    def main():

            # Display instructions for the user

            # Accept fat grams and calories from the user

            # Compute the percentage of calories due to fat

            # Echo the input data and display the percentage of calories due to fat

    if __name__ == "__main__": main()

(I've also added two other lines; if you don't already recognize them, don't worry about it. Just focus on the development process.)

Step #5: Write the Program a Piece at a Time
Students like to try to write their programs all at once, in a single coding marathon in front of the computer. You might be able to get away with this on small programs, but as the amount of code increases, the way to avoid long late-night debugging sessions is to write one section of code at a time, and test each section as you write it.

For example, in our program we know that we need to read two pieces of data and output three, with some calculations in-between. Forget about the calculations for the moment, and just try to deal with the input and output. Your program might look like this: (In the interest of saving space, I didn't reproduce the external documentation.)

    def main():

            # Display instructions for the user

            # Accept fat grams and calories from the user

        fat_grams = eval(input("How many grams of fat are in one serving? "))
        total_calories = eval(input("How many total calories are in one serving? "))

            # Compute the percentage of calories due to fat

            # Echo the input data and display the percentage of calories due to fat

        print(fat_grams, total_calories)

    if __name__ == "__main__": main()

Even though this program doesn't really do anything useful yet, it has enough content that you can run it and be convinced that the program is able to successfully read and write the data. It doesn't make much sense to write the percentage calculations until we know that the calculations will have the correct values to work with. By including a simple output statement, we can see that the values are being read correctly.

If you were to execute this program from a terminal window, here's what you'd see if you entered 1 and 2 as the inputs:

    $ python3 calories.py
    How many grams of fat are in one serving? 1
    How many total calories are in one serving? 2
    1 2
The input messages look good already, but of course the output still needs to be improved. All in due time!

Next, we can add the calculations:

    def main():

            # Display instructions for the user

            # Accept fat grams and calories from the user

        fat_grams = eval(input("How many grams of fat are in one serving? "))
        total_calories = eval(input("How many total calories are in one serving? "))

            # Compute the percentage of calories due to fat

        calories_from_fat = fat_grams * 9
        percent_calories_from_fat = 100 * calories_from_fat / total_calories

            # Echo the input data and display the percentage of calories due to fat

        print(fat_grams, total_calories, percent_calories_from_fat)

    if __name__ == "__main__": main()

In addition to adding the calculations, we added the percentage of calories due to fat to the print statement. Doing so allows us to test the calculations to ensure that they are working correctly. Remember the example calculation given in the assignment handout? It makes for a good test case:

    $ python3 cal.py
    How many grams of fat are in one serving? 3
    How many total calories are in one serving? 170
    3 170 15.8823529412

The output is still minimal, but the answer appears to be correct. Nice!

Continuing in this one-step-at-a-time manner, we can complete the program. What remains to be done? We need to add the rest of the code, add words to the output (so that the user can make sense of the numbers), test the program to verify that it is working correctly, and complete the external documentation. Here's what the completed program might look like:

    ##########################################################################
    #   Author:  Lester I. McCann
    #    Class:  ISTA 130, Fall 2010
    #       SL:  A. Elpful Ooondergrod
    #
    #  Program:  #-1 (Calories from Fat)
    # Due Date:  Smarch 32nd, 2048, before 8:00 p.m.
    #
    # Language:  Python 3
    #   To Run:  python3 calories.py
    #
    # Purpose:  This program determines what percentage of the calories
    #           in a food product are due to the food's fat content, given
    #           a food item's number of grams of fat and total calories.
    #
    #  "Bugs":  None; this program meets the assignment requirements.
    ##########################################################################

    CALORIES_PER_GRAM = 9     # There are roughly nine calories per gram of fat

    def main():

            # Display instructions for the user

        print()
        print("This program will tell you what percentage of the calories\n"+
              "in a serving of a food are from the food's fat content.")
        print()

            # Accept fat grams and calories from the user

        fat_grams = eval(input("How many grams of fat are in one serving? "))
        total_calories = eval(input("How many total calories are in one serving? "))

            # Compute the percentage of calories due to fat

        calories_from_fat = fat_grams * CALORIES_PER_GRAM

        percent_calories_from_fat = 100 * calories_from_fat / total_calories

            # Echo the input data and display the percentage of calories due to fat

        if fat_grams == 1:
            print("\nA food with %d gram of fat " % fat_grams, end="")
        else:
            print("\nA food with %d grams of fat " % fat_grams, end="")

        if total_calories == 1:
            print("and %d calorie per serving" % total_calories)
        else:
            print("and %d calories per serving" % total_calories)

        print("has %.1f%% of those calories from fat." % percent_calories_from_fat)

        # main()


    if __name__ == "__main__": main()

Speaking of extras, in this program I decided that it would be nice if the output wording matched the values the user entered. The IF-ELSE statements will make the words match the quantity; for example, the program will print "1 gram" instead of "1 grams". This step wasn't required by the assignment, but it does make for a more polished final program.

Here's what the user will see when s/he runs it:

    $ python3 calories.py

    This program will tell you what percentage of the calories
    in a serving of a food are from the food's fat content.

    How many grams of fat are in one serving? 3
    How many total calories are in one serving? 170

    A food with 3 grams of fat and 170 calories per serving
    has 15.9% of those calories from fat.


Step #6: Double-Check Your Work
Your section leader doesn't like deducting points from student programs. Much of the time, those points could have been saved if the student had taken just a little extra time to double-check that his/her program was really complete. When you think that you are done, try running through this little check-list:
  1. Have I reread the assignment handout to make sure that I saw all of the requirements?
  2. Does my program meet all of the requirements?
  3. Is my documentation complete? (Did I finish the external documentation? Are my variable names meaningful? Did I use white space effectively? Etc.)
  4. Did I test my program thoroughly, on a wide variety of test cases?
  5. Did I check the results of the test cases by hand to ensure that the program's logic is correct?
  6. Did I submit my program according to the assignment directions?
If you can (honestly!) answer 'yes' to all of these, then you are probably done. Congratulations!



Want to learn more about good programming style? Please visit my Programming Style Documents page for pointers to additional documents about programming style.

Do you have a comment on this page? I'd like to hear it; you can email me at mccannl@acm.org.