0% found this document useful (0 votes)
22 views

Lec 4. Operators Expression and Data Types

Uploaded by

sudeepiitb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Lec 4. Operators Expression and Data Types

Uploaded by

sudeepiitb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Computational Thinking with Programming

Lecture - 4

Operators, Expression and Data types

@cse_bennett @csebennett
Today’s Outline

• Previous Session:
• Introduction to Token.
• Statements and Expressions.

• Today’s Session:
• Data Types and Operators
• Mutable and Immutable data types.
• Data type conversion.
• Operators.

• Hands on Session with Jupyter Notebook:


• We will practice on the Python basic elements in Jupyter Notebook.

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

Lists • Mutable Data Types: Data types in python


where the value assigned to a variable can be
Mutable Dictionary
changed
Sets
Data Types
Numbers
• Immutable Data Types: Data types in python
Immutable Strings
where the value assigned to a variable cannot
Tuples
be changed

4
Data Types
• Numbers: The number data type in Python is used to store numerical values. It is used
to carry out the normal mathematical operations.
• Strings: Strings in Python are used to store textual information. They are used to carry
out operations that perform positional ordering among items.
• Lists: The list data type is the most generic Python data type. Lists can consist of a
collection of mixed data types, stored by relative positions.
• Tuples: Tuples are one among the immutable Python data types that can store values of
mixed data types. They are basically a list that cannot be changed.
• Sets: Sets in Python are a data type that can be considered as an unordered collection
of data without any duplicate items.
• Dictionaries: Dictionaries in Python can store multiple objects, but unlike lists, in
dictionaries, the objects are stored by keys and not by positions.

5
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
• Octal and Hexadecimal >>> a = 2.5 >>>type(a)
>>> type(a) complex
• Floating-point Numbers float >>> type(a)
• Complex Numbers >>> a = 0o11 float
>>> type(a) >>> a = 9999999L
int >>> type(a)
long
6
Data Types (Numbers)
• We can use the following built-in functions to convert one number type
into another:

• int(x), to convert x into an integer value


• long(x), to convert x into a long integer value
• float(x), to convert x into a floating-point number
• complex(x), to convert x into a complex number where the imaginary
part stays 0 and x becomes the real part
• complex(x,y), to convert x and y to a complex number where x becomes
the real part and y becomes the imaginary part
7
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 = “Bennett”
>>> print(a)
Bennett
>>> a = ‘University’
>>> print(a)
University

8
Data Types (String)
• Characters of string can be individually accessed using a method
called indexing.
• Characters can be accessed from both directions: forward and
backward.
• Forward indexing starts form 0, 1, 2…. Whereas, backward indexing
starts form −1, −2, −3…
>>> a = “Bennett University”
>>> print(a[5])
t
>>> print(a[-1])
y
>>> print(a[-5])
r
9
Data Types (Tuples)
• Tuple data type in Python is a collection of various immutable Python
objects separated by commas.
• Tuples are generally used for different Python Data Types.
• A Python tuple is created using parentheses around the elements in the
tuple. Although using parentheses is only optional, it is considered a
good practice to use them.
>>> a = (1,2,3,4)
>>> print(a)
(1,2,3,4)
>>> a = (‘ABC’,’DEF’,’XYZ’)
>>>print(a)
(ABC,DEF,XYZ)
10
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 that is, 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)
11
Data Types (List)
Unlike strings, lists can contain any sort of objects: numbers,
strings, and even other lists. Python lists are:

>>> a = [2,3,4,5]
• Ordered collections of arbitrary objects
>>> b = [“Bennett”,
• Accessed by offset “University”]
• Arrays of object references >>> print(a,b)
• Of variable length, heterogeneous, and arbitrarily nestable >>> [2,3,4,5]
• Of the category, mutable sequence [‘Bennett’,’Universi
• Data types in which elements are stored in the index basis with ty’]
starting index as 0
• Enclosed between square brackets ‘[]’
12
Data Types (List)
• Much similar to strings, we can use the index number to access items
in lists as shown below.
• Accessing a List Using Reverse Indexing
• To access a list in reverse order, we have to use indexing from −1, −2…. Here,
−1 represents the last item in the list.
>>> a = [“Bennett”, “University”, “Computer”]
>>> print(a[0])
Bennett
>>> print(a[-1])
Computer
>>> print(a[1])
University
13
Data Types (Set)
• It is an unordered collection of elements which means that a set is a
collection that stores elements of different Python Data Types.
• In Python sets, elements don’t have a specific order.
• 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 = {“bennett”, “computer”, “science”}
>>>print(myset)
{'bennett', 'computer', 'science’}
>>>myset = set((“bennett”, “computer”, “science”))

14
Data Types ( Dictionary)
• Yet another unordered collection of elements.
• Difference between dictionary and other unordered Python data types
such as sets lies in the fact that unlike sets, 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”:”Bennett”,”year”:2020}
>>>print (dict1)
{‘Branch’:’computer’,’College’:’Bennett’,’year’:2020}
>>>di = dict({1:’abc’,2:’xyz})
15
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
• Using the key inside square brackets like we used to use the index inside
square brackets.
>>>dict1 ={“Branch”:”computer”,”College”:”Bennett”,”year”:2020}
>>>print (dict1[year])
2020
16
Datatype Conversion
• As a matter of fact, 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

17
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
18
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
>>>
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)
 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
>>>
20
Operators
• Arithmetic Operators (**, *,/,//,%,+,_)
• Comparison Operators (<, <=, >, >=, ==)
• Python Assignment Operators (=, +=, -=, *=,
/=)
• Logical Operators (and, or, not)
• Bitwise Operators (&, |, ~, >>, <<, ^)
• Membership Operators (in, not in)

21
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

22
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

23
Comparison Operators

Boolean expressions ask a question Operator Description


== Equals to
• Produce a Yes or No result which we use to control != Not equals to
program flow <> Not equals to
Boolean expressions using comparison > Greater than
operators evaluate to: < Less Than
• True / False - Yes / No >= Greater Than Equals to
<= Less Than Equals to
Comparison operators look at variables
• But do not change the variables

24
Example

25
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

26
Logical operators
AND/OR
AND OR

X Y Output >>>a=7>7 and 2>-1 >>>a=7>7 or 2>- X Y Output


>>>print(a) 1
TRUE TRUE TRUE FLASE >>>print(a) TRUE TRUE TRUE
TRUE FALSE FALSE FLASE
>>>print(7 and 0 or 5) TRUE FALSE TRUE
FLASE TRUE FLASE 5
FLASE TRUE TRUE
FALSE FALSE FLASE
print(onListand
print(onList andinStock)
inStock) FALSE FALSE FLASE

print(onList and onSale)

print(onSale and rotten)

print(onList and inStock and onSale)

print(onList and inStock and onList)

print(onList and inStock)


27
Logical operators
Just the reverse of NOT
what is there.
• not(true)  false

28
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
operand but not both.
It operates bit by bit.
~ Binary Ones Complement It is unary and has the effect of 'flipping'
bits.
• 2 is 10 in binary and 7 is 111.

<< Binary Left Shift The left operands value is moved left by
In the table below: the number of bits specified by the right
operand.
• Let x = 10 (0000 1010 in binary) and y = 4 >> Binary Right Shift The left operands value is moved right
by the number of bits specified by the
(0000 0100 in binary) right operand.

29
Bitwise operators
AND
• Same as 101 & 111.
• This results in 101 Operation Output Operation Output
5&7 • Which is binary for 5. 0&0
0&1
0
0
0|0
0|1
0
1
1&0 0 1|0 1
1&1 1 1|1 1
• Binary for 4 is 0100, and that for 8 is
1000.
• After operation, output is 1100
4|8 • Which is binary for 12.

30
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

31
Shift operator
Left Shift (<<) Let’s Solve 15^13

12 & 10
Right Shift (>>)
11|00

5<<2

5>>2

32
Operator Precedence
Operators Meaning

() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

*, /, //, % Multiplication, Division, Floor division, Modulus

+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR

==, !=, >, >=, <, <=, in, not in Comparisions, Membership operators

not Logical NOT


and Logical AND
or Logical OR

33
DATA TYPE CONVERSION
Explicit and Implicit
We saw this earlier with the int, float,
Explicit Data Conversion
and str built-in functions

E.g., Adding a float and an integer will


automatically result in a float value

Takes place automatically during run


time between ONLY numeric values
E.g., Adding a string and an integer (or
a float) will result in an error since
string is not numeric
Implicit Data Conversion

Conversion goes from integer to float


Applies type promotion to avoid loss (e.g., upon adding a float and an
of information integer) and not vice versa so as the
fractional part of the float is not lost

34
Operators Let’s Solve
()
** 10*4>>2 and 3
+x, -x, ~x

*, /, //, %

+, -
<<, >> 10%(15<10 and 20<30)
&
^
|
==, !=, >, >=, <, <=,
in, not in
10/(5-5)
not
and
Or
=,*=,/=,//=,%=

2.5%0.15

35
Thank You

36

You might also like