Data Structures and Algorithms
Lecture Slides for
in C and Python
Chapter 2
Python Digest
1
Chandan Banerjee and Atanu Das Data Structures and Algorithms in C and Python
2 Chapter Outcomes
After going through this chapter learners will be able
to introduce Python as modern programming language.
to revise the concepts of Python programming.
to apply basic syntax of Python language.
to explain the object-oriented programming features of Python.
to introduce the functional programming features of Python.
to implement the simple computational problems using Python.
to introduce Numpy array and Pandas data frame data structures.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
3 Content
2.1 Introduction 2.12 Iteration-Loops
2.2 Features of Python 2.13 Loop Control Statements
2.3 Advantages of Python 2.14 Functions
2.4 String and Variables 2.15 Modules
2.5 User Input 2.16 Packages
2.6 Python Operators 2.17 Files
2.7 Lists 2.18 Exceptions
2.8 Sets 2.19 Classes and Objects
2.9 Tuples 2.20 Functional Programming in Python
2.10 Dictionaries 2.21 Numpy Array in Python
2.11 Conditional Statements 2.22 Series and DataFrames in Pandas
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
4 Introduction
Python language was developed by Guido van Rossum in the
late 1980s and the early 1990s at the National Research
Institute for Mathematics and Computer Science in the
Netherlands.
It is derived from many other languages, including ABC,
Algol-68, C, C++, UNIX shell, SmallTalk, Modula-3, and Perl.
The present-day industry has accepted this technology and
promoted this language so much that it has already become a
favorite among programmers.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
5 Features of Python
1. Easy-to-learn 9. Broad Standard Library
2. Easy-to-read 10. Dynamic Data Type
3. Easy-to-maintain 11. Databases
4. Portable 12. Scripting
5. Extendable 13. Structured
6. Interactive Mode 14. Garbage Collection
7. Scalable 15. Integration with Other Languages
8. GUI Programming
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
6 Advantages of Python
1. Free 7. Adaptable
2. Open Source 8. Easy Front-End Collaboration
3. Beginner Friendly 9. Advance Computing Abilities
4. Ease of Implementation 10. Easy Documentation
5. General Purpose 11. Packages
6. Structured 12. Career Opportunities
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
7 Python Programme Execution
Python is normally started by using the following 3 different ways:
Command Prompt (of Operating System)
Python Command Line
Integrated Development Environment (IDE).
Python code can be executed in 2 modes:
Command mode
Script mode
All Python codes in the book have been executed using Python 3.
It may be executed using all popular Python interpreters and IDEs like IPython,
Python IDLE, Jupyter Notebook, Jupyter Lab, Spyder, VS Code, Google Collab,
PyCharm etc.
Python is used for developing the popular applications like YouTube, BitTorrent and
Dropbox.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
8 String and Variables
Normally Python variables are used to store values. For example, a string variable is a
series of characters, surrounded by single or double quotes.
Example 1: Hello world string
print("Hello from Python world!")
Output
Hello from Python world!
Example 2: Hello world string with a Python variable
msg = "Hello from Python world!"
print(msg)
Output
Hello from Python world!
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
9 String and Variables
Example 3: Concatenation or combining strings
first_name = 'Raunak'
last_name = 'Das'
name = first_name + ' ' + last_name
print(name)
Output
Raunak Das
Note: Python variables are case sensitive.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
10 String and Variables
Example 4: Different quotations in Python
Single ('), double ("), and triple (''' or """) quotes are used in Python to denote string
literals, as long as the same type of quote starts and ends the string.
To span the string across multiple lines, the triple quotes are used.
For example, all the following are legal:
my_word = 'Python'
my_sentence = "Data structure with Python."
my_paragraph = """ A Textbook of Data Structures & Algorithms with C and
Python: Theory and Practical for University and GATE Examinations."""
Output
<No output generated since all are comments>
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
11 String and Variables
Example 5: Multiline Statements
Python statements typically end with a new line. Python allows the use of the line
continuation character (\) to denote that the line should continue.
number_one = 5
number_two = 6
number_three = 9
average = (number_one + \
number_two + \
number_three)/3
print(average)
Output:
6.666666666666667
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
12 String and Variables
Example 6: Comments in Python
The hash sign indicates the beginning of a comment in a single line.
# This is the first Python program to print
Example 7: Multiline comment
For multi-line comments, 3 single quotes (‘’’) that are not inside a string literal are used.
''' This is the first line
This is the second line '''
Output:
<No output since the above 2 lines are comments>
Note: Single ('), double ("), and triple (''' or """) quotes are used in Python to denote string literals.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
13 String and Variables
Example 8: Indentation in Python
Python identifies blocks of code by line indentation.
a = 1
if a == 1:
print("a is 1")
else:
print("Output")
Output:
a is 1
Note: All statements within a given block must be indented with either blank spaces or tab
characters, but not a mixture of the two.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
14 String and Variables
Example 9: Python Identifiers and Variables
Identifiers are used to identify a variable, function, class, module, or another object. It
starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores, and digits (0 to 9).
Punctuation characters such as @, $, and % within identifiers are not allowed in Python.
It is a case-sensitive programming language. Thus, in Python, Name, and name are two
different identifiers. The following is a list of Python's reserved words:
and as assert break class continue def
del elif else except finally for from
global if import in is lambda nonlocal
not or pass raise return try while
with yield False None True
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
15 String and Variables
Example 9: Python Identifiers and Variables
Python variables are used to store and manipulate values. A variable is an object in
Python since every element is termed as an object in Python. An appropriate name is
given to the variable to identify and use each variable easily in the program.
Every variable has a type and the type of the variable is defined by the type of value it
refers to. Python variables have three major components.
Variable name
Variable type
The value assigned to a variable
# Example of variable declaration and assignments
a = 10 # Integer type (forward) declaration not required
b = 10 # Integer type (forward) declaration not required
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
16
String and Variables
Example 10: Python data types – I
Data types are used to define the type or nature of a variable in Python. Various types of
data can be stored in the memory. Python has five built-in data types: numeric, string,
list, tuple, and dictionary.
# Numeric type
x = 10
print("The data type of the variable x:", type(x))
y = 10.00
print("The data type of the variable y:", type(y))
z = 10+12j
print("The data type of the variable z:", type(z))
Output
The data type of the variable x: <class 'int'>
The data type of the variable y: <class 'float'>
The data type of the variable z: <class 'complex'>
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
17
String and Variables
Example 11: Python data types – II
# String type
myStr1 = “Python”
print("The data type of the variable myStr1:", type(myStr1))
myStr2 = "Python latest version is 3.7.4"
print("The data type of the variable myStr2:", type(myStr2))
Output
The data type of the variable myStr1: <class 'str'>
The data type of the variable str2: <class 'str'>
Note: Python supports primitive data types – integer, floating-point, Boolean, string, list, tuple,
and dictionary.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
18 User Input
Example: Prompting for numerical input
age = input("How old are you? ")
age = int(age)
pi = input("What's the value of pi? ")
pi = float(pi)
print(‘Your Age ’ + age)
print(‘pi = ’ + pi)
Output
How old are you? 54
What's the value of pi? 3.4
Your Age 54
pi = 3.4
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
19 Python Operators
Arithmetic operators
Relational (Comparison) operators
Assignment operators
Logical operators
Bitwise operators
Membership operators (in, not in)
Identity operators
Unary operators (is, is not)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
20 Python Operators
Operators’ precedence
Operator Description
** Exponentiation (raise to the power)
~ , +, - Complement, unary plus, and minus (method names for the last two are +@ and −@)
*, /, %, // Multiply, divide, modulo, and floor division
+, - Addition and subtraction
>>, << Right and left bitwise shift
& Bitwise 'AND'
^, | Bitwise exclusive `OR' and regular `OR'
<=, <, >, >= Comparison operators
<, >, ==, != Equality operators
=, %=, /=, //=, -=, Assignment operators
+=, *=, **=
is, is not Identity operators
in, not in Membership operators
not, or, and Logical operators
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
21 Lists
A list stores a series of items in a particular order. We access items using an index,
or within a loop. Lists allow us to store sets of information in one place.
Example: Create a list
cities = ['Kolkata', 'Delhi', 'Mumbai', 'Chennai', 'Agra']
print(cities)
Output:
['Kolkata', 'Delhi', 'Mumbai', 'Chennai', 'Agra']
Example: Get the last item in a list
cities = ['Kolkata', 'Delhi', 'Mumbai', 'Chennai', 'Agra']
last_cities = cities[-1]
print(last_cities)
Output
Agra
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
22 Lists
Example: Inserting elements at a particular position Output
cities = [] ['Kochi', 'Bhopal']
[Link](0, 'Kochi')
[Link](3, 'Bhopal')
print(cities)
Example: Slicing a list Output
megaCities = ['Kolkata', 'Delhi', 'Mumbai', 'Chennai'] ['Kolkata', 'Delhi']
first_two = megaCities[:2] ['Delhi', 'Mumbai', 'Chennai']
middle_three = megaCities[1:4] ['Delhi', 'Chennai']
middle_jump = megaCities[1:4:2] ['Delhi', 'Mumbai', 'Chennai']
last_three = megaCities[-3:]
print(first_two)
print(middle_three)
print(middle_jump)
print(last_three)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
23 Lists
Example: Removing elements by deleting an element Output
by its position
cities = ['Kolkata', 'Delhi', 'Mumbai', 'Chennai'] ['Kolkata', 'Delhi', 'Mumbai']
del cities[-1]
print(cities)
Example: Pop the last item from a list Output
cities = ['Kolkata', 'Delhi', 'Mumbai', 'Chennai'] Chennai
most_recent_cities = [Link]()
print(most_recent_cities)
Example: Pop the first item in a list Output
cities = ['Kolkata', 'Delhi', 'Mumbai', 'Chennai'] Kolkata
first_cities = [Link](0)
print(first_cities)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
24 Lists
Example: Sorting a list permanently Output
cities = ['Kolkata', 'Delhi', 'Mumbai', 'Chennai', 'Agra'] ['Chennai', 'Delhi', 'Agra', 'Kolkata',
[Link]() 'Mumbai']
print(cities)
Example: Sorting a list permanently in reverse Output
alphabetical order 'Delhi', 'Mumbai', 'Chennai',
cities = ['Kolkata', 'Agra'] ['Mumbai', 'Kolkata', 'Delhi',
[Link](reverse = True) 'Chennai', 'Agra']
print(cities)
Example: Reversing the order of a list Output
cities = ['Kolkata', 'Delhi', 'Mumbai', 'Chennai', 'Agra'] ['Agra', 'Chennai', 'Mumbai',
[Link]() 'Delhi', 'Kolkata']
print(cities)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
25 Lists
Example: Using a loop to generate a list of square number Output
squares = [] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
cubes = []
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
for x in range(1, 11):
square = x**2
cube = x**3
[Link](square)
[Link](cube)
print(squares)
print(cubes)
Example: List comprehensions Output
squares = [x**2 for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81,
cubes = [x**3 for x in range(1, 11)] 100]
print(squares) [1, 8, 27, 64, 125, 216, 343,
print(cubes) 512, 729, 1000]
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
26 Lists
Example: Use of lambda function for list comprehension Output
lambda functions are required when function objects are required.
letters = list(map(lambda x: x, 'Python')) ['P', 'y', 't', 'h', 'o', 'n']
print(letters)
Example: Conditionals in the list comprehension – I Output
myList1 = [x for x in range(20) if x % 2 == 0] [0, 2, 4, 6, 8, 10, 12, 14,
print(myList1) 16, 18]
Example: Conditionals in the list comprehension – II Output
myList2 = [y for y in range(100) if y % 2 == 0 if y % 5 == 0] [0, 10, 20, 30, 40, 50, 60,
print(myList2) 70, 80, 90]
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
27 Lists
Example: Conditionals in the list comprehension – III
myList3 = ["Even" if i%2 == 0 else "Odd" for i in range(10)]
print(myList3)
Output:
['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']
Example: Transpose of a matrix using list comprehension
matrix = [[15, 25], [35, 45], [55, 65], [75, 85]]
transpose = [[row[i] for row in matrix] for i in range(2)]
print(transpose)
Output:
[[15, 35, 55, 75], [25, 45, 65, 85]]
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
28 Sets
A set is a unique collection of items that are unordered and un-indexed.
Example: Create a Set and accessing items Output
mySet = {'Kolkata', 'Delhi', 'Mumbai', 'Chennai', 'Agra'} Mumbai
for x in mySet: Agra
print(x) Chennai
Kolkata
Delhi
Example: Add multiple items to a set, using the update() method Output
mySet = {'Kolkata', 'Delhi', 'Mumbai', 'Chennai', 'Agra'} {'Agra', 'Nagpur',
[Link](["Nagpur", "Ranchi", "Gangtok"]) 'Kolkata', 'Chennai',
print(mySet) 'Gangtok', 'Mumbai',
'Delhi', 'Ranchi'}
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
29 Sets
Example: Remove item(s) using remove() Output
mySet = {'Kolkata', 'Delhi', 'Mumbai', 'Chennai', 'Agra'} {'Agra', 'Kolkata', 'Delhi', 'Chennai'}
[Link]("Mumbai")
print(mySet)
Example: Remove item(s) using pop() Output
mySet = {'Kolkata', 'Delhi', 'Mumbai', 'Chennai', 'Agra'} Chennai
x = [Link]() {'Kolkata', 'Delhi', 'Mumbai',
print(x) 'Agra'}
print(mySet)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
30 Sets
Example: Join two sets using Union Output
set1 = {"x", "y", "z"} {1, 2, 3, 'x', 'y', ‘z’}
set2 = {1, 2, 3}
set3 = [Link](set2) {1, 2, 3, 'y', 'z', 'x'}
print(set3)
[Link](set2)
print(set1)
Example: Intersection operation on two sets Output
set1 = {5, 2, 6, 4, 3, 7} {2, 3}
set2 = {1, 2, 3} {2, 3}
set3 = [Link](set2)
print(set3)
set4 = set1 & set2
Print(set4)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
31 Sets
Example: Difference operation on two sets Output
set1 = {5, 2, 6, 4, 3, 7} {4, 5, 6, 7}
set2 = {1, 2, 3}
set3 = set1 - set2
print(set3)
Example: Checking subset Output
set1 = {5, 2, 6, 4, 3, 7} False
set2 = {1, 2, 3}
set3 = [Link](set2)
print(set3)
Example: The set() constructor Output
mySet = set(('Kolkata', 'Delhi', 'Mumbai', 'Chennai', 'Agra')) {'Delhi', 'Chennai',
# note the double round-brackets 'Mumbai', 'Kolkata', 'Agra'}
print(mySet)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
32 Tuples
Tuples are similar to lists, but the items in a tuple cannot be modified (i.e., not mutable).
Example: Creating and looping through a tuple Output
dims = (1975, 2009) 1975
for dim in dims:
print(dim) 2009
Example: Overwriting a tuple Output
dims = (1000, 6000) (1000, 6000)
print(dims)
dims = (12000, 9000) (12000, 9000)
print(dims)
Note: Tuple indices are similar to list max(), min() and sorted() will not work where max(), min() and sorted() will work for a tuple with numeric and string type data.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
33 Dictionaries
Dictionaries store connections between pieces of information. Each item in a dictionary is a
key-value pair. When we provide a key, Python returns the value associated with that key.
Example: Creating and getting the value with get() Output
stranger_0 = {'color': 'green'} green
stranger_color = stranger_0.get('color')
stranger_points = stranger_0.get('points', 0) 0
print(stranger_color)
print(stranger_points)
Example: Adding a key-value pair Output
stranger_0 = {'color': 'green', 'points': 5} {'color': 'green',
stranger_0['x'] = 0 stranger_0['y'] = 25 'points': 5, 'x': 0,
stranger_0['speed'] = 1.5
print(stranger_0) 'y': 25, 'speed': 1.5}
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
34 Dictionaries
Example: Modifying values in a dictionary Output
stranger_0 = {'color': 'green'} {'color': 'green', 'points': 5}
stranger_color = stranger_0.get('color')
stranger_points = stranger_0.get('points', 0) {'color': 'yellow', 'points': 10}
print(stranger_color)
print(stranger_points)
Example: Deleting a key-value pair Output
stranger_0 = {'color': 'green', 'points': 5} {'color': 'green',
print(stranger_0) 'points': 5}
del stranger_0['points']
print(stranger_0) {'color': 'green'}
Note: We can delete items of a dictionary as well as the entire dictionary using the del statement.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
35 Dictionaries
Example: Storing dictionaries in a list Output
users = [] # Start with an empty list. last: raunak
new_user = { # Make a new user, and add them to the list.
first: das
'last': 'raunak', username: raunakdas
'first': 'das', last: biyas
'username': 'raunakdas', first: banerjee
}
username: biyasbanerjee
[Link](new_user)
new_user = { # Make another new user, and add them as
well.
'last': 'biyas',
'first': 'banerjee',
'username': 'biyasbanerjee',
}
[Link](new_user)
for user_dict in users: # Show all information about each
user.
Data Structures and Algorithms in C and Python
for k,Chandan
v inBanerjee and Atanu Das
user_dict.items():
36 Dictionaries
Example: Storing lists in a dictionary Output
# Store multiple languages for each person. Raunak:
fav_languages = {
- python
'Raunak': ['python', 'ruby'],
'Biyas': ['c'], - ruby
'Rangan': ['ruby', 'go'], Biyas:
'Arka': ['python', 'haskell'], -c
}
Rangan:
# Show all responses for each person. - ruby
for name, langs in fav_languages.items(): - go
print(name + ": ") Arka:
for lang in langs:
print("- " + lang) - python
- haskell
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
37 Dictionaries
Example: Storing dictionaries in a dictionary Output
users = { Username: RDas
'RDas': {
Full name: Raunak Das
'first': 'Raunak',
'last': 'Das', Location: Garia
'location': 'Garia',
}, Username: BBanerjee
'BBanerjee': {
Full name: Biyas Banerjee
'first': 'Biyas',
'last': 'Banerjee', Location: Saltlake
'location': 'SaltLake',
},
}
for username, user_dict in [Link]():
print("\nUsername: " + username)
full_name = user_dict['first'] + " "
full_name += user_dict['last']
location = user_dict['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + [Link]())
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
38 Conditional Statements ( , if else, elif)
Example: A simple if conditional statements Output
age = int(input(‘enter age ’)) enter age 23
if age >= 18:
print("You can vote!") You can vote!
Example: If-Else conditional statements Output
my_marks=int(input("Enter the marks: ")) Enter the marks: 75
if my_marks>=90: Grade is not 'O'
print("Grade is 'O'") Marks: 75
print("Marks:", my_marks)
else:
print("Grade is not 'O'")
print("Marks:", my_marks)
print("Bye...have a nice day!")
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
39 Conditional Statements ( , if else, elif)
Example: Nested if-elif-else Statements Output
myNumber = int(input("Enter a Number ")) Enter a Number 15
if myNumber%3 == 0:
if myNumber%4 == 0: Divisible by 3 not divisible by 4
print("Divisible by 4 and 3")
else:
print("Divisible by 3 not divisible by 4")
elif myNumber%4 == 0:
print("Divisible by 4 not divisible by 3")
else:
print("Not Divisible by 3 not divisible by 4")
Example: Testing if a value is in a list Output
players = ['al', 'bea', 'cyn', 'dale'] True
print('al' in players) False
print('hi' in players)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
40
Iteration Loops ( while)
Example: Using while with a flag
prompt = "Tell me something, and I'll "
prompt += "repeat it back to you."
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input (prompt)
if message == 'quit':
active = False
else:
print(message)
Output
Tell me something, and I'll repeat it back to you.
Enter 'quit' to end the program. hello
hello
Tell me something, and I'll repeat it back to you.
Enter 'quit' to end the program. mr das
mr das
Tell me something, and I'll repeat it back to you.
Enter 'quit' to end the program. Quit
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
41
Iteration Loops ( for)
Example: Using nested for loop
for i in range(1, 5):
for j in range(1, 5):
k = i + j
print(k, end = ',')
print()
Output
2,3,4,5,
3,4,5,6,
4,5,6,7,
5,6,7,8,
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
42 Loop Control Statements
( break)
It brings control out of the loop.
Example: Using break to exit a loop
prompt = "\nWhat games have you played?"
prompt += "\nEnter 'quit' when you're done. "
while True:
game = input(prompt)
if game == 'quit':
break
else:
print("I was playing " + game + "!")
Output
What games have you played?
Enter 'quit' when you're done. chess
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
43 Loop Control Statements
( continue)
Example: Using continue in a loop Output
banned_users = ['Srinath', 'Azahar', 'Agarkar', 'Sammi'] Add a player to your team.
prompt = "Add a player to your team." Enter 'quit' when you're done. Sachin
prompt += "\nEnter 'quit' when you're done. " Add a player to your team.
players = [] Enter 'quit' when you're done. Birat
while True: Add a player to your team.
player = input(prompt)
Enter 'quit' when you're done. Rohit
if player == 'quit':
Add a player to your team.
break
elif player in banned_users: Enter 'quit' when you're done. quit
print(player + " is banned!") Your team:
continue Sachin
else: Birat
[Link](player) Rohit
print("\nYour team:")
for player in players:
print(player)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
44 Loop Control Statements
( pass)
We use pass
statements to write empty loops. Pass is also used for empty
pass statement is a null operation.
control statements, functions and classes. The
Example: Using nested for loop
for letter in 'Data_Structure':
pass
print('Last Letter: ', letter)
Output
Last Letter: e
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
45 Functions
Functions are named blocks of code designed to do one specific job. It accepts the required
information, and returns the processed information.
Example: Making a function using positional Output
argumentsn
def describe_pet(animal, name): I have a cat.
"""Display information about a pet."""
print("\nI have a " + animal + ".")
Its name is pussy.
print("Its name is " + name + ".")
describe_pet ('cat', 'pussy') I have a dog.
describe_pet ('dog', 'kit') Its name is kit.
Example: Using keyword arguments Output
def describe_pet(animal, name): I have a cat.
"""Display information about a pet.""" Its name is pussy.
print("\nI have a " + animal + ".")
print("Its name is " + name + ".")
describe_pet(animal='cat', name='pussy ') I have a dog.
describe_pet(name='kit', animal='dog') Its name is kit.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
46 Functions
Example: Using a default value arguments Output
def describe_pet(name, animal='dog'): I have a cat.
"""Display information about a pet."""
print("\nI have a " + animal + ".")
Its name is pussy.
print("Its name is " + name + ".")
describe_pet('pussy', 'cat') I have a dog.
describe_pet('kit') Its name is kit.
Example: Using None to make an argument optional Output
def describe_pet(animal, name = None): I have a cat.
"""Display information about a pet.""" Its name is pussy.
print("\nI have a " + animal + ".")
if name:
print("Its name is " + name + ".") I have a snake.
describe_pet('cat', 'pussy')
describe_pet('snake')
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
47 Functions
Example: Returning a dictionary with optional values
def build_person(first, last, age = None):
"""Return a dictionary of information about a person."""
person = {'first': first, 'last': last}
if age:
person['age'] = age
return person
musician = build_person('Kishor', 'Kumar', 54)
print(musician)
musician = build_person('Shreya', 'Ghoshal')
print(musician)
Output
{'first': 'Kishor', 'last': 'Kumar', 'age': 54}
None
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
48 Functions
Example: Allowing a function to modify a list Output
def print_models(unprinted, printed): Printing ring
"""3d print a set of models.""" Printing bracelet
while unprinted: Printing nose pin
current_model = [Link]()
print("Printing " + current_model) Unprinted: []
[Link](current_model) Printed: ['ring', 'bracelet', 'nose pin']
# Store some unprinted designs, and print each of them.
unprinted = ['nose pin', 'bracelet', 'ring']
printed = []
print_models (unprinted, printed)
print("\nUnprinted:", unprinted)
print("Printed:", printed)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
49 Modules
The module is used to break down large programs into small, manageable ones. It is a
Python file that contains Python statements and definitions.
Example: Defining module Example: Importing and working with modules
# [Link] import calculator
def addition(a, b): s = [Link](14, 15)
c = a + b print(s)
return c m = [Link](9, 5)
def subtraction(a,b): print(m)
c = a - b
Output
return c
def multiplication(a, b): 29
c = a * b 45
return c
def division(a,b):
c = a / b
return c
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
50 Modules
Example: Importing with prior knowledge
from calculator import subtraction, multiplication
st = [Link](19, 5)
print(st)
mu = [Link](19, 5)
print(mu)
Output
14
95
Example: Module aliasing Output
import calculator as cal 45
aa = [Link](40, 5)
print(aa) 6
di = [Link](48, 8)
print(di)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
51 Modules
Example: Member aliasing
from calculator import addition as add, division as div
aa = add(300, 50)
print(aa)
dd = div(24, 8)
print(dd)
Output:
350
3.0
Example: Built-in Math module Output
import math 5
cc = [Link](4.3)
ccc = [Link](6) 6
print(cc)
print(ccc)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
52
Packages
The package is a hierarchical file directory structure that defines a single Python
application environment consisting of modules and sub-packages, etc.
The Python Package Index (PyPI) is a repository of software for the Python
programming language. We can download Python packages from this repository in the
internet.
Example: Storing a function in a package
# [Link] (save this file in the ‘devices’ folder/directory)
def pc():
myList = ['8GB RAM','2TB Hard Disk']
print('The configuration of PC')
for model in myList:
print('\t%s ' % model)
def laptop():
myList = ['2GB RAM','1TB Hard Disk']
print('The configuration of Laptop')
for model in myList:
print('\t%s ' % model)
def smartphone():
myList = ['4GB RAM','128GB Hard Disk']
print('The configuration of Smartphone')
for model in myList:
print('\t%s ' % model)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
53
Packages
Example: Importing an entire user-defined package
from myfunc import *
‘’’ [Link] (save this file in the folder/directory here ‘devices’ is saved
from device import myfunc ’’’
[Link]()
[Link]()
[Link]()
Output:
The configuration of PC
8GB RAM
2TB Hard Disk
The configuration of Laptop
2GB RAM
1TB Hard Disk
The configuration of Smart Phone
4GB RAM
128GB Hard Disk
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
54
Packages (PIP Package manager)
PIP is a package manager for Python packages or modules. If we do not have PIP
installed, we can download and install it using the following method.
Example: Installing PIP
If the Python is correctly installed, we can proceed to install PIP using the following
steps in Windows OS. If PIP is not installed properly during Python installation:
∙ Download [Link] to a folder on our computer from [Link]
[Link].
∙ Open a command prompt and navigate to the folder containing [Link].
∙ Run the following command: python [Link]
∙ .Pip is now installed!
∙ We have to use the following command in the command prompt to install pymysql in
the machine:
pip install pymysql
Note: We can download and install PIP from the following page: [Link]
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
55 Files
File pointer specifies the position in the file where writing or reading take place.
Example: Reading an entire file at once Output
filename = '[Link]' <Content of the text file [Link]
with open(filename) as f_obj: will be printed>
contents = f_obj.read()
print(contents)
Example: Storing the lines in a list Output
filename = '[Link]' <Content of the text
with open(filename) as f_obj: file [Link] will be
lines = f_obj.readlines() printed line by line>
for line in lines:
print([Link]())
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
56
Files
Example: Writing multiple lines to an empty file Output
filename = '[Link]' Content of [Link]'>>>
with open(filename, 'w') as f: I love programming!
[Link]("I love programming!\n") I love creating new games.
[Link]("I love creating new games.\n")
Example: Appending to a file Output
filename = '[Link]' Content of [Link]'>>>
with open(filename, 'a') as f: I love programming!
[Link]("I also love working with data.\n") I love creating new games.
[Link]("I love making applications as well.\n") I also love working with data.
I love making applications as well.
Example: Opening a file from a subfolder in Windows Output
f_path = "C:\AD\Python\books\[Link]" Content (lines) of [Link]
with open(f_path) as f_obj: will be printed in the console.
lines = f_obj.readlines()
print(lines)
Note: The close() method automatically flushes the data but we can use ush() method if we
wantChandan
to flush the data before closing it.
Banerjee and Atanu Das
Data Structures and Algorithms in C and Python
57 Exceptions
We can write a try-except block to handle the exception that might be raised.
Example: Handling the ZeroDivisionError exception Output
try: You can't divide by zero!
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
Example: Handling the FileNotFoundError exception Output
f_name = '[Link]' If the file does not
try: exist the following
with open(f_name) as f_obj: message will be
lines = f_obj.readlines() displayed:
except FileNotFoundError: Can't find file myFile.
msg = "Can't find file {0}.".format(f_name) txt.
print(msg)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
58 Exceptions
Example: Using an else block Output
print("Enter two numbers. I'll divide them.") Enter two numbers. I'll divide them.
x = input ("First number: ") First number: 5
y = input ("Second number: ") Second number: 0
try: You can't divide by zero!
result = int(x) / int(y)
except ZeroDivisionError: Note: The use of else and
print("You can't divide by zero!") finally clauses with try -
else: except block are optional.
print(result)
Example: Printing the exception Output
try: Error will be printed
# Instructions to execute
except Exception as e:
print(e, type(e))
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
59 Classes and Objects
Classes are the foundation of object-oriented programming (OOP).
Classes represent real-world things we want to model in our programs: for example,
cars, dogs, and robots.
We use a class to make objects, which are specific instances of cars, dogs, and robots.
A class defines the general behavior that a whole category of objects can have, and
the information that can be associated with those objects.
OOP has the following three essential properties:
Abstraction: We can declare abstract classes in Python as OOPs properties.
Encapsulation: Classes are used to encapsulate (hide) data and methods in OOP.
Inheritance: Classes can inherit from each other – we can write a class that extends the
functionality of an existing class. This allows us to code efficiently for a wide variety of
situations.
Polymorphism: We can override (using same name for different tasks) functions and
operators in OOP.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
60 Classes and Objects (Encapsulation)
Example: Creating and using a class Example: Creating an object from the class
class Car(): myCar = Car('Suzuki', 'Swift-Dzire', 2020)
"""A simple attempt to model a car."""
def __init__(self, make, model, year): Example: Accessing attribute values
"""Initialize car attributes.""" print([Link])
[Link] = make print([Link])
[Link] = model print([Link])
[Link] = year
# Fuel capacity and level in gallons. Suzuki
self.fuel_capacity = 15 Swift-Dzire
self.fuel_level = 0 2020
def fill_tank(self):
"""Fill gas tank to capacity.""" Example: Accessing attribute values
self.fuel_level = self.fuel_capacity myCar.fill_tank()
print("Fuel tank is full.") [Link]()
def drive(self):
Fuel tank is full.
"""Simulate driving."""
The car is moving.
print("The car is moving.")
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
61 Classes and Objects (Encapsulation)
Example: Data Encapsulation Using Class and Example: Creating multiple objects
Object
myCar = Car('Audi', 'A4', 2019)
class Car(): myOldCar = Car('Hyundai', 'City', 2020)
"""A simple attempt to model a car.""" myTruck = Car('Toyota', 'Tacoma', 2020)
def __init__(self, make, model, year):
"""Initialize car attributes.""" Example: Modifying an attribute directly
[Link] = make
myNewCar = Car('Audi', 'A4', 2019)
[Link] = model
myNewCar.fuel_level = 6
[Link] = year
Example: Writing a method to update an
# Fuel capacity and level in gallons.
self.fuel_capacity = 15
self.fuel_level = 0
attribute's value
def fill_tank(self): def update_fuel_level(self, new_level):
"""Fill gas tank to capacity.""" """Update the fuel level."""
self.fuel_level = self.fuel_capacity if new_level <= self.fuel_capacity:
print("Fuel tank is full.") self.fuel_level = new_level
def drive(self): else:
"""Simulate driving.""" print("The tank can't hold that much!")
print("The car is moving.")
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
62
Classes and Objects (Inheritance)
Example: The __init__() method for a child class Example: Using child methods and parent methods
class eCar(Car): my_eCar = eCar('BMW', 'models', 2020)
""" A simple model of an electric car. """ my_eCar.charge()
def __init__(self, make, model, year): my_eCar.drive()
""" Initialize an electric car. """ Output
super().__init__(make, model, year )
# Attributes specific to electric cars. The vehicle is fully charged.
# Battery capacity in kWh. The car is moving.
self.battery_size = 90
# Charge level in %.
self.charge_level = 0
Example: Adding new methods to the child class
""“ snip from left column of slide 61 ""“
""“ snip from the above example in this slide """
class eCar(Car):
def charge(self):
"""Fully charge the vehicle."""
self.charge_level = 110
print("The vehicle is fully charged.")
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
63
Classes and Objects (Polymorphism)
Example: Overriding parent methods Example: Overriding operators (‘+’ operator)
class Vector():
class eCar(Car):
def __init__(self, a, b):
""“ snip from left column of slide 61 ""“ self.a = a
def fill_tank(self): self.b = b
"""Display an error message.""" def __str__(self):
print("This car has no fuel return 'Vector (%d, %d)' % (self.a, self.b)
tank!") def __add__(self, other):
return Vector(self.a+other.a, self.b+other.b)
my_eCar = eCar('BMW', 'models', 2020) V1 = Vector(7, 8)
my_eCar.fill_tank() V2 = Vector(9, -3)
print(V1 + V2)
Output Output
This car has no fuel tank! Vector (16, 5)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
64
Classes and Objects
Example: Storing classes in a file before importing Example: Importing an entire module
# [Link] import car
class Car():
""" A simple attempt to model a car. """ myBeetle = [Link]('Volkswagen', 'Beetle', 2019)
--snip— myBeetle.fill_tank()
class eCar(Car): [Link]()
""" A simple model of an electric car. """
--snip-- myBMW = [Link]('BMW', 'Model X', 2020)
[Link]()
Example: Importing classes from a module [Link]()
# [Link]
from car import Car, eCar Output
myBeetle = Car('Volkswagen', 'Beetle', 2019) Fuel tank is full.
myBeetle.fill_tank()
The car is moving.
[Link]()
The vehicle is fully charged.
myBMW = eCar('BMW', 'Model 1', 2020)
[Link]() The car is moving.
[Link]()
Fuel tank is full.
The car is moving.
The vehicle is fully charged.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
The car is moving.
Functional Programming in Python
Example: lter() Function
65 Output
def chk(x): [2, 3, 4, 6, 8, 9, 10, 12, 14,
if(x%2 == 0 or x%3 == 0): 15, 16, 18]
return 1
elements = list(filter(chk, range(2, 20)))
print(elements)
Example: : map() Function Output
def sqr(x): Original list: [1, 2, 3, 4, 5]
return x*x
Modified list: [1, 4, 9, 16, 25]
myList = [1, 2, 3, 4, 5]
newList = list(map(sqr, myList))
print('Original list: ' , myList)
print('Modified list: ' , newList)
Example: : map() Function Output
import functools Original list: [1, 2, 3, 4, 5]
def multi(x, y): Modified list: [1, 4, 9, 16, 25]
return x*y
myList = [1, 2, 3, 4, 5]
result = [Link](multi, myList)
print('Original list: ' , myList)
print('Multiplied Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das list: ' , result)
66 Numpy Array in Python
The Numpy (Numerical Python) is an open-source Python library used for scientific
computation on multi-dimensional arrays and matrices.
Besides its scientific uses, numpy library can also be used as an efficient multi-
dimensional container (called n-dimensional array or ndarray object) of data.
Using numpy, we can also perform mathematical and logical operations on arrays.
ndarray is the main object to deal with multidimensional homogeneous array with
predetermined (fixed) items.
Numpy supports a much greater variety of numerical types than Python does, like bool,
complex, complex128, complex64, float, float16, float32, float64, int, int16, Int32,
Int64, int8, intc, intp, uint16, uInt32, uInt64, and uint8.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
67 Numpy Array in Python
Example: Creating an array Output
import numpy as np [ 1, 5, 9, 13, 17]
b = [Link](1, 20, 4) [ 0. 2. 4. 6. 8. 10. 12. 14. 16. 18. 20.]
print(b) [ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
b1 = [Link](0, 20, 11)
print(b1)
b2 = [Link](0, 20, 11, dtype = int)
print(b2)
Example: Creating an identity matrix (2D array) Output
import numpy as np [ [1., 0., 0.],
b = [Link](3) [0., 1., 0.],
print(b) [0., 0., 1.] ]
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
68 Numpy Array in Python
Example: Reshaping a 1D array into matrix form Output
import numpy as np [ [ 1, 3, 5, 7],
a = [Link](1, 40, 2).reshape(5, 4) [ 9, 11, 13, 15],
[17, 19, 21, 23],
[25, 27, 29, 31],
[33, 35, 37, 39]]
Example: Accessing, summing and conditioning on ndarray object
# Consider the last example ndarray definition
print(a[1][2]) # Output: 13
rowsum = [Link](-1)
print(rowsum) # Output: array([16, 48, 80, 112, 144])
print(a[rowsum>48, :])
Output
array([[17, 19, 21, 23],
[25, 27, 29, 31],
[33, 35, 37, 39]])
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
69 Numpy Array in Python
Table: Functions for manipulating numpy arrays
Functions Types Functions
Trigonometric sin(), arccos(), arcsin(), arctan(), arctan2(), cos(), deg2rad, degrees(), hypot(),
rad2deg(), radians(), tan(), unwrap()
Rounding around(), ceil(), x(), oor(), rint(), round(), trunc()
Exponents and exp(), exp2(), expm1(), log(), log10(), log1p(), log2(), logaddexp(), logaddexp2()
logarithms
Arithmetic add(), divide(), divmod(), oat_power(), oor_divide(), mod(), multiply(),
operations negative(), positive(), power(), reciprocal(), remainder(), subtract(),
true_divide()
Complex numbers conj(), isreal()
handling
Special functions cbrt(), clip(), convolve(), fabs(), heaviside(), interp(), maximum(), minimum(),
nan_to_num(), real_if_close(), sign(), sqrt(), square()
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
70 Series and DataFrames in Pandas
Pandas is an open-source Python library that provides easy-to-use data structure and data
analysis tools developed by Wes McKinney starting in 2008.
The primary focus of pandas library is to provide building blocks for the data analysis world.
These pandas data structures are designed to work with SQL relational data (or level data)
and Excel spreadsheets.
Pandas library is very useful for statistical analysis and decision making.
Table: Pandas data structures
Data Structure Dimensions Explanation
Series 1 Labelled, homogeneous array, size-immutable.
DataFrame 2 Size-mutable, tabular structure, heterogeneous
typed columns, labelled rows and columns.
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
71
Series and DataFrames in Pandas
Example: Creating and displaying DataFrame Output
import pandas as pd Name Age
data = {'Name’: ['Atanu','Chandan','Raunak','Biyas’], Roll-1 Atanu 45
'Age’: [45, 44, 11, 13]} Roll-2 Chandan 44
df = [Link](data, index = ['Roll-1', 'Roll-2', Roll-3 Raunak 11
'Roll-3', 'Roll-4']) Roll-4 Biyas 13
print(df)
Example: Creating DataFrame from dictionaries Output
import pandas as pd Col-1 Col-2
data = {'Col-1' : [Link]([1, 2, 3], index = ['x1', x1 1.0 1
'x2', 'x3']), 'Col-2' : [Link]([1, 2, 3, 4], index = x2 2.0 2
['x1', 'x2', 'x3', 'x4'])} x3 3.0 3
df = [Link](data) x4 NaN 4
print(df)
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
72
Series and DataFrames in Pandas
Example: : Addition and deletion of column in a DataFrame
import pandas as pd
data = {'Col-1' : [Link]([1, 2, 3], index = ['x1', 'x2', 'x3']),
'Col-2' : [Link]([1, 2, 3, 4], index = ['x1', 'x2', 'x3', 'x4'])}
df = [Link](data)
# Adding a new column to an existing DataFrame object with column label by passing new
series
df['Col-3'] = [Link]([11, 22, 33], index = ['x1', 'x2', 'x3’])
df['Col-4'] = df['Col-1'] + df['Col-3']
print(df)
# Deleting Column 1
del df['Col-1']
print(df)
Output
Col-1 Col-2 Col-3 Col-4 Col-2 Col-3 Col-4
x1 1.0 1 11.0 12.0 x1 1 11.0 12.0
x2 2.0 2 22.0 24.0 x2 2 22.0 24.0
x3 3.0 3 33.0 36.0 x3 3 33.0 36.0
x4 NaN 4 NaN NaN x4 4 NaN NaN
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
73
Series and DataFrames in Pandas
Example: Addition and deletion of rows in a DataFrame Output
import pandas as pd Col-1 Col-2
df1 = [Link]([[11, 22], [33, 44]], columns = ['Col-1', 'Col-2']) 0 11 22
df2 = [Link]([[55, 66], [77, 88]], columns = ['Col-1', 'Col-2']) 1 33 44
df1 = [Link](df2) # Addition of rows 0 55 66
print(df1) 1 77 88
# Drop rows with label 0 Col-1 Col-2
df1 = [Link](0) 1 33 44
print(df1) 1 77 88
Example: Descriptive statistics with DataFrame Output
import pandas as pd Age Marks
import numpy as np count 12.000000 12.000000
# Creating a dictionary of series mean 21.416667 82.500000
data = {'Name' : [Link](['Rohit', 'Rahul', 'Raunak', 'Sachin', 'Sourav', std 4.378840 10.475079
'Gourab', 'Atanu', 'Chandan', 'Raj', 'Satyam', 'Partha', 'Ayush']), min 14.000000 56.000000
'Age' : [Link]([16, 18, 20, 21, 19, 22, 23, 14, 27, 25, 23, 29]), 25% 18.750000 77.500000
'Marks' : [Link]([89, 78, 92, 89, 81, 56, 75, 87, 88, 95, 76, 84])} 50% 21.500000 85.500000
# Creating a DataFrame 75% 23.500000 89.000000
df = [Link](data) max 29.000000 95.000000
print([Link]()) # Function computes a summary of statistics
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das
74
END
Data Structures and Algorithms in C and Python
Chandan Banerjee and Atanu Das