Writing a Program

Introduction

In this course, we have covered a good amount of theory and programming knowledge to give you a foundation on which to continue developing. We will be ending this course by bringing together everything we have covered into writing a well structured program.


Comments

Before we consider writing our Python project, let us quickly discuss a very important part to writing code: Commenting. Commenting is the inclusion of human readable, non-executable statements within the source code of a program so as to improve the readability of the code.

Comments are useful to provide more structure to your code, to help you better plan out your code, help others to see what you are trying to achieve in your code, and to remind you of what you were doing when you look back at your code later on.

To add comments in Python, you simply have to prefix the comment with a hash character "#". For example:

# This is a comment
x = 2 # This is also a comment

As you can see from the above example, a comment can be placed on the same line as a statement. Anything following the hash symbol will be ignored by the Python interpreter when processing your code.


Sample Program

To pull everything together, we are going to write a sample program. For inspiration of what program to write, we are going to consider the first problem in the Project Euler problem set.

The problem statement is this:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

Rather than find the answer to this specific question, we are going to generalize the problem into a function which can be used to find the answer to similar problems. We will then ask the user for some input to define the parameters of the problem, then we will calculate the answer and display it.

Let's call our generalized function sum_of_multiples(), and we will define the following input parameters:

  1. Upper Limit: An integer which determines the number below which we need to add up the multiples defined by the next parameter. In the original problem statement, this value is 10.
  2. Multiples: An array of multiples to use for the addition.

So, the definition of the function in Python will look like

def sum_of_multiples(upper_limit, multiples):
    # The code will go here

We will also want to generalize another function to determine if a number is a multiple of any of the values in the multiples array. We can do this by cycling through all the multiples and if any of them factor into the number we are considering, we return true. So this function will look like this:

def is_multiple(number, multiples):
    for factor in multiples:
        if number % factor == 0:
            return True
    return False

Now, we also want some code to read in the various numbers from the user via the keyboard. For this, let's also define a generic function we can use for retrieving numbers from the user via the keyboard.

def get_number(question):
    is_number = False
    number = 0
    while (not is_number):
        input = raw_input(question)
        try:
            number = int(input)
            is_number = True
        catch:
            print "That was not a number. Please try again."
            is_number = False
    return number

This function will keep on asking the user for a number until they enter in a value which can be interpreted as a number.

Next, let us consider how to perform the addition of numbers which are below the upper_limit and which are factors of the items in the multiples array.

def sum_of_multiples(upper_limit, multiples):
    total = 0
    for i in range(1, upper_limit):
        if is_multiple(i, multiples):
            total = total + i
    return total

Well, that was easy. We loop from 1 up to the upper_limit, and if the specific number we are considering per loop iteration is a factor of any of the multiples, we add it to the total. Finally, we return the total value we have added up.

Ok, let's put it all together.

def get_number(question):
    # Initialize is_number, which stores the answer, and number which is the integer value
    is_number = False
    number = 0

    # Keep asking for a number until a number is entered
    while (not is_number):
        input = raw_input(question)

        # Attempt to convert it to a number, if this fails, ask the user again
        try:
            number = int(input)
            is_number = True
        except:
            print "That was not a number. Please try again."
            is_number = False

    # Return the integer value entered by the user
    return number

def is_multiple(number, multiples):
    # Loop through the multiples and check for a factor
    for factor in multiples:
        if number % factor == 0:
            return True

    # If no factor is found, return false
    return False

def sum_of_multiples(upper_limit, multiples):
    # Initialize the total variable which will store the sum
    total = 0

    # Loop from 1 until upper limit
    for i in range(1, upper_limit):
        # If this number is a factor of the multiples, add it to the total
        if is_multiple(i, multiples):
            total = total + i

    # Return the total sum
    return total

def main():
    # Get User Input
    upper_limit = get_number("Please enter the upper limit: ")
    num_multiples = get_number("How many multiples would you like to check for? ")
    multiples = []
    for i in range(0, num_multiples):
        multiples.append(get_number("Multiple %d: " % (i)))

    # Perform Calculation and Display Answer
    total = sum_of_multiples(upper_limit, multiples)
    print "The sum of the multiples under %d is %d" % (upper_limit, total)

if __name__ == '__main__':
    main()

Exercise

  1. Give the second problem from Project Euler a try, with the same approach of taking the problem, and writing a generic function (or set of functions as we have done above) to solve a class of similar problems, not just the specific problem asked in the problem instructions.

Now what?

If you were able to follow along up until this point, well done, you are well on your way to being a proficient programmer. This course has focused on the theoretical aspects of programming, rather than teaching you the intricacies of the Python programming language. To learn more about Python, I recommend heading over to http://www.learnpython.org .


Comments

comments powered by Disqus