VOOZH about

URL: https://www.codecademy.com/resources/docs/python/scope

⇱ Python | Scope | Codecademy


Skip to Content

Python Scope

Preview: @BrandonDusch 578 total contributions
@BrandonDusch

578 total contributions

Published Dec 29, 2021Updated Jul 30, 2022

Scope refers to the areas where variables are visible and accessible. Variables that can be accessed anywhere in a Python program are in the global scope. Conversely, variables that are defined within the body of structures like classes and methods exist only in the local scope.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 CoursesIncludes 6 Courses
    • With Professional CertificationWith Professional Certification
    • Beginner Friendly.
      75 hours75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With CertificateWith Certificate
    • Beginner Friendly.
      24 hours24 hours

Local Scope

Suppose a variable is initialized within a function. This variable can only be used within that function and not from outside the function.

defmy_function():
x =200
print(x)
my_function()
Copy to clipboard
Copy to clipboard

Nested Functions and Local Scope

In the example below, a variable x is defined within the local scope of the outer_function() function, followed by a defined inner_function() function. Since inner_function() exists within the local scope of outer_function(), x can be accessed and printed within inner_function():

defouter_function():
x =200
# Initialized in outer function
definner_function():
print(x)
inner_function()
outer_function()
# Output: 200
Copy to clipboard
Copy to clipboard

Global Scope

A variable initialized in the main body is defined as a global variable and can be used anywhere in the code, including nested blocks, loops, etc. This is because these variables exist in the global scope of the code.

Visit us
Visit us
Hide code
Code
Output
Hide output
Copy to your clipboard

All contributors

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 CoursesIncludes 6 Courses
    • With Professional CertificationWith Professional Certification
    • Beginner Friendly.
      75 hours75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With CertificateWith Certificate
    • Beginner Friendly.
      24 hours24 hours