blockOfWood

Structured programming

reusing blocks of code


Structured programming

modularising code

A very common way to design computer programs is to define modules of code to process data.

Here is a module defined in Python which displays a greeting:

def displayGreeting():

print("Hello")

print("How are you?")

In our computer program, we can call the module when we need to use it:

def displayGreeting():

print("Hello")

print("How are you?")

 

#call the module

displayGreeting()

 

We could call the module as many times as we need to:

def displayGreeting():

print("Hello")

print("How are you?")

 

#call the module many times

displayGreeting()

displayGreeting()

displayGreeting()

displayGreeting()

Note: this is the same as this

What if we wanted to change the greeting? In both versions of the code, which approach makes the change easier, modular or non-modular?

Let's imagine that a computer program passes the module some information to process:

def displayMessage(name):

msg1 = "Hello, "+name

msg2 = "How are you today, "+name

print(msg1)

print(msg2)

Now, when we call the module, we need to make sure we send it some data to process:

#call the module and pass it some data to process

displayMessage("Jack")

displayMessage("Jill")

displayMessage("Joe")

displayMessage("Jane")

STOP!!!!

If you are not sure what is going on, open your IDE and type in this program and the module definition. See what happens!

So, modules can be called in a computer progam. They do stuff like process data.

Interestingly, a module can return data back to the computer progam that called it:

Here is a module which accepts some data, a STRING, and returns the first letter of the STRING.

def getFirstLetter(word):

firstLetter = word[0]

return firstLetter

myLovelyWord = input("Please enter a lovely word")

while myLovelyWord != "end":

#Call the module and send it a STRING. Assign the returned value to a variable

f = getFirstLetter(myLovelyWord)

print("The first letter of your lovely word is ", f)

myLovelyWord = input("Please enter a lovely word")

In Structured Programming, we will study two kinds of modules:

  • functions - these are modules which always return data to the calling program.
  • procedures - these are modules which don't return anything.

Tags

module function return parameter identifier pseudocode data type


Feelings

How do you feel right now?

Code sample