Prepare for the A Level Computer Science OCR Exam with engaging quizzes, detailed explanations, and effective study tips. Maximize your readiness and boost your confidence for exam day!

Practice this question and more.


Which type of variable can be accessed and modified both inside and outside a function in Python?

  1. Local Variable

  2. Global Variable

  3. Static Variable

  4. Instance Variable

The correct answer is: Global Variable

A global variable in Python is defined outside any function and can be accessed and modified from anywhere in the code, including within functions. This is particularly useful when you want to maintain a value that should be the same across different parts of your program, without passing it explicitly as a parameter every time. When inside a function, a global variable can be modified if you declare it as global using the keyword 'global'. This explicit declaration informs Python that you want to refer to the global variable defined outside the function rather than creating a new local variable with the same name. In contrast, local variables are confined to the function in which they are defined, meaning they cannot be accessed or modified from outside that function. Static and instance variables pertain more to class-based contexts in object-oriented programming, where they serve different scopes and lifetimes, which do not allow the same level of accessibility from outside their respective classes or methods as global variables do.