Variables and Scope of Variable
Variables and Scope of Variable
Creating Variables
Example
x=5
y = "John"
print(x)
print(y
Variables do not need to be declared with any particular type, and can
even change type after they have been set.
Variable Scope in Python
In programming languages, variables need to be defined before using
them. These variables can only be accessed in the area where they are
defined, this is called scope. You can think of this as a block where you
can access variables.
1. Local Scope
Local scope variables can only be accessed within its block.
def myfunc():
300
x = 300
print(x)
myfunc()
2. Global Scope
The variables that are declared in the global scope can be accessed from
anywhere in the program. Global variables can be used inside any
functions. We can also change the global variable value.
Examples:
x=300
def myfunc():
print(x) 300
300
myfunc()
print(x)
function()
But, what would happen if you declare a local variable with the same
name as a global variable inside a function?
function()
print(msg)
As you can see, if we declare a local variable with the same name as
a global variable then the local scope will use the local variable.
Naming Variables
If you operate with the same variable name inside and outside of a function,
Python will treat them as two separate variables, one available in the global scope
(outside the function) and one available in the local scope (inside the function):
x = 300
x = 200 300
print(x)
myfunc()
print(x)