Variables in Python

Variables in Python

Variable is defined as a container in memory that stores a value that can be changed. It is a way of referring to a location in the memory.
In python we do not need to declare the variable nor do we need to worry about declaring the type of the variable.
A single variable can change types dynamically during the execution of a program. A variable can assigned with a string in the beginning of the program and can be assigned a integer by the end of the program.

There are two categories we need to look into

Variables and Identifiers

The name of a variable is regarded as an identifier. Though an identifier is not just to represent variables, it can be used to represent types, labels, subroutines, functions etc.

A variable has a name, a scope, a type and a value.

Rules for local and global variables in python

A variable declared within a function is considered to be implicitly global in nature i.e. the scope of the variable is limited to the function unless the variable is explicitly declared as global.


Variables vs. Identifiers

Variables and identifiers are very often mistaken as synonyms. In simple terms: The name of a variable is an identifier, but a variable is "more than a name". A variable has a name, in most cases a type, a scope, and above all a value. Besides this, an identifier is not only used for variables. An identifier can denote various entities like variables, types, labels, subroutines or functions, packages and so on.

Global and Local Variables in Python

Global variables are the one that are defined and declared outside a function and we need to use them inside a function.

# This function uses global variable s
def code():
    print cl

# Global scope
cl = "I love Codelabs"


I love Codelabs

If a variable with same name is defined inside the scope of function as well then it will print the value given inside the function only and not the global value.

# This function has a variable with
# name same as s.
def func():
    s = "I love learning."
    print s

# Global scope
s = "I love Codelabs"
print s


I love learning.
I love Codelabs



What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.