Introduction to Python Programming/Python Programming - Data Types

Chapter 3.	Dataypes
Python supports object oriented programming paradigm. This essentially means that Python programming paradigm is centered on data for solving all problems posed. A variable is location in the memory of the computer you are running the program. The assignment operator,=, is used to assign values to the variable. For e.g., x=5

Python allows for multiple assignments in a single command. >>> x,y,z=5,6,34 >>> x   5 >>> y   6 >>>z 34   >>> x=3 >>> z=5 >>> x,y,z (3, 6, 5)   >>> a=b=c=78 >>> a,b,c (78, 78, 78)   >>> a=5 >>> a,b,c (5, 78, 78)   >>>

3.1. Built-in Datatypes
Python does not type cast variables. There is no need to instantiate variables before their usage quite unlike its C or Java counterpart. Python reduces the coding efforts on the programmer. Python provides three basic built data types namely None, Numeric class, and Boolean class.

3.1.1. None
The word None denotes an object with no value.

3.1.2. Numeric class
Python supports four different numerical types:


 * 1) int(signed integers)
 * 2) long integers that can be represented in octal and hexadecimal
 * 3) float – floating point real values
 * 4) complex – complex numbers

Out of the above mentioned four numeric classes, the Python numeric classes that implement integer and floating data types called int and float. The standard arithmetic operations of addition, subtraction, multiplication, division, and power of exponentiation can be used within parentheses forcing the order of operations from the normal operator precedence. There are two more very useful operations the remainder operator %, and integer division, //. When two integers are divided, the result is a floating point. The remainder operator % returns the remainder remaining after the division, and the integer division // returns the integer portion of a division after truncating the quotient. >>> 2*3   6    >>> x=2 >>> y=3 >>> x*y 6   >>> mystr="str" >>> mystr*x 'strstr' >>> mystr*x*y 'strstrstrstrstrstr' >>> print(5+3*4) 17   >>> print((5+3)*4) 32   >>> print(5**10) 9765625   >>> print(5/3) 1   >>> print(4/3) 1   >>> print(4//3) 1   >>> print(6%3) 0   >>> print(3/6) 0   >>> print(6//6) 1   >>> print(8%6) 2   >>> print(9**100) 265613988875874769338781322035779626829233452653394495974574961739092490901302182994384699044001   >>> print(float(5)+3*4) 17.0   >>> print((float(5)+3)*4) 32.0   >>> print(float(5)**10) 9765625.0   >>> print(float(5)/3) 1.66666666667   >>> print(float(4)/3) 1.33333333333   >>>     >>> print(float(4)//3) 1.0   >>> print(float(6)%3) 0.0   >>> print(float(3)/6) 0.5   >>> print(float(6)//6) 1.0   >>> print(float(8)%6) 2.0   >>> print(float(5)**10) 9765625.0

3.1.3. Boolean class
The boolean data type is implemented in the Python bool class representing the truth values. The possible state values for a Boolean object are True and False with the standard boolean operators, and, or, and not.

>>> True True >>> False False >>> True==False False >>> False==False True >>> not True False >>> not False True >>> True and True True >>> True and False False >>> False and True False >>> False and False False >>> not not True True >>> not True and not False False >>>

3.2.	Sequences
Python is strongly typed, that is Python does not convert data from one type into another data type automatically. So if you have a string variable and a numeric variable, Python print command will throw an error instead of automatically converting one of them into another type and then print.

>>> a=1 >>> b="str" >>> b="this is a string" >>> print a + b   Traceback (most recent call last): File "", line 1, in        print a +b TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> print str(a)+b 1this is a string >>>   >>> print (a,b) (1, 'this is a string') >>> print a,b 1 this is a string

3.2.1.	String
Python has a built in string class named “str”, so because careful while using a variable called str for your programming purposes. String is a series of Unicode characters. Strings can be enclosed within single quotes or double quotes. Multiple line strings can be denoted using triple single ‘’’ or double quotes “””. >>> mystring="This is a valid string" >>> type(mystring) 

Python strings are immutable, that is they cannot be changed after they are created. New strings can be created as we go on programming. Characters in the string can be accessed by the [] operator but cannot change the value. Strings are indexed with 0 at the beginning. >>> mystring="this is my string" >>> len(mystring) 17   >>> mystring[:] 'this is my string' >>> mystring[0] 't'   >>> mystring[1] 'h'   >>> mystring[3:6] 's i'   >>>

>>> mystring[7:] ' my string' >>> mystring[6]="not"

Traceback (most recent call last): File "", line 1, in        mystring[6]="not" TypeError: 'str' object does not support item assignment

3.2.2.	List
Lists in Python are one of the most used data types and is very flexible. The individual data items with the list may or may not be of the same type. Lists are declared by enclosing the data items in square brackets with each item separated from one another with a comma. The slice operator [] can be used to access the items with in lists. You can add items to the list, replace the items in the list, and delete items in the list using the index or using the item itself. >>> mylist=["file1", "my string", 5, 7] >>> print mylist ['file1', 'my string', 5, 7] >>> type(mylist)  >>> mylist[1] 'my string' >>> mylist[0] 'file1' >>> mylist[1:2] ['my string'] >>> mylist[1:3] ['my string', 5] >>> mylist.append(10) >>> mylist ['file1', 'my string', 5, 7, 10] >>> mylist.append("python") >>> mylist.append("no this") >>> mylist ['file1', 'my string', 5, 7, 10, 'python', 'no this'] >>> mylist[1:3] ['my string', 5] >>> mylist[4:] [10, 'python', 'no this'] >>> mylist[-1] 'no this' >>> print mylist ['file1', 'my string', 5, 7, 10, 'python', 'no this'] >>> mylist[1]="new string" >>> print mylist ['file1', 'new string', 5, 7, 10, 'python', 'no this'] >>> mylist[-1] 'no this' >>> len(mylist) 7   >>> mylist[6] 'no this' >>> print mylist ['file1', 'new string', 5, 7, 10, 'python', 'no this'] >>> len(mylist) 7   >>> del mylist[6] >>> print mylist ['file1', 'new string', 5, 7, 10, 'python'] >>> mylist.remove('python') >>> print mylist ['file1', 'new string', 5, 7, 10]

3.2.3.	Tuples
Tuples in Python are of immutable set or ordered items that can be strings, or any other type of variable. Once created, tuples cannot be changed. >>> x=(1) >>> print x   1 >>> px=(1,"my my") >>> print px   (1, 'my my') >>> print px[1] my my   >>> print px[1][1] y   >>> px[1]="new string" Traceback (most recent call last): File "", line 1, in    px[1]="new string" TypeError: 'tuple' object does not support item assignment

3.2.4.	Dictionary
A dictionary in Python allows one to one mapping of data and key values. There is a key value that points to the value separated by a semicolon. Every key value is pair separated from each other with a common and the entire dictionary is enclosed in flower brackets. Keys must be unique values; however values may or may not be unique.

>>> mydict={'a':"annual fees", 'b':'monthly fees', 'c':"biweekly", 'd':"weekly"} >>> mydict {'a': 'annual fees', 'c': 'biweekly', 'b': 'monthly fees', 'd': 'weekly'} >>> len(mydict) 4   >>> mydict['e']="daily" >>> mydict {'a': 'annual fees', 'c': 'biweekly', 'b': 'monthly fees', 'e': 'daily', 'd': 'weekly'} >>> mydict['e']="hourly" >>> mydict {'a': 'annual fees', 'c': 'biweekly', 'b': 'monthly fees', 'e': 'hourly', 'd': 'weekly'} >>>

3.3. Operators
While working in Python, one must understand that Python calculates based on formulas. Values are bound to variables and then calculations are stored in the variables. There are operators which indicate a particular function being carried out on the values tied to variables and resulting in the output. Complex formulas can be built upon these simple operators that perform calculations and return values. In the following sections, we will examine Python operators.

3.3.1. Assignment Operators
The simple assignment operator, =, assigns a numeric or Boolean value to the variable. The first assignment of the value to a variable creates the variable.

3.3.2. Relational and Logical Operators
Relational and logical operators compare values on either side and return Boolean values indicating whether a test that was made using the relational and logical operator holds good or not. Table 1 provides introduces Python’s relational and logical operators.

Table 1 Python's relational and logical operator

Python Working examples: x=4 y=5 print x==5 False print x>y False print x>=y False print x>> x,y (5, 6)   >>> (x>> (x>> (x>y and x<6) False >>> (x>y and x>6) False >>> not(x>y and x>6) True >>> (x>> (x>> (x>y or x<6) True >>>( x>y or x>6) False >>> not(x>y or x>6) True

3.3.3. Bitwise Operators
Bitwise operators work on bits and perform bit by bit operation. In binary operations, numbers are treated as string of bits. For example, 0 is represented by 0, 1 is represented by 1, and 2 is represented by 10 in binary.

Python program examples:

>>> x=5 >>> x<<2 20   (Explanation: 5 in binary is 0101, moving left 2 times, and padding the right with zeroes, we have 010100 which is binary for 20) >>> x   5 >>> x>>2 1   (Explanation: 5 in binary is 0101, moving right 2 times, and padding the left with zeroes, we have 0001 which is binary for 1) >>> x=5 >>> y=6 >>> x&y 4   (Explanation: 5 in binary is 0101, and 6 in binary is 0110. “AND” ing each bit with its counterpart, we get answer 0100 which is binary for 4) >>> x|y 7   (Explanation: 5 in binary is 0101, and 6 in binary is 0110. “OR” ing each bit with its counterpart, we get answer 0111 which is binary for 7) >>> x^y 3   (Explanation: 5 in binary is 0101, and 6 in binary is 0110. Exclusive “OR” ing each bit with its counterpart, we get answer 0011 which is binary for 3) >>> x^y -6   (Explanation: It's an artifact of two's complement integer representation.

In 16 bits, 1 is represented as 0000 0000 0000 0001. Inverted, you get 1111 1111 1111 1110, which is -2. Similarly, 15 is 0000 0000 0000 1111. Inverted, you get 1111 1111 1111 0000, which is -16. In general, ~n = -n – 1)

3.3.4. Membership Operators
In Python, one can examine the existence of an item, element within a list, string, or a dictionary using the IN operator. The non existence of a particular pattern, element, value, key can also be verified by using the NOT IN operator. A programmer should always consider not naming the variables as key words used by Python. >>> a=["a",(1,2,3),"b", "python", 2.7] >>> "anu" in a   False >>> "a" in a   True >>> "anu" not in a   True >>>   >>> if "python" in a: print "yay! Python exists" yay! Python exists >>>

3.3.5. Identity Operators
The identity operators are used to compare two values and return a Boolean value as the result.

>>> a=20 >>> b=30 >>> if a is b: print "true! they are equal" >>> if a is not b: print "true! they are not equal" true! they are not equal >>>

3.3.6. Operator Precedence
The following table lists all operators from highest precedence to lowest.