Local & Global Variables (Cambridge (CIE) O Level Computer Science)

Revision Note

Robert Hampton

Expertise

Computer Science Content Creator

Local Variables

What is a local variable?

  • A local variable is a variable declared within a specific scope, such as a function or a code block

  • Local variables are accessible only within the block in which they are defined, and their lifetime is limited to that particular block

  • Once the execution of the block ends, the local variable is destroyed, and its memory is released

Python example

  • In this python code, you can see that the localVariable (with the value 10) is declared inside of the function printValue

  • This means that only this function can access and change the value in the local variable

  • It cannot be accessed by other modules in the program

Local variables

def printValue():
    localVariable = 10  # Defines a local variable inside the function
    print("The value of the local variable is:", localVariable)

printValue()  # Call the function

Global Variables

What is a global variable?

  • A global variable is a variable declared at the outermost level of a program. This means that they are declared outside any modules such as functions or procedures

  • Global variables have a global scope, which means they can be accessed and modified from any part of the program

Python example

  • In this python code, you can see that the globalVariable (with the value 10) is declared outside of the function printValue

  • This means that this function and any other modules can access and change the value in the global variable

Global variables

globalVariable = 10 # Defines a global variable

def printValue():
    global globalVariable
    print("The value into the variable is:", globalVariable)

printValue() # Call the function

You've read 0 of your 0 free revision notes

Get unlimited access

to absolutely everything:

  • Downloadable PDFs
  • Unlimited Revision Notes
  • Topic Questions
  • Past Papers
  • Model Answers
  • Videos (Maths and Science)

Join the 100,000+ Students that ❤️ Save My Exams

the (exam) results speak for themselves:

Did this page help you?

Robert Hampton

Author: Robert Hampton

Rob has over 16 years' experience teaching Computer Science and ICT at KS3 & GCSE levels. Rob has demonstrated strong leadership as Head of Department since 2012 and previously supported teacher development as a Specialist Leader of Education, empowering departments to excel in Computer Science. Beyond his tech expertise, Robert embraces the virtual world as an avid gamer, conquering digital battlefields when he's not coding.