Learning Python: Variable Scope

When a variable is declared, it is accessible in areas of the program that are after where was it declared. For example, if you declare a variable outside of a function, the variable then becomes accessible to code that is run in the function.

Examples

number = 9

def myfunction():
    print(number)

print(number) # 9
myfunction() # 9

The variable number above is what is called a global variable. If we want the number variable to be accessible only inside the function, that is called a local variable.

def myfunction():
    number = 9
    print(number) # 9

myfunction() # 9

print(number) # NameError: name 'number' is not defined.

This blog post was originally published on my blog Communicode, where I write about different tech topics.

Python
Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.