KS48525 3.2.10 to 3.2.11 26 min read 10 question quiz 14 exam marks

Subroutines and Structured Programming

Procedures and functions, parameters and return values, local and global scope, and why breaking a program into named pieces is the difference between code you can maintain and code you cannot.

Procedures and functions

A subroutine is a named block of code that can be called from elsewhere in a program. AQA distinguishes two kinds.

A procedure carries out a task and does not return a value.

OCR reference language
SUBROUTINE greet(name)
    OUTPUT 'Hello ' + name
ENDSUBROUTINE

greet('Amira')

A function carries out a calculation and returns a value, which the calling code then uses.

OCR reference language
SUBROUTINE area(width, height)
    RETURN width * height
ENDSUBROUTINE

size ← area(4, 7)

The difference is exactly that: a function has a RETURN and its call appears where a value is expected. A procedure is called as a statement on its own.

Parameters and arguments

A parameter is the name in the subroutine definition. An argument is the actual value passed in when it is called. In the example above, width and height are parameters and 4 and 7 are arguments.

Parameters are what make a subroutine reusable. A subroutine that always calculates the area of a four by seven rectangle is useless. One that takes any two numbers can be called anywhere.

A function takes values in and hands a value backA function drawn as a machine. The code defines area with two parameters, w and h, and returns w times h. The line x equals area of 3, 4 calls it: the two arguments, 3 and 4, drop into the machine through the hopper, and the result, 12, comes out of the chute and is stored in x, so print of x shows 12. Parameters are the names the function uses for what it is given, and arguments are the actual values supplied when it is called. Below, a procedure and a function are compared: a procedure does a job, such as printing a greeting, and gives nothing back, while a function hands a value back to the caller with return.area.py1def area(w, h):2    return w * h34x = area(3, 4)5print(x)output12A function is a machinearea(w, h)34arguments in12returnedw and h:parametersProceduredef hello():    print("Hi")does a job, givesnothing backFunctiondef double(n):    return n * 2hands a value backwith return1234
  1. Define it once with def, naming the parameters it will be given.
  2. Call it with arguments. They fill the parameters, w = 3 and h = 4.
  3. return hands the result back to the line that called it.
  4. A procedure does a job. A function also gives a value back.
Parameters are the names in the definition. Arguments are the values in the call.

Scope

The scope of a variable is the region of the program in which it can be accessed.

A local variable is declared inside a subroutine and exists only while that subroutine is running. A global variable is declared outside every subroutine and can be accessed anywhere.

OCR reference language
SUBROUTINE tally()
    count ← 0
    count ← count + 1
    RETURN count
ENDSUBROUTINE

count here is local. It is created when the subroutine starts and destroyed when it ends, so the subroutine returns 1 every single time it is called.

Why local variables are the better default

  • No accidental interference. Two subroutines can each have a variable called i without either affecting the other.
  • Memory is reclaimed. A local variable stops using memory as soon as the subroutine ends.
  • The subroutine is self contained. Everything it needs comes in as a parameter and everything it produces comes back as a return value, so it can be moved, tested and reused without dragging the rest of the program along with it.
Global variables are not simply wrong

They are the right answer when genuinely many parts of the program need one shared value, such as a running total in a game. What makes them dangerous is that any subroutine can change one, so a bug can be caused from anywhere in the program.

Local and global variables as the rooms of a houseScope shown as a house. The whole program is the house, and the variable score equals 10, declared in the hallway, is global: every room, which is to say every function, can read it. Each function is a room with its own local variables on the wall: bonus has extra equals 5 and reset has temp equals 0. A local variable exists only inside its own room and is gone when the function ends. The code on the right defines bonus, which prints score plus extra, giving 15, and then tries to print extra from outside, which fails with a NameError because extra is not visible out there. In the picture a person standing outside the house asks for extra and is refused.The program: global scopescore = 10global: every function can read itbonus()extra = 5local: only inthis roomreset()temp = 0local: only inthis roomprint(extra)NameErrorthe room's variables are not visible from outsidescope.py1score = 10          # global23def bonus():4    extra = 5       # local5    print(score + extra)67bonus()             # 158print(extra)        # erroroutput15NameError: name 'extra' is not defineda function can read a global variablea local variable dies when the function ends123
  1. The program is the house. A variable made in the hallway is global, and any function can read it.
  2. Each function is a room. Variables made inside it are local and live only in that room.
  3. Outside code cannot see a room's local variables: asking for one gives a NameError.
Make variables local by default. Reach for a global only when many functions truly share it.

Structured programming

Structured programming means building a program from separate, named, self contained subroutines with clearly defined inputs and outputs, rather than as one long block.

The advantages come up in exams constantly, and they are worth learning as reasons rather than as a list.

It is easier to write. Decomposing the problem gives you a set of small tasks, each of which is achievable. Two people can work on different subroutines at the same time without colliding.

It is easier to test. A subroutine with defined inputs and one output can be tested on its own with a handful of values. A tangled program can only be tested as a whole, which means a fault could be anywhere.

It is easier to maintain. A change to how VAT is calculated means editing one subroutine, not searching a thousand lines. Because the subroutine is self contained, you can be confident the change has not broken something elsewhere.

Code can be reused. A validation subroutine written once can be called from every point in the program that needs it, and reused in the next program entirely.

It is easier to read. A main program that reads loadQuestions(), askQuestion(), updateScore() explains itself. The same logic written inline does not.

Answer with the reason, not the label

"It is easier to maintain" is one mark at best. "It is easier to maintain, because a change only has to be made in the one subroutine responsible for that task rather than in every place the code was repeated" is the full answer.

Key terms you must be able to define

Subroutine
A named block of code that can be called from elsewhere in a program.
Procedure
A subroutine that performs a task and does not return a value.
Function
A subroutine that performs a calculation and returns a value to the code that called it.
Parameter
A named value in a subroutine definition that receives an argument when the subroutine is called.
Argument
The actual value passed to a subroutine when it is called.
Return value
The value a function sends back to the code that called it.
Scope
The region of a program in which a variable can be accessed.
Local variable
A variable declared inside a subroutine, which exists only while that subroutine runs.
Global variable
A variable declared outside all subroutines, accessible anywhere in the program.
Structured programming
Building a program from separate, self contained subroutines with defined inputs and outputs.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineSubroutine
AnswerA named block of code that can be called from elsewhere in a program.
DefineProcedure
AnswerA subroutine that performs a task and does not return a value.
DefineFunction
AnswerA subroutine that performs a calculation and returns a value to the code that called it.
DefineParameter
AnswerA named value in a subroutine definition that receives an argument when the subroutine is called.
DefineArgument
AnswerThe actual value passed to a subroutine when it is called.
DefineReturn value
AnswerThe value a function sends back to the code that called it.
DefineScope
AnswerThe region of a program in which a variable can be accessed.
DefineLocal variable
AnswerA variable declared inside a subroutine, which exists only while that subroutine runs.

Reach the top grade on this topic

There are two things that separate a full mark answer here.

Naming the direction of data. A parameter carries data in. A return value carries data out. An answer that says which is which, and names the actual values in the question, is complete.

Explaining scope as a consequence rather than a rule. "Local variables cannot be accessed outside the subroutine" is the rule. "Which means two subroutines can each use a variable called total without one overwriting the other" is the reason it is worth having, and that is what a high mark answer says.

Mistakes that cost marks here

Avoid these
  • Calling every subroutine a function. A function returns a value, a procedure does not.
  • Mixing up parameter and argument. The parameter is in the definition, the argument is the value passed in.
  • Saying a local variable is 'deleted' when the program ends. It ends when the subroutine ends, not the program.
  • Listing the advantages of structured programming without giving a reason for any of them.
  • Assuming global variables are always bad practice. They are appropriate for genuinely shared state and dangerous only because any part of the program can change one.
Fun fact

The word 'bug' predates computing, but the most famous one is real. In 1947 a moth was found stuck in a relay of the Harvard Mark II, and the operators taped it into the logbook with the note 'first actual case of bug being found'.

Knowledge check

0 of 10 answered
1What is the difference between a procedure and a function?
2In SUBROUTINE area(width, height), what are width and height?
3A variable declared inside a subroutine is described as having what kind of scope?
4Why can two different subroutines both use a local variable called count?
5Which of these is a genuine advantage of structured programming?
6A subroutine returns 1 every time it is called, even though it should count upwards. What is the most likely cause?
7What is passed to a subroutine when it is called?
8Which statement about global variables is correct?
9Why does using parameters make a subroutine more useful?
10A program calls validate(age) and stores the result. What must validate be?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

14 marks
1State one difference between a parameter and an argument.2 marks
State

Mark scheme0 / 2
  • LA parameter is the name given in the subroutine definition
  • LAn argument is the actual value passed in when the subroutine is called
Model answer

A parameter is the named variable listed in the subroutine's definition, which receives a value when the subroutine runs. An argument is the actual value supplied at the point where the subroutine is called.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Explain why it is usually better to use local variables than global variables inside a subroutine.4 marks
Explain

Mark scheme0 / 4
  • LA local variable exists only while the subroutine runs
  • LSo it cannot be changed by any other part of the program
  • LTwo subroutines can use the same variable name without conflict
  • LThe subroutine becomes self contained, so it is easier to test and reuse
Model answer

A local variable is created when the subroutine starts and destroyed when it finishes, so it cannot be read or altered by any other part of the program. That removes a whole class of bug in which one section of a program changes a value another section was relying on, and it means two subroutines can each use a variable called total without either affecting the other. It also makes the subroutine self contained: everything it needs arrives as a parameter and everything it produces leaves as a return value, so it can be tested on its own and reused in another program without dragging the rest of the code along with it.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Describe two advantages of breaking a long program into subroutines.4 marks
Describe

Mark scheme0 / 4
  • LCode written once can be called from several places, so there is less repetition
  • LA change or correction only has to be made in one place
  • LEach subroutine can be tested independently
  • LThe program is easier to read and several people can work on it at once
Model answer

The first advantage is maintenance. A task written once as a subroutine is called wherever it is needed, so there is no repeated code, and when that task has to change it is corrected in exactly one place rather than in every copy. The second is testing and readability. Each subroutine has one clear job and defined inputs and outputs, so it can be tested on its own with a small set of values before it is trusted, and the main program reads as a list of named steps, which makes it far easier for another programmer, or for you in six months, to follow.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4A subroutine is written to count how many times it has been called, but it returns 1 every time. Explain the cause and how it could be corrected.4 marks
Explain

Mark scheme0 / 4
  • LThe counter is declared as a local variable inside the subroutine
  • LIt is therefore created again each time the subroutine is called
  • LThe value from the previous call is lost when the subroutine ends
  • LCorrect it by making the counter global, or by passing the count in and returning it
Model answer

The counter has been declared and initialised inside the subroutine, which makes it local. A local variable is created when the subroutine starts and destroyed when it ends, so the value reached on one call is gone by the next and the counter is reset to zero every time, which is why it always returns one. There are two reasonable corrections. Declaring the counter as a global variable outside every subroutine means it persists between calls. Alternatively, and more safely, the current count can be passed in as a parameter and the new count returned, which keeps the subroutine self contained.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 14