# 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 centred 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 "<pyshell#14>", line 1, in <module> 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) <type 'str'>

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' >>>

t | h | i | s | i | s | m | y | s | t | r | i | n | g | |||

0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |

-17 | -16 | -15 | -14 | -13 | -12 | -11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |

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

Traceback (most recent call last): File "<pyshell#61>", line 1, in <module> 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) <type 'list'> >>> 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 "<pyshell#7>", line 1, in <module> 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

Sl No. | Relational Operator | Description |
---|---|---|

1 | == | If the two values on the right hand side and left hand side of the operator are the same, the condition becomes true |

2 | != | If the values on the right hand side and left hand side of the operator are not the same, the condition becomes true |

3 | < | If the value on the left hand side is less than the right hand side of the operator, the condition becomes true |

4 | > | If the value on the left hand side is greater than right hand side of the operator, the condition becomes true |

5 | <= | When the value on the left hand side is less than or equal to the value on the right hand side, the condition returns true |

6 | >= | When the value on the left hand side is greater than the value on the right hand side, the condition returns true |

7 | <> | When the values on either side of the operator are not equal, then the conditional operator returns true |

8 | AND | The statement checks for the Boolean value of the individual statements and returns the Boolean when both the conditions is true |

9 | OR | The statement checks for the Boolean value of the individual statements and returns the Boolean when at least one of the conditions is true |

10 | NOT | Returns the negative of the statement made |

Python Working examples:

x=4 y=5 print x==5 False print x>y False print x>=y False print x<y True print x<=y True >>> x,y (5, 6) >>> (x<y and x<6) True >>> (x<y and x<1) False >>> (x>y and x<6) False >>> (x>y and x>6) False >>> not(x>y and x>6) True >>> (x<y or x<6) True >>> (x<y or x<1) True >>> (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.

Sl No. | Operators | Functions |
---|---|---|

1 | x << y | Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y |

2 | x >> y | Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y |

3 | x & y | Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0 |

4 | y | Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1 |

5 | ~ x | Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1 |

6 | x ^ y | Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1 |

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.

Sl No. | Operator | Description |
---|---|---|

1 | ** | Exponentiation (raise to the power) |

2 | “~”, “ +”, “ –“ | Complement, unary plus and minus (method names for the last two are +@ and -@) |

3 | * / % // | Multiply, divide, modulo and floor division |

4 | + - | Addition and subtraction |

5 | >> << | Right and left bitwise shift |

6 | & | Bitwise 'AND' |

7 | Bitwise exclusive `OR' and regular `OR' | |

8 | <= < > >= | Comparison operators |

9 | <> == != | Equality operators |

10 | = %= /= //= -= += *= **= | Assignment operators |

11 | “is”, “is not” | Identity operators |

12 | “in”, “not in” | Membership operators |

13 | “not”, “or”, “and” | Logical operators |