Python data types, operators, control flow statements and data structures are explained here.
Size: 3.77 MB
Language: en
Added: Apr 15, 2025
Slides: 108 pages
Slide Content
Dr. A. B. Shinde
Assistant Professor,
Electronics and Computer Science,
P V P Institute of Technology, Sangli
Data Types, Operators and
Control Flow
Contents…
Dr. A. B. Shinde
•Python Data Types: Numbers, Strings, Sequences, Declaration and
Initialization.
•Operators in Python: Arithmetic, Relational, Assignment, Logical,
Bitwise, Membership, Identity, Operator Precedence & Associativity.
•Control Flow- if, if-elif-else, nested if-else, Loops: for, while loop,
Loops using break, continue, pass.
•Python Data Structures: List, Tuple, Set, Dictionary, Slicing and
Comprehension operations using sequences.
2
Python Data Types
Dr. A. B. Shinde
Python Data Types
Dr. A. B. Shinde
•Python offers versatile collections of data types, including lists, string,
tuples, sets, dictionaries and arrays.
•The Python data types are as follows:
4
Data Types: Numeric
Dr. A. B. Shinde
Numeric Data Types
Dr. A. B. Shinde
•Numeric Data:
•Integers
– This value is represented by int class. It contains positive or
negative whole numbers (without fractions or decimals). In Python,
there is no limit to how long an integer value can be.
•Float
– This value is represented by the float class. It is a real number
with a floating-point representation. It is specified by a decimal point.
•Complex Numbers
– A complex number is represented by a complex
class. It is specified as
(real part) + (imaginary part)j.
6
Numeric Data Types
Dr. A. B. Shinde
•Numeric Data: Integer
•This is the whole
number, including negative numbers but not fractions.
•In Python, there is no limit to how long an integer value can be.
7
x = 10 # A positive integer
y = -13 # A negative integer
z = 0 # Zero is also considered an integer
Numeric Data Types
Dr. A. B. Shinde
•Numeric Data: Integer operations
8
Numeric Data Types
Dr. A. B. Shinde
•Numeric Data: Float
•This is a real
number
with a floating-point representation. It is specified
by a decimal point.
•Optionally, the character e or E followed by a positive or negative
integer may be appended to specify scientific notation.
•Examples: 0.5 and -7.823457.
•They can be created directly by entering a number with a decimal point.
9
a = 3.14 # A positive float
b = -0.99 # A negative float
c = 0.0 # A float value that represents zero
Numeric Data Types
Dr. A. B. Shinde
•Numeric Data: Float Operations
10
Numeric Data Types
Dr. A. B. Shinde
•Numeric Data: Complex
•A complex number is a number that consists of real and imaginary
parts.
•Example: 2 + 3j is a complex number where 2 is the real component,
and 3 multiplied by j is an imaginary part.
11
Numeric Data Types
Dr. A. B. Shinde
•Numeric Data: Complex Operations
12
Numeric Data Types
Dr. A. B. Shinde
•Type Conversion:
13
Data Types: String
Dr. A. B. Shinde
String Data Types
Dr. A. B. Shinde
•A string is a sequence of characters.
•Python treats anything inside quotes as a string.
•This includes letters, numbers, and symbols.
•Python has no character data type so single character is a string of
length 1.
15
String Data Types
Dr. A. B. Shinde
•Creating a String
•Strings can be created using either
single (‘)
or
double (“)
quotes.
16
String Data Types
Dr. A. B. Shinde
•Multi-line Strings
•If we need a string to span multiple lines then we can use
triple quotes
(”’ or “””).
17
String Data Types
Dr. A. B. Shinde
•Accessing characters in String
•Strings in Python are sequences of characters, so we can access
individual characters using
indexing.
•Strings are indexed starting from
0
and
-1
from end
.
•This allows us to retrieve specific characters from the string.
18
Positive Indexing Negative Indexing
String Data Types
Dr. A. B. Shinde
19
•String Slicing:
•Slicing
is a way to extract portion of a string by specifying
the
start
and
end
indexes.
•The syntax for slicing is
string[start:end], where
start
starting index
and
end
is stopping index (excluded).
Python Operators
Dr. A. B. Shinde
Operators in Python
Dr. A. B. Shinde
•Arithmetic,
•Relational,
•Assignment,
•Logical,
•Bitwise,
•Membership,
•Identity,
•Operator Precedence & Associativity.
21
Arithmetic Operators
Dr. A. B. Shinde
•Arithmetic Operators in Python
•Operators
are fundamental for performing mathematical calculations.
•Arithmetic operators are symbols used to perform mathematical
operations on numerical values.
•Arithmetic operators include
–addition (+),
–subtraction (-),
–multiplication (*),
–division (/), and
–modulus (%).
22
Arithmetic Operators
Dr. A. B. Shinde
•Arithmetic Operators in Python
23
Operator Description Syntax
+ Addition:
adds two operands
x + y
– Subtraction:
subtracts two operands
x – y
* Multiplication:
multiplies two operands
x * y
/
Division (float):
divides the first operand
by the second
x / y
//
Division (floor):
divides the first operand
by the second
x // y
%
Modulus:
returns the remainder when the
first operand is divided by the second
x % y
**
Power:
Returns first raised to power
second
x ** y
Arithmetic Operators
Dr. A. B. Shinde
•Arithmetic Operators in Python
24
Relational Operators
Dr. A. B. Shinde
•Relational/Comparison operators are used to compare the values of
two operands (elements being compared).
•When comparing strings, the comparison is based on the alphabetical
order of their characters (lexicographic order).
25
Operator Description Syntax
>
Greater than:
True if the left operand is greater than
the right
x > y
< Less than:
True if the left operand is less than the rightx < y
== Equal to:
True if both operands are equal x == y
!= Not equal to:
True if operands are not equal x != y
>=
Greater than or equal to:
True if the left operand is
greater than or equal to the right
x >= y
<=
Less than or equal to:
True if the left operand is less
than or equal to the right
x <= y
Relational Operators
Dr. A. B. Shinde
26
Inequality Operators a != b Equality Operators a == b
Relational Operators
Dr. A. B. Shinde
27
Greater than Sign a > b Less than Sign a < b
Greater than or Equal to Sign x >= y Less than or Equal to Sign x <= y
Relational Operators
Dr. A. B. Shinde
•Chaining Comparison Operators
•Chaining comparison operators
is used to check multiple conditions in a
single expression.
•One simple way of solving multiple conditions is by using Logical
Operators.
28
Assignment Operators
Dr. A. B. Shinde
29
Assignment Operators Addition Assignment Operator
Assignment Operators
Dr. A. B. Shinde
30
Subtraction Assignment Operator Multiplication Assignment Operator
Assignment Operators
Dr. A. B. Shinde
31
Division Assignment Operator Modulus Assignment Operator
Assignment Operators
Dr. A. B. Shinde
32
Floor Division Assignment Operator
It is used to divide the left operand with
the right operand and then assigs the
result(floor value) to the left operand.
Exponentiation Assignment Operator
Logical Operators
Dr. A. B. Shinde
•Logical operators are used to combine conditional statements, allowing
you to perform operations based on multiple conditions.
•Logical operators are used on conditional statements (either True
or False).
•They perform Logical AND , Logical OR, and Logical
NOT operations.
33
Operator Description Syntax Example
and
Returns True if both the
operands are true
x and yx>7 and x>10
or
Returns True if either of the
operands is true
x or y x<7 or x>15
not
Returns True if the operand is
false
not x
not(x>7 and x>
10)
Logical Operators
Dr. A. B. Shinde
•Truth Table for Logical Operators
34
Logical Operators
Dr. A. B. Shinde
•Logical AND operation
35
Logical Operators
Dr. A. B. Shinde
•Logical OR operation
36
Logical Operators
Dr. A. B. Shinde
•Logical NOT Operation
37
Bitwise Operators
Dr. A. B. Shinde
•Python bitwise operators are used to perform bitwise calculations on
integers.
•The integers are first converted into binary and then operations are
performed on each bit or corresponding pair of bits, hence the name
bitwise operators.
•The result is then returned in decimal format.
38
Operator Description Syntax
& Bitwise AND x & y
| Bitwise OR x | y
~ Bitwise NOT ~x
^ Bitwise XOR x ^ y
>> Bitwise right shift x>>
<< Bitwise left shift x<<
Bitwise Operators
Dr. A. B. Shinde
•Bitwise AND Operator
•Bitwise AND (&)
operator takes two equal-length bit patterns as
parameters.
•The two-bit integers are compared.
•If the bits in the compared positions of the bit patterns are 1, then the
resulting bit is 1. If not, it is 0.
39
Bitwise Operators
Dr. A. B. Shinde
40
Bitwise AND Operator
Bitwise OR Operator
Bitwise Operators
Dr. A. B. Shinde
41
Bitwise XOR Operator
Bitwise NOT Operator
Bitwise Operators
Dr. A. B. Shinde
•Bitwise Shift
•These operators are used to shift the bits of a number left or right
thereby multiplying or dividing the number by two respectively.
•They can be used when we have to multiply or divide a number by two.
42
Bitwise Operators
Dr. A. B. Shinde
•Bitwise Right Shift
•Shifts the bits of the number to the right and fills 0 on voids left (fills 1 in
the case of a negative number) as a result.
•Similar effect as of dividing the number with some power of two.
43
Example:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5
Bitwise Operators
Dr. A. B. Shinde
44
Bitwise Right Shift
Bitwise Operators
Dr. A. B. Shinde
•Bitwise Left Shift
•Shifts the bits of the number to the left and fills 0 on voids right as a
result.
•Similar effect as of multiplying the number with some power of two.
45
Example:
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
Bitwise Operators
Dr. A. B. Shinde
46
Bitwise Left Shift
Membership Operators
Dr. A. B. Shinde
•The membership operators test for the membership of an object in a
sequence, such as strings, lists, or tuples.
•Python offers two membership operators to check or validate the
membership of a value.
•IN Operator
•NOT IN Operator
47
Membership Operators
Dr. A. B. Shinde
•IN Operator
•The
in operator is used to check if a character/substring/element exists
in a sequence or not.
•Evaluate to True if it finds the specified element in a sequence
otherwise False.
48
Membership Operators
Dr. A. B. Shinde
•NOT IN Operator
•The ‘not in’ operator evaluates to True if it does not find the variable in
the specified sequence and False otherwise.
49
Identity Operators
Dr. A. B. Shinde
•Identity Operators
•The Identity Operators are used to compare the objects if both the
objects are actually of the same data type and share the same memory
location.
•There are different identity operators:
•IS Operator
•IS NOT Operator
50
Identity Operators
Dr. A. B. Shinde
•IS Operator
•The
is
operator evaluates to True if the variables on either side of the
operator point to the same object in the memory and false otherwise.
51
Identity Operators
Dr. A. B. Shinde
•IS NOT Operator
•The
is not
operator evaluates True if both variables on the either side
of the operator are not the same object in the memory location
otherwise it evaluates False
52
Operator Precedence
Dr. A. B. Shinde
•Operator Precedence
53
10 + 20 * 30
is calculated as 10 + (20 * 30)
and not as (10 + 20) * 30
Operator Associativity
Dr. A. B. Shinde
•Associativity of Operators
•If an expression contains two or more operators with the same
precedence then Operator Associativity is used to determine.
•It can either be
Left to
Right or from
Right to
Left.
54
Operator Associativity
Dr. A. B. Shinde
•Associativity of Operators
55
Operator Precedence
Dr. A. B. Shinde
•Operator Precedence and Associativity in Python
56
Precedence Operators Description Associativity
1 () Parentheses Left to right
2
x[index],
x[index:index]
Subscription, slicing Left to right
3 await x Await expression N/A
4 ** Exponentiation Right to left
5 +x,
-x, ~x
Positive, negative, bitwise NOTRight to left
6 *,
@, /, //, %
Multiplication, matrix, division,
floor division, remainder
Left to right
7 +,
–
Addition and subtraction Left to right
8 <<,
>>
Shifts Left to right
9 & Bitwise AND Left to right
Operator Precedence
Dr. A. B. Shinde
•Operator Precedence and Associativity in Python
57
10 ^ Bitwise XOR Left to right
11 | Bitwise OR Left to right
12
in,
not in, is, is not,
<,
<=, >, >=, !=, ==
Comparisons,
membership tests,
identity tests
Left to Right
13 not x Boolean NOT Right to left
14 and Boolean AND Left to right
15 or Boolean OR Left to right
16 if-else Conditional expression Right to left
17 lambda Lambda expression N/A
18 :=
Assignment expression
(walrus operator)
Right to left
Precedence Operators Description Associativity
Control Flow: If … Else
Dr. A. B. Shinde
Control Flow
Dr. A. B. Shinde
•Conditional statements in
Python are used to execute certain blocks of
code based on specific conditions.
•These statements help control the flow of a program, making it behave
differently in different situations.
•Statements
•if,
•if-elif-else,
•nested if-else,
•Loops: for, while loop,
•Loops using break, continue, pass.
59
Control Flow
Dr. A. B. Shinde
•If Conditional Statement
•If statement
is the simplest form of a conditional statement.
•It executes a block of code if the given condition is true.
60
Short-hand if statement allows
us to write a single-line if
statement
Control Flow
Dr. A. B. Shinde
•If else Conditional Statements
•It allows us to specify a block of code that will execute if the condition(s)
associated with an if or elif statement evaluates to False.
•Else block provides a way to handle all other cases that don't meet the
specified conditions.
61
The short-hand if-else statement
Control Flow
Dr. A. B. Shinde
•elif Statement
•elif statement stands for "else if."
•It allows us to check multiple conditions, providing a way to execute
different blocks of code based on which condition is true.
•Using elif statements makes our code more readable and efficient by
eliminating the need for multiple nested if statements.
62
Control Flow
Dr. A. B. Shinde
•Nested if…else Conditional Statements
•Nested if…else
means an if-else statement inside another if statement.
•We can use nested if statements to check conditions within conditions.
63
Control Flow
Dr. A. B. Shinde
•Match-Case Statement
•match-case statement
is switch-case found in other languages.
•It allows us to match a variable's value against a set of patterns.
64
Control Flow: Loop Statements
Dr. A. B. Shinde
Loop Statements
Dr. A. B. Shinde
•Loops are used to repeat actions efficiently.
•The main types are For loops (counting through items) and While loops
(based on conditions).
•Additionally, Nested Loops allow looping within loops for more complex
tasks.
66
Loop Statements
Dr. A. B. Shinde
•While Loop in Python
•While loop
is used to execute a block of statements repeatedly until a
given condition is satisfied.
•When the condition becomes false, the line immediately after the loop
in the program is executed.
67
while expression:
statement(s)
Loop Statements
Dr. A. B. Shinde
•While Loop with else statement
•Else clause is only executed when our while condition becomes false.
•If we break out of the loop or if an exception is raised then it won’t be
executed.
68
while condition:
# execute these statements
else:
# execute these statements
Loop Statements
Dr. A. B. Shinde
•Infinite While Loop
•If we want a block of code to execute infinite number of times then we
can use the while loop in Python to do so.
69
Loop Statements
Dr. A. B. Shinde
•For Loop
•For loops
are used for sequential traversal.
•For example: traversing a
list
or
string
or
array
etc.
•“for in” loop in Python is similar to
foreach
loop in other languages.
70
for iterator_var in sequence:
statements(s)
Loop Statements
Dr. A. B. Shinde
•For Loop
•Example with List, Tuple, String, and Dictionary
71
Loop Statements
Dr. A. B. Shinde
•for Loop with else Statement
•We can combine else statement with for loop like in while loop.
•But as there is no condition in for loop based on which the execution
will terminate so the else block will be executed immediately after for
block finishes execution.
72
Loop Statements
Dr. A. B. Shinde
•Nested Loops
•Loop inside another loop is called
as
nested loop.
73
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
while expression:
while expression:
statement(s)
statement(s)
Loop Statements
Dr. A. B. Shinde
•Loop Control Statements
•Loop control statements change execution from their normal sequence.
•When execution leaves a scope, all automatic objects that were created
in that scope are destroyed.
•Python supports the following control statements.
•Continue
•Break
•Pass
74
Loop Statements
Dr. A. B. Shinde
•Loop Control Statements
•Continue Statement
•The
continue statement
in Python returns the control to the beginning of
the loop.
75
Loop Statements
Dr. A. B. Shinde
•Loop Control Statements
•Break Statement
•The
break statement
in Python brings control out of the loop.
76
Loop Statements
Dr. A. B. Shinde
•Loop Control Statements
•Pass Statement
•pass statement in Python is used to write empty loops.
•Pass is also used for empty control statements, functions and classes.
77
Python Data Structures
Dr. A. B. Shinde
List
Dr. A. B. Shinde
•In Python, a
list
is a built-in dynamic sized array (automatically grows
and shrinks).
•We can store all types of items (including another list) in a list.
•A list may contain mixed type of items.
•List can contain duplicate items.
•List in Python are Mutable (Changeable). Hence, we can modify,
replace or delete the items.
•List are ordered. It maintain the order of elements based on how they
are added.
•Accessing items in List can be done directly using their position (index),
starting from 0.
79
List
Dr. A. B. Shinde
•Example: List Operations
80
List
Dr. A. B. Shinde
•Creating a List
•Using Square Brackets
81
Using list() Constructor
List
Dr. A. B. Shinde
•Creating a List
•Creating List with Repeated Elements
82
Accessing List Elements
Tuple
Dr. A. B. Shinde
•A tuple is an immutable/unchangeable ordered collection of elements.
•Tuples are similar to lists, but unlike lists, they cannot be changed after
their creation (i.e., they are immutable).
•Tuples can hold elements of different data types.
•The main characteristics of tuples are being ordered, heterogeneous
and immutable
83
Tuple
Dr. A. B. Shinde
•Creating a Tuple
•A tuple is created by placing all the items inside parentheses (),
separated by commas.
•A tuple can have any number of items and they can be of different
data
types
84
Tuple
Dr. A. B. Shinde
•Creating a Tuple with Mixed Datatypes
85
Tuple
Dr. A. B. Shinde
•Accessing of Tuples
•We can access the elements of a tuple by using indexing and
slicing.
•Indexing starts at 0 for the first element and goes up to n-1, where n is
the number of elements in the tuple.
•Negative indexing starts from -1 for the last element and goes
backward
86
Tuple
Dr. A. B. Shinde
•Concatenation of Tuples
•Tuples can be concatenated using the + operator.
•This operation combines two or more tuples to create a new tuple
87
Tuple
Dr. A. B. Shinde
•Slicing of Tuple
•Slicing a tuple
means creating a new tuple from a subset of elements of
the original tuple.
88
Tuple
Dr. A. B. Shinde
•Deleting a Tuple
•Since tuples are immutable, we cannot delete individual elements of a
tuple.
•However, we can delete an entire tuple using
del statement.
89
Tuple
Dr. A. B. Shinde
•Tuple Built-In Methods
•Tuples support only a few methods due to their immutable nature. The
two most commonly used methods are count() and index()
90
Built-in-Method Description
index( )
Find in the tuple and returns the index of the given
value where it’s available
count( )
Returns the frequency of occurrence of a specified
value
Tuple
Dr. A. B. Shinde
•Tuple Built-In Functions
91
Buiit-in Function Description
all() Returns true if all element are true or if tuple is empty
any()
return true if any element of the tuple is true. if tuple is empty, return
false
len() Returns length of the tuple or size of the tuple
enumerate() Returns enumerate object of tuple
max() return maximum element of given tuple
min() return minimum element of given tuple
sum() Sums up the numbers in the tuple
sorted() input elements in the tuple and return a new sorted list
tuple() Convert an iterable to a tuple.
Tuples Vs Lists
Dr. A. B. Shinde
Similarities Differences
Functions that can be used for both lists
and tuples:
len(), max(), min(), sum(), any(), all(),
sorted()
Methods that cannot be used for tuples:
append(), insert(), remove(), pop(), clear(),
sort(), reverse()
Methods that can be used for both lists
and tuples:
count(), Index()
we generally use ‘tuples’ for
heterogeneous (different) data types and
‘lists’ for homogeneous (similar) data
types.
Tuples can be stored in lists.
Iterating through a ‘tuple’ is faster than in a
‘list’.
Lists can be stored in tuples.
‘Lists’ are mutable whereas ‘tuples’ are
immutable.
Both ‘tuples’ and ‘lists’ can be nested.
Tuples that contain immutable elements
can be used as a key for a dictionary.
92
Set
Dr. A. B. Shinde
•Python set is an unordered collection of multiple items having different
datatypes.
•Sets are mutable, unindexed and do not contain duplicates.
•The order of elements in a set is not preserved and can change.
93
Set
Dr. A. B. Shinde
•Creating a Set
•In Python, the most basic and efficient method for creating a set is
using curly braces.
94
Set
Dr. A. B. Shinde
•Using the set() function
•Sets can be created by using the built-in
set()
function with an iterable
object or a sequence by placing the sequence inside curly braces,
separated by a ‘comma’.
95
Set
Dr. A. B. Shinde
•Adding Elements to a Set
•We can add items to a set using
add() method
and
update() method.
•add() method can be used to add only a single item.
•To add multiple items we use update() method.
96
Set
Dr. A. B. Shinde
•Accessing a Set
•We can loop through a set to access set items as set is unindexed and
do not support accessing elements by indexing.
•Also we can use
in keyword
which is membership operator to check if
an item exists in a set.
97
Set
Dr. A. B. Shinde
•Removing Elements from the Set
•We can remove an element from a set in Python using several
methods: remove(), discard() and pop().
•Each method works slightly differently :
•Using
remove() Method
or
discard() Method
•Using
pop() Method
•Using
clear() Method
98
Set
Dr. A. B. Shinde
•Removing Elements from the Set
•Using remove() Method or discard() Method
•remove() method removes a specified element from the set. If the
element is not present in the set, it raises a KeyError.
•discard() method also removes a specified element from the set.
•Unlike remove(), if the element is not found, it does not raise an error.
99
Set
Dr. A. B. Shinde
100
Removing Elements from the Set
Using remove() Method or discard() Method
Set
Dr. A. B. Shinde
•Removing Elements from the Set
•Using pop() Method
•pop() method removes and returns an arbitrary element from the set.
•This means we don’t know which element will be removed.
•If the set is empty, it raises a KeyError.
101
Set
Dr. A. B. Shinde
•Removing Elements from the Set
•Using clear() Method
•clear() method removes all elements from the set, leaving it empty.
102
Dictionaries
Dr. A. B. Shinde
•A Python dictionary
is a data structure that stores the value in
key:
value
pairs.
•Values in a dictionary can be of any data type and can be duplicated,
whereas keys can’t be repeated and must be
Dictionaries
Dr. A. B. Shinde
•Create a Dictionary
•A dictionary can be created by placing a sequence of elements within
curly
{}
braces, separated by a ‘comma’.
104
Dictionaries
Dr. A. B. Shinde
•Accessing Dictionary Items
•We can access a value from a dictionary by using the
key
within square
brackets or get() method.
105
Dictionaries
Dr. A. B. Shinde
•Adding and Updating Dictionary Items
•We can add new key-value pairs or update existing keys by using
assignment.
106
Dictionaries
Dr. A. B. Shinde
•Removing Dictionary Items
•We can remove items from dictionary using the following methods:
•del: Removes an item by key.
•pop(): Removes an item by key and returns its value.
•clear(): Empties the dictionary.
•popitem(): Removes and returns the last key-value pair.
107
This presentation is published only for educational purpose
Thank You… [email protected]