Procedures

CT03c

  • Define the term 'procedure'

  • Define the term 'parameter'

  • Create procedures.

Repeating ourselves

CT03c

Previously you have learned that you can use loops to repeat blocks of code as many times as you need.

But what happens if you have code you want to re-use multiple times, but not immediately? 

What if you want to have the same code work on different input lists, but don’t want to rewrite the code or debug it again?

What if you need to carry out some operation at the start of a program and then again much later? A loop would not be useful to us here.

Procedures

CT03c

To solve these problems you can use a programming structure known as a procedure.

Procedures are blocks of code defined separately from the main program. They can be used as many times as you like. 

These blocks of code carry out an action of some description. They usually use input parameters.

You’ve already used procedures in your code without knowing it.

Print

CT03c

One of the earliest things you learned to do in Python was display values on the screen using print().

print() is an example of a procedure.

The code that makes print work is hidden, but there is code being run by the computer to get the procedure to work.

You give print() some input in the form of parameters. The text and/or variables you type into the brackets are inputs for the print procedure.

Other examples

CT03c

You’ve used a few different procedures throughout your programming so far:

list.append(), list.remove(), del 

If you look at help documents online, you will see that these procedures are defined like this:

These definitions tell programmers how to interact with the procedures. The identifiers between the <> are supplied by the programmer. 

<list>.append(<item>)
<list>.remove(<item>)
del <list>(<item>)

Procedures carry out an action but do not return any value.

User-defined procedures

CT03c

You can also define our own procedures in code.

A key point to remember here is that a procedure definition should occur before the main program.

Example: creating a procedure

CT03c

You need to create a procedure that prints out a menu for a larger program.

You should use comments to divide up the sections for maintainability.

# ---------------------------
# Subprograms
# ---------------------------
def showMenu():
  print ("Option 1")
  print ("Option 2")
  print ("Option 3")

def is the keyword to create a procedure.

You should give your procedure a meaningful name.

Code inside the procedure is indented. The procedure finishes at the next outdented line.

This procedure does not take input parameters which is why the brackets are empty.

You must have a set of brackets and a colon here.

Example: creating a procedure with input

CT03c

You need to create a procedure that prints out a menu for a larger program.

The comments have been used to show that this is where the subprograms are defined.

# -----------------------------
# Subprograms
# -----------------------------
def printList(listToPrint):
    for item in listToPrint:
        print(item)

Again def is used and the procedure given a meaningful name.

This time an input parameter has been used.

This means that an item will be passed into the procedure so that something is done with it.

The value that has been passed into the procedure is being used here.

As you'll see on the next slide you can choose the parameter identifier. It does not have to match the name of the value passed into it.

Example: using your procedure

CT03c

Using a procedure is known as calling it.

You call your procedures in the main part of your code, after the subprograms have all been defined

The values being passed into the procedure are known as an argument.

# -----------------------------
# Sub Programs
# -----------------------------
def printList(listToPrint):
  for item in ListToPrint:
    print(item)

# -----------------------------
# Main program
# -----------------------------
minutes = [15, 23, 12, 7, 18]
printList(minutes)

Procedure is defined above the main program

Calling the procedure by writing the name of it.

Comments used to separate subprograms from the main code.

The argument does not have the same name as the input parameter, i.e. minutes is different to listToPrint.

Activity 1 

All the data structures in the following program are correct, but the lines of code labelled as such are mixed up.

When correctly written, the program calls a procedure twice using different data structures each time. The procedure prints the count of lines and every item in the list.

Put all the code lines in the right order and in the right places. Make sure that the relevant part of the code is defined as a subprogram and that it is called twice.

# =====> All of these lines are jumbled up
print (item)
def printAnyList (pList):
printAnyList (caravans)
for item in pList:
print ("This input list has " + str (len (pList)) + " items.")
printAnyList (names)

# ------------------------------------------------------------
# Global variables
# ------------------------------------------------------------
caravans = ["Excellent", "Premium", "Prestige", "Nova", "Eco",
            "Evolution", "Tourer"]
names =["Livinitup", "Waltzing Matilda", "Home Sweet Home",
        "Seldom Inn", "Seeyoulater", "The Long Haul",
        "Happycampers", "On Tour", "Home & Away"]

# ------------------------------------------------------------
# Subprograms
# ------------------------------------------------------------

# ------------------------------------------------------------
# Main program
# ------------------------------------------------------------

Activity 1 

When correctly written, the program calls a procedure twice using different data structures each time. The procedure prints the count of lines and every item in the list.

# Global variables -------------------------------------------
caravans = ["Excellent", "Premium", "Prestige", "Nova", "Eco",
            "Evolution", "Tourer"]
names =["Livinitup", "Waltzing Matilda", "Home Sweet Home",
        "Seldom Inn", "Seeyoulater", "The Long Haul",
        "Happycampers", "On Tour", "Home & Away"]

# Subprograms ------------------------------------------------

def printAnyList (pList):
    for item in pList:
        print (item)
    print ("This input list has " + str (len (pList)) + " items.")

# Main program------------------------------------------------
printAnyList (names)
printAnyList (caravans)

Arguments? subprograms?

CT03c

A subprogram is any code block that is defined outside the main program and which can be reused. Procedures are just one kind of subprogram. Functions are another kind of subprogram. You will look at them next lesson.

So far, items in brackets have been labelled as parameters, but:

  • When you define a subprogram the items in the brackets are known as parameters.
  • When you call a subprogram the values that are passed into the subprogram using the brackets are known as arguments.

Activity 2 

  1. Load ‘Act2_Student’ into your programming environment. Amend the code to:
    • Add a definition for a subprogram named ‘shortVegetable’, including two input parameters. The names of the input parameters can be determined by reading the body of the subprogram.
    • Add a call to the subprogram, passing in the correct arguments.
    • Debug your code until you have the program working correctly. 
  2. Predict what you think will happen if you swap the order of the arguments in the subprogram call? 
  3. Modify the code to swap the order of the arguments in the subprogram call. Run the code. Did it behave as you predicted? Why? Why not?

Activity 2 

  1. Load ‘Act2_Student’ into your programming environment.
# ------------------------------------------------------------
# Global variables
# ------------------------------------------------------------
theNumber = 0                   # Invalid input
theVegetable = ""               # Empty string

# ------------------------------------------------------------
# Subprograms
# ------------------------------------------------------------
# =====> Write the definition of the subprogram here
def shortVegetable (pVeg, pNum):

    if (len(pVeg) >= pNum):
        print (pVeg[0:pNum])
    else:
        print ("Number is longer than vegetable")

# ------------------------------------------------------------
# Main program
# ------------------------------------------------------------

theNumber = int(input ("Enter your favourite number, less than 10 (0 to exit): "))
while (theNumber != 0):
    theVegetable = input ("Enter your favourite vegetable: ")

    # =====> Add a call to the subprogram, including passing arguments
    shortVegetable(theVegetable, theNumber)

    theNumber = int(input("Enter your favourite number, less than 10 (0 to exit): "))

Review

CT03c

  • Define the term 'procedure’.
    • A block of code defined before the main program that can be reused many times.
  • Procedures carry out an action and do not return a value.
  • Define the term 'parameter’.
    • A value that is passed into a procedure (input).
  • Create procedures.
    • The def keyword is used to create procedures.

ct03c Procedures

By David James

ct03c Procedures

  • 399