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: global variables

All topicsPractise exam questions
Knowledge organiser

Additional Programming Techniques

2.2.3j

The use of global variables within functions and procedures:

What you need to know

A global variable is defined in the main program (outside any sub-program) and can be accessed from anywhere in the program, including inside functions and procedures. While useful for sharing data, overusing global variables can make programs harder to debug and maintain.

Key points

  • Global variables are declared in the main program, outside of any function or procedure.
  • They can be accessed from anywhere in the program, including inside sub-programs.
  • In OCR pseudocode, use the global keyword: global userID = "Cust001".
  • In Python, use the global keyword inside a function to modify a global variable.
  • Overusing global variables can make code harder to debug and maintain.
  • It is generally better to use local variables and pass values as parameters where possible.

Code examples

Global vs Local variable
python
score = 0  # Global variable

def add_points(points):
    global score
    score = score + points  # Modifies the global

add_points(10)
add_points(5)
print(score)  # Output: 15