Python Variables


Variables are used to tag the data. They act as references for data or objects.


Creating Variables


Python is implicitly defined hence creating variables only requires:

1. Variable Name

2. '=' : assignment operator

3. Value

# variable = value


a = 1 # int
b = 1.3 # float
c = 1+2j # complex
d = "hello" # str
e = [1, 2, 3, 2] # list
f = (1, 2, 3, 2) # tuple
g = {"a": "apple"} # dict
h = {1, 2, 3} # set


Variable Nomenclature

A variable name must obey all three rules in Python:

  1. It must consist of only A-Za-z0-9_
  2. It must not begin with digits 0-9
  3. It must not be a keyword. import keyword; print(keyword.kwlist)


    False
    None
    True
    and
    as
    assert
    async
    await
    break
    class
    continue
    def
    del
    elif
    else
    except
    finally
    for
    from
    global
    if
    import
    in
    is
    lambda
    nonlocal
    not
    or
    pass
    raise
    return
    try
    while
    with
    yield


Assignment Operator

= is used as assignment operator whereas == is used for comparison. = works right-side to left-side in a code statement.

LHS ← RHS


Multiple Assignments

Python allows for multiple values to be assigned multiple variable references in the same statement.

x, y, z = 1, 2, 3
x = y = z = 0

Type() Function

type(object) takes a variable or an object and returns its object type.

>>> x = "hello"
>>> type(x)
str


Input/Output Variable


A built-in input() provides a console interface for any input value. The default data type is str.

For publishing a value from variable reference simply use the built-in function print().

>>> x = input("Enter something: ")
>>> print(x)


Typecasting


eval() function can evaluate any value to its correct data type. Formatting is required such as string must use quotes and list must use [] etc.

Apart from eval() function the respective data type function can also be used for type casting. Eg: int(), float(), complex(), str(), list(), tuple(), dict(), set()

>>> x = input()
1
>>> type(x)
str

>>> x = eval(input())
1
>>> type(x)
int


Python Global Variable

Variables that are defined outside any function definition and directly under the module namespace are called global. The scope of global variables is the entire module.