Scope

What Is Scope?

  • Scope defines where a variable can be accessed in your program. It's about the region within which the variable is recognized.

Types of Scope:

  1. Local Scope:
    • A variable created inside a function is local and can only be used within that function.
    • Example:

      python
      def myfunc():
          x = 300
          print(x)
      
      myfunc()  # Output: 300
      
  2. Function Inside Function:
    • Local variables are accessible to inner functions within the same outer function.
    • Example:

      python
      def myfunc():
          x = 300
          def myinnerfunc():
              print(x)
          myinnerfunc()
      
      myfunc()  # Output: 300
      
  3. Global Scope:
    • A variable created outside of a function is global and can be accessed by any function in the program.
    • Example:

      python
      x = 300
      
      def myfunc():
          print(x)
      
      myfunc()  # Output: 300
      print(x)  # Output: 300
      

Naming Variables:

  • Using the same variable name inside and outside of a function will treat them as two separate variables.
  • Example:

    python
    x = 300
    
    def myfunc():
        x = 200
        print(x)
    
    myfunc()  # Output: 200
    print(x)  # Output: 300
    

Global Keyword:

  • Used to create or modify global variables inside a function.
  • Example:

    python
    def myfunc():
        global x
        x = 300
    
    myfunc()
    print(x)  # Output: 300
    
  • To change a global variable inside a function:

    python
    x = 300
    
    def myfunc():
        global x
        x = 200
    
    myfunc()
    print(x)  # Output: 200
    

Nonlocal Keyword:

  • Used to work with variables inside nested functions, making the variable belong to the outer function.
  • Example:

    python
    def myfunc1():
        x = "Jane"
        def myfunc2():
            nonlocal x
            x = "hello"
        myfunc2()
        return x
    
    print(myfunc1())  # Output: hello
    

Exercises:

  1. Local Scope Exercise:
    • Write a function that creates a local variable and prints its value.
  2. Global Scope Exercise:
    • Create a global variable and write two functions that print and modify its value.
  3. Using Global Keyword:
    • Modify a global variable inside a function using the global keyword.
  4. Nonlocal Keyword Exercise:
    • Write a nested function where the inner function modifies a variable from the outer function using the nonlocal keyword.

Summary:

  • Understanding scope is crucial for managing variables and their accessibility within your code. Practice using local, global, and nonlocal scopes to get comfortable with variable management in Python!