Web/ Design/ Vista

Resources for Designers & Developer

Python Variables – Data Types

All variables are objects in Python and can store data of the following types

Text, Numeric, Binary, Boolean, Sequence, Mapping and Set

These different data types are represented by inbuilt keywords as follows –

 str - for text type
 int, float, complex - for numeric types
 bytes, bytearray, memoryview - for binary types
 bool - for boolean type
 list, tuple, range - for sequence types
 dic - for mapping type
 set, frozenset - for set types

Assigning variables

a = 'Hello Python' 

This creates a string variable (str ) and assigns a value 'Hello Python' to it
a = 12 

This creates an integer (int) variable and assigns a value 12 to it
a = 12.25 

This creates a float variable and assigns a value 12.25 to it
a = 1 + 2j 

This creates a complex variable and assigns a value 1+2j to it. Here 1 is the real part and 2j is the imaginary part.
a = ["dollar", "pound", "yen"]

This creates a list variable and assigns a value ["dollar", "pound", "yen"] to it
a = ("dollar", "pound", "yen")

This creates a tuple variable and assigns a value ("dollar", "pound", "yen") to it
a = {"city" : "Dallas", "pin" : 75202}

This creates a dict variable and assigns a value {"city" : "Dallas", "pin" : 75202} to it
a = {"dollar", "pound", "yen"}

This creates a set variable and assigns a value {"dollar", "pound", "yen"} to it
a = True

This creates a bool variable and assigns a value True (True/False) to it

Apart from the variable types above Python provides functions to generate special variable types as below –

a = bytes(5) 

This is an example of a byte value - it generates a value like: b'\x00\x00\x00\x00\x00'
a = bytearray(5) 

Tthis creates a bytearray object and assigns a value which is an array of the given bytes. 

Output: bytearray(b'\x00\x00\x00\x00\x00')
a = memoryview(bytes(5))

This creates a memoryview object and assigns a value of type byte. 
a = range(5)

This creates a range variable and assigns a value (0,5) to it

Output: range(0,5)

Python also provides a way to explicitly specify the data type at the time of assignment –

 a = str("Hello Python")
 a = int(10)
 a = float(12.25)
 a = complex(1+2j)
 a = list(("dollar", "pound", "yen"))
 a = tuple(("dollar", "pound", "yen"))
 a = range(6)
 a = dict(name="Akira", age=22)
 a = set(("dollar", "pound", "yen"))
 a = frozenset(("dollar", "pound", "yen"))
 a = bool(5)
 a = bytes(5)
 a = bytearray(5)
 a = memoryview(bytes(5))