Many people find variable scopes difficult. but don't worry I am here to talk about variable scopes in python. I hope you will understand this topic very easily
We have mainly 2 types of variables in python,
Global Varibale
variable1 = "Hello world"
Local Variable
def func():
variableL = "Hello World"
as you can see, the local variable is inside a function called 'func'. If you don't know what defining a function is, then check out my another blog post which explains Defining a Function. The variable which is declared inside the function is called a local variable. why? it's because you can only access that variable inside the function. here's a example to make you further understand
let's take this 2 code snippets
var1 = "Hello World"
print(var1)
def fun():
var2 = "Hello World"
fun()
print(var2)
The second snippet will give this error NameError: name 'var2' is not defined
.
why? because the variable var2
is called outside the function.
still didn't get it? here's a analogy, Just imagine local variables as a young child inside his home. if someone calls him to come with him outside his home, will his parents allow him? no, it's the same logic,
the local variable var2
is the child and the function fun
is his home. he is just not allowed to move outside. okay, what if his parents allowed him to go out? is it possible to a local variable to be a global variable? yes of course, but the variable needs the permission to be a global variable.
The permission is
global
keyword, when you put the global keyword before the name of the variable name, the local variable is now no longer a local variable. it's consider as a global variable. here's a code for example.
var3 = ""
def fun1():
global var3
var3 = "Hello World"
fun1()
print(var3)
this code now gives what we need.
this will the output Hello World
. the moment you gave the permission. the function treats the variable var3
as a global variable, so after we called the function by fun1
the var3
is overwritten with Hello World
.
I hope you understood a little bit about variable scopes, thanks for reading my article have a good day :)