Python scope

Created By: chatGPT

In Python, the concept of scope refers to the visibility and lifetime of a variable. It determines where a variable can be accessed or modified. Python has several scopes that affect how variables are handled during execution.

The main types of scopes in Python are:

  • Local Scope: Variables defined within a function are accessible only inside that function.
  • Enclosing Scope: This occurs when a function is nested within another function. The inner function can access variables from its own scope and the outer function's scope.
  • Global Scope: Variables defined at the top level of a script or module are accessible throughout the entire module. To modify a global variable inside a function, the global keyword is used.
  • Built-in Scope: This contains built-in functions and variables that are available in any Python code, such as print() and len().
Here's an example to illustrate local and global scope:
x = 10  # Global Variable

def local_scope_example():
    x = 5  # Local Variable
    print('Inside function:', x)

local_scope_example()
print('Outside function:', x)

In the example above, within the function local_scope_example, a new local variable x is created, which shadows the global variable. The output will be:

  • Inside function: 5
  • Outside function: 10
If you want to access the global variable within a function, you can use the global keyword as follows:
x = 10  # Global Variable

def modify_global():
    global x
    x = 5  # Modify global variable

modify_global()
print('Global x after modification:', x)

After calling modify_global, the value of the global variable x will be changed to 5, and the output will be:

  • Global x after modification: 5
Understanding scope is crucial for managing variable states and avoiding unintended side effects in your code. This knowledge helps you to write more maintainable and efficient Python scripts.
Introduction And SetupVariablesData TypesIntFloatStrBoolListTupleSetDictMethodsString MethodsList MethodsDict MethodsSet MethodsControl FlowIf StatementElif StatementElse StatementFor LoopWhile LoopBreak StatementContinue StatementFunctionsDef StatementReturn StatementLambda FunctionsScopeParametersArgumentsDefault ParametersVariable Length ArgumentsOperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsAssignment OperatorsIdentity OperatorsMembership OperatorsData StructuresListsTuplesSetsDictionariesCommentsSingle Line CommentsMulti Line CommentsSyntaxIndentationDocstringsEvent HandlingError HandlingTry StatementExcept StatementFinally StatementRaise StatementAssert StatementContext ManagersWith Statement