A Gentle Introduction to Python
Lecture - 3
Operators, Expression and Data types
Today’s Outline
• Previous Session:
• Introduction to Token.
• Statements and Expressions.
• Today’s Session:
• Data Types, indexing and Operators
• Mutable and Immutable data types.
• Data type conversion.
• Operators.
2
Data Types
• Data type is the classification of the type of values that can be assigned
to variables.
• Dynamically typed languages, the interpreter itself predicts the data type
of the Python Variable based on the type of value assigned to that
variable.
>>> x = 2
▪ x is a variable and 2 is its value >>> type(x)
int
▪ x can be assigned different values; >>> x = 2.3
hence, its type changes accordingly >>> type(x)
float
3
Data Types (Numbers)
The number data type is divided into the following five data types:
>>> a = 0x19
>>> a = 2 >>> type(a)
• Integer >>> type(a) int
• Long Integer (removed from py3) int >>> a = 2 + 5j
• Floating-point Numbers >>> a = 2.5 >>>type(a)
>>> type(a) complex
• Complex Numbers float >>> type(a)
>>> a = 0o11 float
>>> type(a) >>> a = 9999999L
int >>> type(a)
long
5
Data Types (String)
• Python string is an ordered collection of characters which is
used to represent and store the text-based information.
• Strings are stored as individual characters in a contiguous
memory location.
• It can be accessed from both directions: forward and
backward.
>>> a = “Shiv Nadar”
>>> print(a)
Shiv Nadar
>>> a = ‘University’
>>> print(a)
University
6
Data Types (String)
• Characters of string can be individually
accessed using a method called indexing.
>>> a = “Shiv Nadar University”
• >>> print(a[5])
N
• Forward indexing starts form 0, 1, 2…. >>> print(a[-1])
y
>>> print(a[-5])
• Backward indexing starts form −1, −2, r
−3…
7
• Mutable Data Types: Data types in python where the value assigned to a
variable can be changed
• Immutable Data Types: Data types in python where the value assigned to a
variable cannot be changed
Lists
Tuples
Data Types (Tuples)
• Tuple data type in Python is a
collection of various immutable Python >>> a = (1,2,3,4)
objects separated by commas. >>> print(a)
(1,2,3,4)
>>> a = (‘ABC’,’DEF’,’XYZ’)
• Tuples are generally store different >>>print(a)
Python Data Types. (ABC,DEF,XYZ)
• A Python tuple is created using
parentheses around the elements in the
tuple.
11
Data Types (Tuple)
• To access an element of a tuple, we simply use the index of that
element. We use square brackets.
• Reverse Indexing by using indexes as −1, −2, −3, and so on, where −1
represents the last element.
• Slicing: Extract some elements from the tuple.
>>> a = (1,2,3,4) >>> a = (1,2,3,4)
>>> print(a[1]) >>> print(a[-1])
2 4
>>> a = (‘ABC’,’DEF’,’XYZ’) >>> a = (‘ABC’,’DEF’,’XYZ’)
>>>print(a[2]) >>>print(a[1:])
XYZ (DEF, XYZ)
12
Data Types (List)
Unlike strings, lists can contain any sort of objects; numbers, strings, and even
other lists. Python lists are:
• Ordered collections of arbitrary objects
>>> a = [2,3,4,5]
• Accessed by offset >>> b = [“Shiv”,
• Arrays of object references “Nadar”, “University”]
• Variable length, heterogeneous, and arbitrarily nestable >>> print(a,b)
>>> [2,3,4,5][‘Shiv’,
• Mutable ‘Nadar’, ’University’]
• Starting index is 0
• Enclosed between square brackets ‘[ ]’
13
Data Types (List)
• Much like strings, we can use the index
number to access items in lists as shown >>> a = [“Shiv”, “Nadar” “University”,
below. “Computer”]
>>> print(a[0])
Shiv
• Accessing a List Using Reverse Indexing >>> print(a[-1])
• To access a list in reverse order, we Computer
must use indexing from −1, −2…. >>> print(a[1])
Here, −1 represents the last item in University
the list.
14
Data Types (Set)
• It is an unordered collection of elements which means elements
don’t have a specific order.
• A collection that stores elements of different Python Data Types.
• Sets in Python can’t have duplicates. Each item is unique.
• The elements of a set in Python are immutable. They can’t accept
changes once added.
>>> myset = {“Shiv Nadar”, “computer”, “science”}
>>>print(myset)
{‘Shiv Nadar', 'computer', 'science’}
>>>myset = set((“Shiv Nadar”, “computer”, “science”))
15
Data Types ( Dictionary)
• An unordered collection of elements.
• A dictionary contains keys and values rather than just elements.
• Unlike lists the values in dictionaries are accessed using keys and not by
their positions
>>>dict1 ={“Branch”: “computer”, “College”: “SNU”, “year”:2011}
>>>print (dict1)
{‘Branch’:’computer’,’College’:’SNU’,’year’:2011}
>>>di = dict({1: ‘abc’,2: ‘xyz’})
16
Data Types ( Dictionary)
• The keys are separated from their respective values by a colon (:)
between them, and each key–value pair is separated using commas (,).
• All items are enclosed in curly braces.
• While the values in dictionaries may repeat, the keys are always
unique.
• The value can be of any data type, but the keys should be of
immutable data type, that is
• We can access value of a key using the key inside square brackets.
>>>dict1 ={“Branch”:”computer”,”College”:”SNU”,”year”:2011}
>>>print (dict1[year])
2011
17
Datatype Conversion
• We can do various kinds of conversions between strings, integers and
floats using the built-in int, float, and str functions
>>> x = 10 >>> y = "20" >>> z = 30.0
>>> float(x) >>> float(y) >>> int(z)
10.0 20.0 30
>>> str(x) >>> int(y) >>> str(z)
'10' 20 '30.0'
>>> >>> >>>
integer ➔ float string ➔ float float ➔ integer
integer ➔ string string ➔ integer float ➔ string
18
Explicit and Implicit Data Type
Conversion
• Data conversion can happen in two ways in Python
1. Explicit Data Conversion (we saw this earlier with the int, float, and str
built-in functions)
2. Implicit Data Conversion
• Takes place automatically during run time between ONLY numeric values
• E.g., Adding a float and an integer will automatically result in a float value
• E.g., Adding a string and an integer (or a float) will result in an error since
string is not numeric
• Applies type promotion to avoid loss of information
• Conversion goes from integer to float (e.g., upon adding a float and an
integer) and not vice versa so as the fractional part of the float is not lost
19
Implicit Data Type Conversion:
Examples
>>> print(2 + 3.4)
▪ The result of an expression that involves
5.4
a float number alongside (an) integer >>> print( 2 + 3)
number(s) is a float number 5
>>> print(9/5 * 27 + 32)
80.6
>>> print(9//5 * 27 + 32)
59
>>> print(5.9 + 4.2)
10.100000000000001
>>>
20
Implicit Data Type Conversion:
Examples
>>> print(2 + 3.4)
▪ The result of an expression that involves
5.4
a float number alongside (an) integer
>>> print( 2 + 3)
number(s) is a float number
5
>>> print(9/5 * 27 + 32)
▪ The result of an expression that involves
80.6
values of the same data type will not result
>>> print(9//5 * 27 + 32)
in any conversion
59
>>> print(5.9 + 4.2)
10.100000000000001
>>>
21
Operators
• Arithmetic Operators (**, *,/,//,%,+,_)
• Comparison Operators (<, <=, >, >=, ==)
• Python Assignment Operators (=, +=, -=, *=, /=)
• Logical Operators (and, or, not)
• Bitwise Operators (&, |, ~, >>, <<, ^)
• Membership Operators (in, not in)
22
Operator
• Arithmetic operator
Low High
Precedence
+ - * / // % **
Plus minus multiplication Float Integer Mod power
division division (remainder)
3 3 2 2 2 2 1
Left to right Right to left
23
Lets solve -
a%b = a – (b * (a//b))
20//9
-20//9 20%9
20//-9 -20%9
20%-9
-20//-9
-20%-9
27
Lets solve -
5/10*5+5*2 2**3**1
5//10*5+5*2 1**3**2
5%10*5+5*2 2**1**3
28
Built-in Functions
abs(x) # returns absolute value of x
pow(x, y) # returns value of x raised to y
min(x1, x2,...) # returns smallest argument
max(x1, x2,...) # returns largest argument
divmod(x, y) # returns a pair(x // y, x % y)
round(x [,n]) # returns x rounded to n digits after .
bin(x) # returns binary equivalent of x
oct(x) # returns octal equivalent of x
hex(x) # returns hexadecimal equivalent of x
Assign value in variables; x, y and n.
Check the working in Python
29
Mathematical
Functions
Assign a value in variable x and check the working in Python
30
Comparison Operators
Boolean expressions ask a question Operator Description
== Equals to
• Produce a Yes or No result which we use to control
program flow != Not equals to
<> Not equals to
Boolean expressions using comparison
operators evaluate to: > Greater than
• True / False - Yes / No < Less Than
>= Greater Than Equals to
Comparison operators look at variables <= Less Than Equals to
• But do not change the variables
== Equals to is used for comparison
= Is used for assignment 31
Example
32
Logical operators
• Logical operators are the and, or, not operators.
Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x
33
Logical Boolean
AND/OR True/False
AND OR
>>>a=7>7 and 2>-1 >>>a=7>7 or 2>-1
X Y Output X Y Output
>>>print(a) >>>print(a)
TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE
TRUE FALSE FALSE >>>print(7 and 0 or 5) TRUE FALSE TRUE
5
FALSE TRUE FALSE FALSE TRUE TRUE
FALSE FALSE FALSE FALSE FALSE FALSE
34
Logical operators
Just the reverse of
NOT
what is there.
• not(true) → false
35
Bitwise operators
Operator Description
& Binary AND Operator copies a bit to the result if it
Bitwise operators act on operands as exists in both operands
if they were string of binary digits. | Binary OR It copies a bit if it exists in either
operand.
^ Binary XOR It copies the bit if it is set in one
It operates bit by bit. operand but not both.
~ Binary Ones Complement It is unary and has the effect of 'flipping'
• 2 is 10 in binary and 7 is 111. bits.
In the table below: << Binary Left Shift The left operands value is moved left by
the number of bits specified by the right
operand.
• Let x = 10 (0000 1010 in binary) and y = 4
(0000 0100 in binary) >> Binary Right Shift The left operands value is moved right
by the number of bits specified by the
right operand.
37
Bitwise operators
AND
Operation Output Operation Output
• Same as 101 & 111. 0|0 0
0&0 0
• This results in 101
0&1 0 0|1 1
5&7 • Which is binary for 5.
1&0 0 1|0 1
1&1 1 1|1 1
• Binary for 4 is 0100, and that for 8 is
1000.
• After I operation, output is 1100
4|8 • Which is binary for 12.
• Bitwise operators are used in encryption algorithms and
39
applications
Bitwise operators
XOR
XOR (exclusive Operator Output
OR) returns 1 0^0 0
• If one operand is 0 Otherwise, it 0^1 1
and another is 1. returns 0. 1^0 1
1^1 0
40
Shift operator
A shift operator performs bit manipulation on data by shifting the bits of its first operand right or left
Shift operator
Left Shift (<<) Let’s Solve 15^13
12 & 10
Right Shift (>>)
11|00
5<<2
5>>2
42
Bitwise operators
Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators Operator
&
^
Bitwise AND
Bitwise XOR
Precedence
| Bitwise OR
==, !=, >, >=, <, <=, in, not in Comparison, Membership operators
not Logical NOT
and Logical AND
or Logical OR
44
Let’s Solve
10*4>>2 and 3
10%(15<10 and 20<30)
10/(5-5)
2.5%0.15
45
Membership Operators