Skip to main content

Python Variables

Python variable declaration is  allocate the memory for storing the values. Python datatypes are Numbers, Strings, Lists, Tuples and Dictionary. Python has the good memory management support. In this tutorial we will learn about  What is variable,  Rules for creating variable, Variable Types Variable declaration type. Techtuts provides an example along with concepts. You have to workout the example programs for good and well.

What is variable

Variable provides the memory space for assigning values. Python automatically assign the datatypes to based on the values assigned on the variables.  Each variable can be identified by a word, which is called  variable name.

Variables are created on python, when we are assigning values to it.

Rules for creating variable name

  1. It should contains alphabetic, Numbers and underscore only.
  2. It must not start with numbers.
  3. Spaces are not allowed within the variable name.

Python variable types

Python  two types of variables. The data type of  variables are as follows.

  1. Local
  2. Global

Python Local Variable

A variable declared within the scope of functions or classes are called as local variables for its functions or classes. Value of the variable can change within the functions and classes.

Ex:-

>>> a = 10
>>> print(a)
10

>>> def printa():
...     a = 20
...     print(a)
... 
>>> printa()
20
>>> 

Python Global Variable

A variable declared outside the scope of functions or classes are called as global variables. Value of the global variable can change outside of the functions and classes. For getting a global variable inside the functions and classes, We need to do specify the global keyword before the variable.

Ex:-

>>> a = 10
>>> print(a)
10
>>> def printa():
...     global a
...     print(a)
...     a = 20
...     print(a)
... 
>>> printa()
10
20
>>> print(a)
20
>>>