ModuleI_HandsOnPython
ModuleI_HandsOnPython
Python Programming
Data Types, Control Flow, Strings, Functions & File Handling
1 Introduction to Python 4
1.1 What is Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Installing and Running Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Your First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Indentation and Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 Variables and Dynamic Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6 Basic Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7 Python’s Core Data Types at a Glance . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.8 Operators, Briefly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.9 Practice Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2 Lists 9
2.1 What is a List? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 Creating Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.3 Mutability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.4 Indexing and Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.5 List Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.6 List Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.7 Nested Lists and Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.8 Iterating Over Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.9 List vs. Tuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.10 Practice Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3 Tuples 14
3.1 What is a Tuple? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.2 Creating Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.3 Immutability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.4 Indexing, Slicing, and Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.5 Packing and Unpacking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.6 Nested Tuples and Tuples as Dictionary Keys . . . . . . . . . . . . . . . . . . . . . 16
3.7 Tuple vs. List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.8 Practice Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4 Dictionaries 18
4.1 What is a Dictionary? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.2 Creating Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.3 Accessing, Updating, and Deleting . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.4 Dictionary Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.5 Iterating Over Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.6 Dictionary Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.7 Nested Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
4.8 Practice Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1
Python Programming for AI & Data Analytics CONTENTS
4.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5 Sets 23
5.1 What is a Set? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.2 Creating Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
5.3 Adding and Removing Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
5.4 Mathematical Set Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
5.5 Membership and Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
5.6 set vs. frozenset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
5.7 Real-World Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
5.8 Practice Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
5.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
6 Conditional Statements 28
6.1 What is a Conditional Statement? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
6.2 Truthy and Falsy Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
6.3 The if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.4 if-else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.5 if-elif-else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.6 Nested Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.7 Compound Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.8 Conditional (Ternary) Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.9 Pattern Matching with match-case (Python 3.10+) . . . . . . . . . . . . . . . . . . 31
6.10 Practice Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
6.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
7 Loops 33
7.1 Why Loops? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
7.2 The for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
7.2.1 range() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
7.3 The while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
7.4 break and continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
7.5 The Loop else Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
7.6 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
7.7 Useful Looping Idioms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
7.8 Loops in Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
7.9 Practice Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
7.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
8 String Manipulation 38
8.1 What is a String? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
8.2 Indexing and Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
8.3 Concatenation and Repetition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
8.4 Common String Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
8.5 Splitting and Joining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
8.6 String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
8.7 Membership and Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
8.8 Iterating Over Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
8.9 Strings as Sequences: A Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
8.10 Practice Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
8.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
2
Python Programming for AI & Data Analytics CONTENTS
10 File Handling 49
10.1 Why File Handling? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
10.2 Opening and Closing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
10.3 The with Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
10.4 File Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
10.5 Reading Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
10.6 Writing and Appending Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
10.7 Working with CSV Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
10.8 Working with JSON Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
10.9 Checking File Existence and Handling Errors . . . . . . . . . . . . . . . . . . . . . 53
10.10Putting It Together: A Small Data Pipeline . . . . . . . . . . . . . . . . . . . . . . . 53
10.11Practice Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
10.12Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3
Chapter 1
Introduction to Python
Learning Objectives
➤ Describe what Python is and why it is widely used in AI and Data Analytics.
➤ Install Python and run code using the interpreter, scripts, and notebooks.
➤ Explain Python’s execution model, indentation rules, and comment syntax.
➤ Declare variables, understand dynamic typing, and use basic input/output.
➤ Identify Python’s core data types at a glance before studying each in depth.
DEFINITION — Python
Python is not the fastest language, but its simplicity accelerates experimentation. A data
scientist can load a dataset, clean it, train a model, and plot results in under twenty lines
of code — something that would take far more boilerplate in a lower-level language such
as Java or C++.
4
Python Programming for AI & Data Analytics CHAPTER 1. INTRODUCTION TO PYTHON
Every Python statement is executed line by line, from top to bottom, by the Python interpreter.
There is no separate compilation step required before running a script.
marks = 85
if marks >= 40:
print ( " Pass " ) # indented -- inside the if - block
print ( " Well done ! " ) # still inside the if - block
print ( " Result processed " ) # not indented -- outside the if - block
Comments are ignored by the interpreter and are used purely for documentation.
5
Python Programming for AI & Data Analytics CHAPTER 1. INTRODUCTION TO PYTHON
EXAMPLE — Comments
"""
This is a multi - line string ,
often used as a block comment or docstring .
"""
Variable names must start with a letter or underscore, may contain letters, digits, and
underscores, are case-sensitive (score and Score are different variables), and cannot be a
reserved keyword such as class, def, or return.
name = input ( " Enter your name : " ) # input () always returns a
str
age = int ( input ( " Enter your age : " ) ) # cast explicitly when a
number is needed
6
Python Programming for AI & Data Analytics CHAPTER 1. INTRODUCTION TO PYTHON
• Try It Yourself
Open a Python interpreter and use type() to check the type of each of the following: 5,
5.0, "5", [5], (5,), {5}, {"a": 5}, None.
• Exercise Set
1. Write a program that stores your name, department, and CGPA in three variables
and prints them using an f-string.
2. Predict the output type of 7 / 2 versus 7 // 2. Verify in the interpreter.
3. Write a program that takes two numbers as input and prints their sum, difference,
product, and quotient.
4. Explain, in one sentence, why Python is described as “dynamically typed”.
7
Python Programming for AI & Data Analytics CHAPTER 1. INTRODUCTION TO PYTHON
1.10 Summary
8
Chapter 2
Lists
Learning Objectives
➤ Explain what a list is and how it differs from other sequence types.
➤ Create, index, slice, and iterate over lists.
➤ Apply the core list methods to add, remove, sort, and search elements.
➤ Use list comprehensions to build lists concisely.
➤ Work with nested lists and 2-D data (matrices).
DEFINITION — List
Think of a list like a shopping cart at a supermarket: you can keep adding items, remove
something you changed your mind about, or reorder items – the cart itself remains the
same object throughout.
9
Python Programming for AI & Data Analytics CHAPTER 2. LISTS
2.3 Mutability
Unlike tuples, list contents can be changed in place after creation.
Because lists are mutable, assigning one list variable to another does not copy it – both
names point to the same object.
a = [1 , 2 , 3]
b = a
b . append (4)
print ( a ) # [1 , 2 , 3 , 4] -- 'a ' changed too !
Use b = [Link]() or b = a[:] to make an independent copy.
subjects = [ " DL " , " GML " , " PE " , " SC " , " PY " ]
subjects [0] # ' DL '
subjects [ -1] # ' PY '
subjects [1:4] # [ ' GML ', ' PE ', ' SC ']
10
Python Programming for AI & Data Analytics CHAPTER 2. LISTS
subjects [:: -1] # [ ' PY ', ' SC ', ' PE ', ' GML ', ' DL ']
subjects [1:3] = [ " ML " , " PROB " ] # slice assignment -- replaces a
range
Method Effect
append(x) Adds x to the end
insert(i, x) Inserts x at index i
extend(iter) Appends all items from another iterable
remove(x) Removes the first occurrence of x
pop(i) Removes and returns item at index i (default: last)
clear() Removes all elements
sort() Sorts the list in place
reverse() Reverses the list in place
count(x) Counts occurrences of x
index(x) Returns index of first occurrence of x
nums = [4 , 8 , 15 , 16 , 23 , 42]
nums . append (50) # [4 , 8 , 15 , 16 , 23 , 42 , 50]
nums . remove (8) # [4 , 15 , 16 , 23 , 42 , 50]
nums . pop () # returns 50; list becomes [4 , 15 , 16 ,
23 , 42]
nums . sort () # [4 , 15 , 16 , 23 , 42]
nums . sort ( reverse = True ) # [42 , 23 , 16 , 15 , 4]
nums . insert (0 , 99) # [99 , 42 , 23 , 16 , 15 , 4]
[Link]() sorts in place and returns None. The built-in sorted(list) returns a new
sorted list, leaving the original unchanged – useful when you still need the original order
elsewhere.
11
Python Programming for AI & Data Analytics CHAPTER 2. LISTS
EXAMPLE — Comprehensions
upper_names = [ name . upper () for name in [ " anya " , " kavin " , " ravi " ]]
# [ ' ANYA ', ' KAVIN ', ' RAVI ']
students = [ " Anya " , " Kavin " , " Ravi " ]
12
Python Programming for AI & Data Analytics CHAPTER 2. LISTS
• Try It Yourself
Given data = [10, 20, 30, 40, 50], write code to: (1) append 60; (2) remove the value
30; (3) insert 25 at index 2; (4) produce a new sorted-descending list without modifying
the original.
• Exercise Set
1. Write a list comprehension that returns the squares of only the even numbers from
1 to 20.
2. Given records = [["CSE", 120], ["AIDA", 90], ["ECE", 110]], write code that
prints the department with the highest strength.
3. Explain the difference between remove() and pop() with an example for each.
4. Write a function that flattens a 2-D list (a list of lists) into a single 1-D list using a
nested comprehension.
2.11 Summary
13
Chapter 3
Tuples
Learning Objectives
➤ Explain what a tuple is and why immutability matters for data safety.
➤ Construct tuples using literals, packing, and the tuple() constructor.
➤ Apply tuple packing, unpacking, and star-unpacking in real code.
➤ Decide confidently when to choose a tuple over a list.
A tuple is a built-in Python sequence type that is ordered, immutable, heterogeneous, and
indexed. Once created, its contents cannot be added to, removed, or replaced.
point = (4 , 7 , 9)
student = ( " Anya " , 21 , " AIDA " )
print ( type ( point ) ) # < class ' tuple '>
A tuple is like a printed examination hall ticket: the roll number, name, and seat are fixed
together at printing time. Once printed, the fields can only be read, never edited.
14
Python Programming for AI & Data Analytics CHAPTER 3. TUPLES
(5) is not a tuple – it is the integer 5 wrapped in parentheses. Only a trailing comma, as
in (5,), makes Python treat it as a one-element tuple.
3.3 Immutability
Immutability applies to the tuple’s references, not necessarily to the objects it contains. If
a tuple holds a mutable object such as a list, that inner list can still be modified in place:
record = ( " Kavin " , [85 , 90 , 78])
record [1]. append (100)
print ( record ) # ( ' Kavin ', [85 , 90 , 78 , 100])
EXAMPLE — Operations
a , b = (1 , 2) , (3 , 4)
a + b # (1 , 2 , 3 , 4)
( " hi " ,) * 3 # ( ' hi ', ' hi ', ' hi ')
15
Python Programming for AI & Data Analytics CHAPTER 3. TUPLES
16 in (4 , 8 , 15 , 16 , 23 , 42) # True
sorted ((4 , 8 , 15 , 16) ) # returns a LIST , not a tuple
NOTE
Because tuples are immutable, there are no append(), remove(), insert(), or sort()
methods. Only count() and index() are available.
point = 4 , 7 , 9 # packing
x , y , z = point # unpacking
a , b = 5 , 10
a, b = b, a # classic swap -- no temp variable
needed
print (a , b ) # 10 5
matrix = ((1 , 2) , (3 , 4) , (5 , 6) )
print ( matrix [2][0]) # 5
16
Python Programming for AI & Data Analytics CHAPTER 3. TUPLES
• Try It Yourself
Given records = (("CSE", 120), ("AIDA", 90), ("ECE", 110)), write one line of
code that prints the strength of the AIDA department using indexing only.
• Exercise Set
3.9 Summary
17
Chapter 4
Dictionaries
Learning Objectives
DEFINITION — Dictionary
student = { " name " : " Anya " , " age " : 21 , " dept " : " AIDA " }
print ( type ( student ) ) # < class ' dict '>
print ( student [ " name " ]) # ' Anya '
A dictionary is like a real paper dictionary or a phone contact list: you look up a word
(the key) to find its meaning (the value) – you never say “give me entry number 5”.
18
Python Programming for AI & Data Analytics CHAPTER 4. DICTIONARIES
student = { " name " : " Anya " , " age " : 21}
student [ " dept " ] = " AIDA " # add a new key
student [ " age " ] = 22 # update an existing key
Using student["gpa"] on a missing key raises a KeyError and stops the program. Prefer
[Link]("gpa") (or with a default) when the key might not exist – this is one of the
most frequent beginner mistakes when processing real data.
Method Effect
keys() Returns a view of all keys
values() Returns a view of all values
items() Returns a view of all (key, value) pairs
get(k, default) Safe lookup with an optional default
update(other) Merges another dict (or key=value pairs) into this one
pop(k) Removes key k and returns its value
setdefault(k, d) Returns student[k], inserting d if absent
clear() Removes all entries
19
Python Programming for AI & Data Analytics CHAPTER 4. DICTIONARIES
print ( list ( scores . keys () ) ) # [ ' Anya ', ' Kavin ', ' Ravi ']
print ( list ( scores . values () ) ) # [93 , 87 , 95]
scores = { " Anya " : 91 , " Kavin " : 87 , " Ravi " : 95}
EXAMPLE — Comprehensions
pass_only = { name : mark for name , mark in scores . items () if mark >=
90}
# { ' Anya ': 91 , ' Ravi ': 95}
20
Python Programming for AI & Data Analytics CHAPTER 4. DICTIONARIES
students = {
" S101 " : { " name " : " Anya " , " dept " : " AIDA " , " cgpa " : 8.7} ,
" S102 " : { " name " : " Kavin " , " dept " : " CSE " , " cgpa " : 9.1} ,
}
print ( students [ " S101 " ][ " cgpa " ]) # 8.7
Dictionaries are the natural Python representation of JSON data – the same nested key-
value structure returned by most web APIs. Mastering dictionaries directly prepares you
for working with real-world datasets and API responses.
• Try It Yourself
Given inventory = {"pen": 50, "pencil": 30, "eraser": 20}, write code to: (1)
add "ruler": 15; (2) safely look up "marker" with a default of 0; (3) print all items
whose count is above 25 using a dictionary comprehension.
• Exercise Set
1. Write a program that counts the frequency of each character in a string using a dic-
tionary.
2. Explain the difference between dict["key"] and [Link]("key") with an example
where the key is missing.
3. Given two lists names and marks of equal length, build a dictionary mapping each
name to its mark using zip().
4. Merge two dictionaries d1 and d2 so that values in d2 override matching keys in d1.
4.9 Summary
21
Python Programming for AI & Data Analytics CHAPTER 4. DICTIONARIES
• Dictionaries mirror JSON structure, making them essential for real-world data and
API work in AI/Data Analytics.
22
Chapter 5
Sets
Learning Objectives
➤ Explain what a set is and why it stores only unique, unordered elements.
➤ Create sets and apply core set methods.
➤ Perform mathematical set operations: union, intersection, difference, symmetric difference.
➤ Distinguish between set and frozenset.
➤ Recognise real-world use cases for sets in data cleaning and analysis.
DEFINITION — Set
A set is like a guest list where each name can appear only once, no matter how many
times someone tries to add it – and the order the names were written in does not matter.
23
Python Programming for AI & Data Analytics CHAPTER 5. SETS
{} creates an empty dictionary, not an empty set. To create an empty set you must use
set().
NOTE
Because sets are unordered, there is no indexing (ids[0] raises a TypeError) and pop()
removes an arbitrary element, not a specific one.
24
Python Programming for AI & Data Analytics CHAPTER 5. SETS
aida_students = { " Anya " , " Kavin " , " Ravi " , " Priya " }
cse_students = { " Ravi " , " Priya " , " Meena " }
nums = {4 , 8 , 15 , 16 , 23 , 42}
16 in nums # True -- membership testing in a set is very fast
len ( nums ) # 6
Sets are implemented using hash tables, so checking membership (x in my_set) is, on
average, much faster than checking membership in a list of the same size – an important
consideration when working with large datasets.
EXAMPLE — frozenset
25
Python Programming for AI & Data Analytics CHAPTER 5. SETS
• Try It Yourself
• Exercise Set
1. Write a program that removes duplicate values from a list while preserving no par-
ticular order, using a set.
2. Given two lists of student roll numbers for two courses, find students enrolled in
both courses using set intersection.
3. Explain why {} does not create an empty set, and show the correct syntax.
4. Explain, with an example, why a frozenset can be used as a dictionary key while a
regular set cannot.
26
Python Programming for AI & Data Analytics CHAPTER 5. SETS
5.9 Summary
“If you only care whether something is there, and only once, make it a set.”
27
Chapter 6
Conditional Statements
Learning Objectives
A conditional statement evaluates a boolean expression and executes one of several pos-
sible code blocks depending on the result. Python’s conditional keywords are if, elif
(else-if), and else.
Falsy Truthy
False, None, 0, 0.0 Any non-zero number
"" (empty string) Any non-empty string
[], (), {}, set() Any non-empty collection
cart = []
if cart :
print ( " You have items in your cart " )
else :
print ( " Your cart is empty " ) # this branch runs -- [] is falsy
28
Python Programming for AI & Data Analytics CHAPTER 6. CONDITIONAL STATEMENTS
EXAMPLE — Basic if
marks = 85
if marks >= 40:
print ( " Pass " )
6.4 if-else
EXAMPLE — if-else
marks = 32
if marks >= 40:
print ( " Pass " )
else :
print ( " Fail " )
6.5 if-elif-else
Use elif to test several conditions in sequence. Only the first branch whose condition is True
runs; the rest are skipped.
cgpa = 8.7
if cgpa >= 9.0:
grade = " O "
elif cgpa >= 8.0:
grade = " A + "
elif cgpa >= 7.0:
grade = " A "
else :
grade = " B "
print ( grade ) # 'A + '
29
Python Programming for AI & Data Analytics CHAPTER 6. CONDITIONAL STATEMENTS
EXAMPLE — Nested if
age = 20
has_id = True
if not has_id :
print ( " ID required " )
Python stops evaluating an and chain as soon as one operand is False, and stops an or
chain as soon as one operand is True. This is useful for guarding against errors, e.g. lst
and lst[0] avoids an index error on an empty list.
30
Python Programming for AI & Data Analytics CHAPTER 6. CONDITIONAL STATEMENTS
marks = 55
status = " Pass " if marks >= 40 else " Fail "
print ( status ) # ' Pass '
# Equivalent to :
if marks >= 40:
status = " Pass "
else :
status = " Fail "
EXAMPLE — match-case
• Try It Yourself
• Exercise Set
31
Python Programming for AI & Data Analytics CHAPTER 6. CONDITIONAL STATEMENTS
short-circuit evaluation.
6.11 Summary
32
Chapter 7
Loops
Learning Objectives
➤ Explain the difference between definite (for) and indefinite (while) iteration.
➤ Use range() effectively to control for loops.
➤ Apply break, continue, and the loop else clause.
➤ Write nested loops for 2-D data processing.
➤ Use looping idioms: enumerate(), zip(), and comprehensions.
DEFINITION — Loop
33
Python Programming for AI & Data Analytics CHAPTER 7. LOOPS
7.2.1 range()
range(n) produces values from 0 to n-1, not n. This off-by-one confusion is one of the
most frequent beginner mistakes.
count = 0
while count < 5:
print ( count )
count += 1
total = 0
value = int ( input ( " Enter a number ( -1 to stop ) : " ) )
while value != -1:
total += value
value = int ( input ( " Enter a number ( -1 to stop ) : " ) )
print ( " Total : " , total )
A while loop’s condition must eventually become False. Forgetting to update the loop
variable (e.g. omitting count += 1) produces an infinite loop that never terminates.
34
Python Programming for AI & Data Analytics CHAPTER 7. LOOPS
EXAMPLE — for-else
def is_prime ( n ) :
for i in range (2 , n ) :
if n % i == 0:
break
else :
return True # runs only if no divisor was found ( no break )
return False
for i in range (1 , 4) :
for j in range (1 , 4) :
print ( i * j , end = " \ t " )
print () # newline after each row
# 1 2 3
35
Python Programming for AI & Data Analytics CHAPTER 7. LOOPS
# 2 4 6
# 3 6 9
names = [ " Anya " , " Kavin " , " Ravi " ]
scores = [91 , 87 , 95]
for name , score in zip ( names , scores ) :
print ( f " { name }: { score } " )
# Loop version
squares = []
for n in range (1 , 6) :
squares . append ( n ** 2)
36
Python Programming for AI & Data Analytics CHAPTER 7. LOOPS
• Try It Yourself
Write a while loop that prints the Fibonacci sequence up to (but not exceeding) 100. Then
write a for loop using break that finds the first number in a list divisible by both 3 and 5.
• Exercise Set
1. Write a program that prints all prime numbers between 2 and 50 using nested loops.
2. Write a program using while that reverses a positive integer without converting it
to a string.
3. Use continue to print all numbers from 1 to 30 that are not multiples of 3.
4. Explain, with an example, what the else clause of a for loop does and when it runs.
7.10 Summary
• for loops iterate over a known sequence; while loops repeat based on a condition.
• break exits a loop early; continue skips to the next iteration.
• The loop else clause runs only when the loop finishes without a break.
• enumerate() and zip() are the idiomatic ways to get indices and pair up parallel
sequences.
37
Chapter 8
String Manipulation
Learning Objectives
DEFINITION — String
A string (str) is a built-in Python sequence type that is ordered, immutable, and indexed,
where each element is a single character (Python has no separate “character” type).
NOTE — Immutability
Like tuples, strings cannot be changed in place. name[0] = "P" raises a TypeError. Any
“modification” method (such as .upper()) actually returns a brand-new string, leaving
the original unchanged.
38
Python Programming for AI & Data Analytics CHAPTER 8. STRING MANIPULATION
Method Effect
upper(), lower() Convert case
strip(), lstrip(), rstrip() Remove leading/trailing whitespace
replace(old, new) Replace all occurrences of a substring
split(sep) Split into a list of substrings
join(iterable) Join an iterable of strings using this string as separator
find(sub) Index of first occurrence, or -1
startswith(sub), endswith(sub) Boolean prefix/suffix test
isdigit(), isalpha(), isalnum() Content type checks
title(), capitalize() Title-case / sentence-case conversion
39
Python Programming for AI & Data Analytics CHAPTER 8. STRING MANIPULATION
" -" . join ([ " 2026 " , " 08 " , " 16 " ]) # '2026 -08 -16 '
split() and join() are the two most-used string operations in data preprocessing: pars-
ing raw CSV/log lines into fields, and reassembling cleaned tokens back into a single
line.
print ( f " { name ! r } " ) # " ' Anya '" -- repr form
print ( f " {2 ** 10 = } " ) # '2 ** 10 = 1024 ' -- self -
documenting expression
40
Python Programming for AI & Data Analytics CHAPTER 8. STRING MANIPULATION
vowel_count = 0
for ch in " Artificial Intelligence " . lower () :
if ch in " aeiou " :
vowel_count += 1
print ( vowel_count )
• Try It Yourself
Given sentence = " Data Science is Powerful ", write code to: (1) strip whitespace;
(2) convert to lowercase; (3) split into a list of words; (4) count how many words contain
the letter "s".
• Exercise Set
1. Write a function that checks whether a given string is a palindrome, ignoring case
and spaces.
2. Given a full name "Anya Rani Rao", extract the initials "A.R.R." using split() and
string slicing.
3. Write a program that counts the number of vowels and consonants in a sentence.
4. Use an f-string to format a table row: name (left-aligned, 10 chars), CGPA (2 decimal
41
Python Programming for AI & Data Analytics CHAPTER 8. STRING MANIPULATION
places).
8.11 Summary
42
Chapter 9
➤ Define and call functions with positional, keyword, and default arguments.
➤ Use *args and **kwargs for flexible function signatures.
➤ Explain variable scope (local vs. global) and return values.
➤ Write lambda functions and use them with map(), filter(), and sorted().
➤ Organise code into modules and import them using various import styles.
DEFINITION — Function
A function is a block of organised, reusable code defined with the def keyword that op-
tionally accepts input (parameters) and optionally produces output (a return value).
def square ( n ) :
return n ** 2
43
Python Programming for AI & Data Analytics CHAPTER 9. FUNCTIONS AND MODULES
A function with no explicit return statement returns None by default. This is distinct from
print(), which displays output but does not hand a value back to the caller.
total (1 , 2 , 3) # 6
total (1 , 2 , 3 , 4 , 5) # 15
build_profile ( name = " Anya " , dept = " AIDA " , year =2)
# { ' name ': ' Anya ', ' dept ': ' AIDA ', ' year ': 2}
44
Python Programming for AI & Data Analytics CHAPTER 9. FUNCTIONS AND MODULES
The names args and kwargs are convention, not syntax – the important part is the * and
** prefixes. *args always packs into a tuple; **kwargs always packs into a dict.
DEFINITION — Scope
Scope determines where a variable is visible. A variable created inside a function is local
to that function; a variable created outside any function is global and readable (but not
writable without the global keyword) from inside functions.
counter = 0 # global
def increment () :
global counter # required to MODIFY a global
inside a function
counter += 1
increment ()
print ( counter ) # 1
DEFINITION — Lambda
square = lambda n : n ** 2
square (6) # 36
students = [( " Anya " , 91) , ( " Kavin " , 87) , ( " Ravi " , 95) ]
students . sort ( key = lambda s : s [1] , reverse = True )
# [( ' Ravi ', 95) , ( ' Anya ', 91) , ( ' Kavin ', 87) ]
45
Python Programming for AI & Data Analytics CHAPTER 9. FUNCTIONS AND MODULES
nums = [1 , 2 , 3 , 4 , 5]
Most Python style guides prefer list comprehensions over map()/filter() for readability:
[n * 2 for n in nums] is equivalent to map above. map/filter remain common when
passing an already-defined function.
9.6 Docstrings
9.7 Modules
A module is simply a .py file containing Python definitions that can be reused across pro-
grams. Python also ships with a large standard library of ready-made modules.
DEFINITION — Module
A module is a file of Python code (functions, classes, variables) that can be imported into
another program using the import statement, enabling code reuse across files.
import math
math . sqrt (16) # 4.0
import math as m
46
Python Programming for AI & Data Analytics CHAPTER 9. FUNCTIONS AND MODULES
m . pi # 3.14159...
import random
random . randint (1 , 6) # random integer , e . g . simulating a
dice roll
import datetime
datetime . date . today () # today 's date
import os
os . listdir ( " . " ) # list files in the current
directory
import statistics
statistics . mean ([88 , 92 , 79]) # 86.333...
EXAMPLE — [Link]
PI_APPROX = 3.14159
EXAMPLE — [Link]
47
Python Programming for AI & Data Analytics CHAPTER 9. FUNCTIONS AND MODULES
Code placed under if __name__ == "__main__": runs only when the file is executed
directly, not when it is imported as a module elsewhere – this lets a file serve as both a
reusable module and a standalone script.
def main () :
print ( " Running as a script " )
• Try It Yourself
• Exercise Set
9.10 Summary
• Functions are defined with def, may take positional, keyword, default, *args, and
**kwargs parameters, and optionally return a value.
• Variables inside a function are local by default; the global keyword is required to
modify a global variable from within a function.
• Lambda functions provide concise, anonymous one-expression functions, often
paired with map(), filter(), or sorted().
• Modules let code be organised across files and reused via import; Python’s standard
library ships many ready-made modules.
“Namespaces are one honking great idea – let’s do more of those!” — The Zen of Python
48
Chapter 10
File Handling
Learning Objectives
➤ Open, read, write, and close files safely using open() and with.
➤ Distinguish between file modes: read, write, append, and binary.
➤ Read files line by line and process large files efficiently.
➤ Work with structured file formats: CSV and JSON.
➤ Handle file-related errors gracefully using try-except.
File handling refers to the set of operations – opening, reading, writing, appending, and
closing – that let a Python program interact with files stored on disk.
f = open ( " students . txt " , " r " ) # open in read mode
content = f . read ()
f . close () # must be closed explicitly to
free resources
Forgetting [Link]() can leave file handles open, leading to resource leaks or data not
being flushed to disk. The with statement (next section) solves this automatically and is
the recommended approach.
49
Python Programming for AI & Data Analytics CHAPTER 10. FILE HANDLING
Mode Meaning
"r" Read (default) – error if the file does not exist
"w" Write – creates the file, overwrites if it already exists
"a" Append – creates the file if absent, adds to the end otherwise
"x" Exclusive creation – error if the file already exists
"rb", "wb" Binary read / write (e.g. images)
"r+" Read and write
Opening a file in "w" mode instantly erases its existing content. Use "a" if you intend to
add to a file without destroying what is already there.
50
Python Programming for AI & Data Analytics CHAPTER 10. FILE HANDLING
For very large files (multi-gigabyte log files or datasets), [Link]() loads the entire file into
memory at once. Iterating for line in f processes one line at a time, keeping memory
usage constant regardless of file size.
lines = [ " Row 1\ n " , " Row 2\ n " , " Row 3\ n " ]
with open ( " output . txt " , " w " ) as f :
f . writelines ( lines )
import csv
51
Python Programming for AI & Data Analytics CHAPTER 10. FILE HANDLING
with open ( " students . csv " , " w " , newline = " " ) as f :
writer = csv . writer ( f )
writer . writerow ([ " Name " , " Dept " , " CGPA " ])
writer . writerow ([ " Anya " , " AIDA " , 8.7])
import json
data = { " name " : " Anya " , " dept " : " AIDA " , " scores " : [88 , 92 , 79]}
52
Python Programming for AI & Data Analytics CHAPTER 10. FILE HANDLING
import os
try :
with open ( " missing . txt " ) as f :
content = f . read ()
except FileNotFoundError :
print ( " The file does not exist . " )
Wrapping file operations in try-except is the professional standard: file systems are ex-
ternal to your program, and files can be missing, locked, or unreadable for reasons outside
your control. Never assume a file operation will succeed.
toppers = []
with open ( " students . csv " , newline = " " ) as f :
for row in csv . DictReader ( f ) :
if float ( row [ " CGPA " ]) >= 8.5:
toppers . append ( row )
• Try It Yourself
Write a program that reads a text file line by line, counts the number of lines, words,
and characters (like the Unix wc command), and writes the result to a new file named
[Link].
53
Python Programming for AI & Data Analytics CHAPTER 10. FILE HANDLING
• Exercise Set
1. Write a program that copies the contents of one text file into another, converting all
text to uppercase.
2. Read a CSV file of student records and print only the names of students with a CGPA
above 8.0, using [Link].
3. Write a Python dictionary representing a student profile to a JSON file, then read it
back and print one field.
4. Write a program that safely attempts to open a file the user names, handling both
FileNotFoundError and PermissionError.
10.12 Summary
54