You are on page 1of 3

Variables

Variables are containers for storing data values.

Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

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)

Msg = “This is declared globally”

def function(): This is declared globally


#local scope of function
print(Msg)

function()
But, what would happen if you declare a local variable with the same
name as a global variable inside a function?

msg = “global variable”

def function(): local variable


#local scope of function global variable
msg = “local variable”
print(msg)

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

def myfunc(): 200

x = 200 300

print(x)

myfunc()

print(x)

You might also like