Revise Computingrevisecomputing.co.uk
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates

Knowledge organisers / Additional Programming Techniques

Functions and Procedures: local variables

All topicsPractise exam questions
Knowledge organiser

Additional Programming Techniques

2.2.3i

The use of local variables within functions and procedures:

What you need to know

A local variable is defined inside a sub-program (function or procedure) and can only be used within that sub-program. Once the sub-program finishes executing, the local variable is removed from memory. This prevents naming conflicts between different parts of a program.

Key points

  • Local variables are declared inside a function or procedure.
  • They can only be accessed within the sub-program where they were created.
  • They are removed from memory when the sub-program ends.
  • Using local variables prevents naming conflicts between sub-programs.
  • If you try to use a local variable outside its sub-program, you will get an error.
  • Parameters of a function/procedure are also treated as local variables.

Code examples

Local variable example
python
def calculate_tax(price):
    tax = price * 0.2  # 'tax' is local
    return tax

result = calculate_tax(100)
print(result)  # Output: 20.0
# print(tax)  # ERROR: 'tax' is not defined here