0% found this document useful (0 votes)
2 views55 pages

ModuleI_HandsOnPython

This document serves as a teaching resource for foundational Python programming, covering topics such as data types, control flow, and file handling. It includes sections on lists, tuples, dictionaries, and sets, along with practice exercises and summaries for each topic. The document is prepared by Ms. A.V. Geetha, Assistant Professor at the Department of AI & Data Analytics.

Uploaded by

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

ModuleI_HandsOnPython

This document serves as a teaching resource for foundational Python programming, covering topics such as data types, control flow, and file handling. It includes sections on lists, tuples, dictionaries, and sets, along with practice exercises and summaries for each topic. The document is prepared by Ms. A.V. Geetha, Assistant Professor at the Department of AI & Data Analytics.

Uploaded by

geethaav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA ANALYTICS

Sri Ramachandra Faculty of Engineering and Technology (SRET), SRIHER

Python Programming
Data Types, Control Flow, Strings, Functions & File Handling

Foundations for AI & Data Analytics Practice

scores = [88 , 92 , 79]


profile = { " name " : " Anya " , " dept " : " AIDA " }
unique_ids = {101 , 102 , 103}
coordinates = (12.9 , 80.2)

Ms. A.V. Geetha


Assistant Professor, Dept. of AI & Data Analytics

A teaching resource for foundational Python programming


Contents

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

9 Functions and Modules 43


9.1 Why Functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
9.2 Defining and Calling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
9.3 Parameters and Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
9.3.1 Default Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
9.3.2 Positional vs. Keyword Arguments . . . . . . . . . . . . . . . . . . . . . . 44
9.3.3 *args and **kwargs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
9.4 Variable Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
9.5 Lambda Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
9.5.1 map(), filter(), and sorted() with Lambdas . . . . . . . . . . . . . . . . . . . 46
9.6 Docstrings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
9.7 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
9.8 Creating and Using Your Own Module . . . . . . . . . . . . . . . . . . . . . . . . . 47
9.9 Practice Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
9.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

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.

1.1 What is Python?


Python is a high-level, interpreted, general-purpose programming language known for its
readable syntax and a vast ecosystem of libraries. It was created by Guido van Rossum and first
released in 1991. Today it is the dominant language in Artificial Intelligence, Machine Learn-
ing, and Data Analytics because of libraries such as NumPy, pandas, scikit-learn, TensorFlow,
and PyTorch.

DEFINITION — Python

Python is a dynamically typed, interpreted programming language that emphasises code


readability through significant whitespace (indentation). It supports multiple program-
ming paradigms: procedural, object-oriented, and functional.

NOTE — Why AI/Data Analytics Teams Prefer 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++.

1.2 Installing and Running Python


Python code can be executed in three common ways.

EXAMPLE — Three Ways to Run Python

# 1. Interactive interpreter ( REPL )


$ python3

4
Python Programming for AI & Data Analytics CHAPTER 1. INTRODUCTION TO PYTHON

>>> print ( " Hello , AIDA ! " )


Hello , AIDA !

# 2. Running a script file


$ python3 analysis . py

# 3. Inside a Jupyter Notebook cell


print ( " Hello , AIDA ! " )

1.3 Your First Program

EXAMPLE — Hello World

print ( " Hello , World ! " )


print ( " Welcome to AI & Data Analytics " )

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.

1.4 Indentation and Comments


Unlike languages such as C or Java that use curly braces {} to mark blocks of code, Python
uses indentation (whitespace at the start of a line) to define blocks. This is not a stylistic choice
— it is a syntax rule.

EXAMPLE — Indentation Defines Blocks

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

NOTE — Common Pitfall

Mixing tabs and spaces, or using inconsistent indentation levels, raises an


IndentationError. Most editors (VS Code, PyCharm, Jupyter) are configured to insert
four spaces per indentation level by convention — stick to this standard.

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 single - line comment


x = 10 # comments can also follow code on the same line

"""
This is a multi - line string ,
often used as a block comment or docstring .
"""

1.5 Variables and Dynamic Typing


A variable is a name bound to a value stored in memory. Python is dynamically typed: you do
not declare a variable’s type in advance, and the same name can be re-bound to a value of a
different type.

EXAMPLE — Declaring Variables

student_name = " Anya " # str


cgpa = 8.7 # float
year = 2026 # int
is_placed = False # bool

student_name = 21 # re - binding to a different type is legal


print ( type ( student_name ) ) # < class ' int '>

NOTE — Naming Rules

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.

1.6 Basic Input and Output

EXAMPLE — input() and print()

name = input ( " Enter your name : " ) # input () always returns a
str
age = int ( input ( " Enter your age : " ) ) # cast explicitly when a
number is needed

print ( " Name : " , name )


print ( f " Age next year : { age + 1} " ) # f - string formatting

6
Python Programming for AI & Data Analytics CHAPTER 1. INTRODUCTION TO PYTHON

1.7 Python’s Core Data Types at a Glance


Python organises data using a small set of built-in types. The remainder of this book studies
the composite (collection) types in depth — this table is a map of where we are headed.

Category Type Example


Numeric int, float, complex 7, 3.14, 2+3j
Text str "AIDA"
Boolean bool True, False
Sequence list, tuple [1,2,3], (1,2,3)
Mapping dict {"id": 101}
Set set, frozenset {1,2,3}
None type NoneType None

• 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.

1.8 Operators, Briefly

Category Operators Example


Arithmetic + - * / // % ** 17 // 4 → 4
Comparison == != > < >= <= 5 == 5 → True
Logical and or not True and False → False
Assignment = += -= *= /= x += 1
Membership in, not in 3 in [1,2,3] → True
Identity is, is not x is None

1.9 Practice Exercises

• 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

DEFINITION — Key Takeaways

• Python is an interpreted, dynamically typed, general-purpose language central to


modern AI and Data Analytics tooling.
• Code blocks are defined by indentation, not braces.
• Variables are names bound to values; no type declaration is required.
• Python’s core collection types — list, tuple, dict, and set — are the building
blocks studied in the chapters that follow.

“Readability counts.” — The Zen of Python

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).

2.1 What is a List?


A list is an ordered, mutable collection of items, written as comma-separated values enclosed
in square brackets [ ].

DEFINITION — List

A list is a built-in Python sequence type that is:


• Ordered — items retain the position in which they were inserted.
• Mutable — elements can be added, removed, or changed after creation.
• Heterogeneous — elements can be of different data types.
• Indexed — elements are accessed using zero-based integer positions.

EXAMPLE — Your First List

scores = [88 , 92 , 79 , 95]


mixed = [ " AIDA " , 2026 , True , 3.5]
print ( type ( scores ) ) # < class ' list '>

NOTE — Everyday Analogy

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.2 Creating Lists

EXAMPLE — Ways to Create a List

empty = [] # empty list


single = [5] # single - element list -- no
trailing comma needed
coords = [10.0 , 20.5] # two - element list
from_tuple = list ((1 , 2 , 3) ) # converting a tuple
from_str = list ( " SRET " ) # [ ' S ', 'R ', 'E ', 'T ']
from_range = list ( range (5) ) # [0 , 1 , 2 , 3 , 4]
repeated = [0] * 5 # [0 , 0 , 0 , 0 , 0]

2.3 Mutability
Unlike tuples, list contents can be changed in place after creation.

EXAMPLE — Mutating a List

marks = [78 , 90 , 65]


marks [0] = 100
print ( marks ) # [100 , 90 , 65]

marks . append (88)


print ( marks ) # [100 , 90 , 65 , 88]

NOTE — A Subtlety Worth Knowing

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.

2.4 Indexing and Slicing


List indexing and slicing work exactly like tuple indexing and slicing.

EXAMPLE — Indexing and Slicing

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

2.5 List Methods

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

EXAMPLE — Core Methods in Action

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]

NOTE — sort() vs sorted()

[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.

2.6 List Comprehensions


A list comprehension builds a new list from an existing iterable in a single, readable line.

DEFINITION — List Comprehension

[expression for item in iterable if condition]


The if condition clause is optional.

11
Python Programming for AI & Data Analytics CHAPTER 2. LISTS

EXAMPLE — Comprehensions

squares = [ n ** 2 for n in range (1 , 6) ]


# [1 , 4 , 9 , 16 , 25]

evens = [ n for n in range (20) if n % 2 == 0]


# [0 , 2 , 4 , ... , 18]

upper_names = [ name . upper () for name in [ " anya " , " kavin " , " ravi " ]]
# [ ' ANYA ', ' KAVIN ', ' RAVI ']

grid = [[ r * 3 + c for c in range (3) ] for r in range (3) ]


# [[0 , 1 , 2] , [3 , 4 , 5] , [6 , 7 , 8]]

2.7 Nested Lists and Matrices

EXAMPLE — Working with Nested Lists

matrix = [[1 , 2] , [3 , 4] , [5 , 6]]


print ( matrix [2][0]) # 5

for row in matrix :


print ( row )
# [1 , 2]
# [3 , 4]
# [5 , 6]

# Flattening a nested list


flat = [ value for row in matrix for value in row ]
# [1 , 2 , 3 , 4 , 5 , 6]

2.8 Iterating Over Lists

EXAMPLE — Looping Patterns

students = [ " Anya " , " Kavin " , " Ravi " ]

for name in students :


print ( name )

for i , name in enumerate ( students , start =1) :


print (i , name )

scores = [91 , 87 , 95]


for name , score in zip ( students , scores ) :
print ( f " { name } scored { score } " )

12
Python Programming for AI & Data Analytics CHAPTER 2. LISTS

2.9 List vs. Tuple

Aspect List Tuple


Mutability Mutable Immutable
Syntax [ ] ( )
Performance Slower, heavier Faster, lighter
Methods Many (append, sort, ...) count(), index()
Usable as dict key No Yes (if hashable)
Best suited for Growing collections Fixed records

• 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.

2.10 Practice Exercises

• 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

DEFINITION — Key Takeaways

• A list is an ordered, mutable, heterogeneous sequence written with [ ].


• Lists support a rich set of methods (append, remove, sort, . . . ) because they are
designed to be modified.
• List comprehensions offer a concise, Pythonic way to build lists from iterables.
• Choose a list over a tuple whenever the data represents a growing or changing col-
lection rather than a fixed record.

“If it needs to grow or change, make it a list.”

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.

3.1 What is a Tuple?


A tuple is an ordered, immutable collection of items, conventionally enclosed in parentheses
( ).
DEFINITION — Tuple

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.

EXAMPLE — Your First Tuple

point = (4 , 7 , 9)
student = ( " Anya " , 21 , " AIDA " )
print ( type ( point ) ) # < class ' tuple '>

NOTE — Everyday Analogy

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

3.2 Creating Tuples

EXAMPLE — Ways to Create a Tuple

empty = () # empty tuple


single = (5 ,) # single - element tuple -- comma
required !
not_tuple = (5) # this is just the integer 5
no_parens = 1 , 2 , 3 # parentheses are optional
from_list = tuple ([1 , 2 , 3]) # converting a list
from_range = tuple ( range (5) ) # converting a range

NOTE — Common Pitfall

(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

EXAMPLE — Immutability in Action

marks = (78 , 90 , 65)


marks [0] = 100
# Traceback ( most recent call last ) :
# TypeError : ' tuple ' object does not support item assignment

NOTE — A Subtlety Worth Knowing

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])

3.4 Indexing, Slicing, and Operations


Tuples support the same indexing, slicing, concatenation, repetition, and membership opera-
tions as lists.

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.

3.5 Packing and Unpacking


Packing groups comma-separated values into a tuple automatically; unpacking assigns a tu-
ple’s elements to individual variables in one statement.

EXAMPLE — Packing, Unpacking, and Swap

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

first , * rest = (1 , 2 , 3 , 4) # star - unpacking


print ( first , rest ) # 1 [2 , 3 , 4]

EXAMPLE — Functions Returning Multiple Values

def stats ( nums ) :


return min ( nums ) , max ( nums ) , sum ( nums ) / len ( nums )

lowest , highest , average = stats ((78 , 90 , 65 , 88) )


A function that appears to “return multiple values” is really returning one packed tuple.

3.6 Nested Tuples and Tuples as Dictionary Keys

EXAMPLE — Nested Tuples

matrix = ((1 , 2) , (3 , 4) , (5 , 6) )
print ( matrix [2][0]) # 5

distance = {(0 , 0) : 0.0 , (1 , 1) : 1.41} # tuples used as dict keys


print ( distance [(1 , 1) ]) # 1.41

16
Python Programming for AI & Data Analytics CHAPTER 3. TUPLES

A list could never be used as a dictionary key – lists are unhashable.

3.7 Tuple vs. List

Aspect Tuple List


Mutability Immutable Mutable
Performance Faster, lighter Slower, heavier
Methods count(), index() Many
Usable as dict key Yes (if hashable) No
Best suited for Fixed records Growing collections

• 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.

3.8 Practice Exercises

• Exercise Set

1. Why does t = (5) not create a tuple, while t = (5,) does?


2. Write a function student_record() that returns a name, CGPA, and department as
a tuple, then unpack the result into three variables.
3. Using star-unpacking, split (1, 2, 3, 4, 5) into its first element, last element, and
everything in between.

3.9 Summary

DEFINITION — Key Takeaways

• A tuple is an ordered, immutable, heterogeneous sequence.


• Tuples support only count() and index() as methods.
• Packing and unpacking enable clean multi-value assignment and function returns.
• Choose a tuple over a list whenever the data represents a fixed record.

“If it shouldn’t change, make it a tuple.”

17
Chapter 4

Dictionaries
Learning Objectives

➤ Explain what a dictionary is and why it is a key-value mapping.


➤ Create, access, update, and delete dictionary entries.
➤ Apply core dictionary methods used in real data-processing code.
➤ Iterate over keys, values, and key-value pairs.
➤ Use dictionary comprehensions to transform data concisely.

4.1 What is a Dictionary?


A dictionary stores data as key–value pairs. Instead of retrieving items by numeric position
(as in a list or tuple), you retrieve them by a unique, meaningful key.

DEFINITION — Dictionary

A dictionary (dict) is a built-in Python mapping type that is:


• Unordered by concept, ordered by insertion — since Python 3.7, dictionaries re-
member insertion order, but logically you should look up by key, not position.
• Mutable — entries can be added, updated, or removed.
• Keyed — every value is associated with a unique, hashable key.

EXAMPLE — Your First Dictionary

student = { " name " : " Anya " , " age " : 21 , " dept " : " AIDA " }
print ( type ( student ) ) # < class ' dict '>
print ( student [ " name " ]) # ' Anya '

NOTE — Everyday Analogy

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

4.2 Creating Dictionaries

EXAMPLE — Ways to Create a Dictionary

empty = {} # empty dict


literal = { " id " : 101 , " name " : " Kavin " } # dict literal
from_pairs = dict ([( " a " , 1) , ( " b " , 2) ]) # from a list of pairs
from_kwargs = dict ( name = " Ravi " , age =22) # from keyword arguments
zipped = dict ( zip ([ " a " , " b " ] , [1 , 2]) ) # from two parallel
iterables -- { ' a ': 1 , 'b ': 2}

4.3 Accessing, Updating, and Deleting

EXAMPLE — Basic Operations

student = { " name " : " Anya " , " age " : 21}

student [ " age " ] # 21 -- KeyError if the key is missing


student . get ( " gpa " ) # None -- get () never raises an error
student . get ( " gpa " , 0.0) # 0.0 -- default value if key is
missing

student [ " dept " ] = " AIDA " # add a new key
student [ " age " ] = 22 # update an existing key

del student [ " age " ] # remove a key


student . pop ( " dept " ) # removes and returns the value

NOTE — Common Pitfall

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.

4.4 Dictionary Methods

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

EXAMPLE — Core Methods in Action

scores = { " Anya " : 91 , " Kavin " : 87}


scores . update ({ " Ravi " : 95 , " Anya " : 93}) # existing key overwritten
print ( scores ) # { ' Anya ': 93 , ' Kavin ': 87 , ' Ravi ': 95}

print ( list ( scores . keys () ) ) # [ ' Anya ', ' Kavin ', ' Ravi ']
print ( list ( scores . values () ) ) # [93 , 87 , 95]

4.5 Iterating Over Dictionaries

EXAMPLE — Looping Patterns

scores = { " Anya " : 91 , " Kavin " : 87 , " Ravi " : 95}

for name in scores : # iterates over keys by default


print ( name )

for name , mark in scores . items () : # unpack key - value pairs


print ( f " { name } scored { mark } " )

for mark in scores . values () :


print ( mark )

4.6 Dictionary Comprehensions

DEFINITION — Dictionary Comprehension

{key_expr: value_expr for item in iterable if condition}

EXAMPLE — Comprehensions

squares = { n : n ** 2 for n in range (1 , 6) }


# {1: 1 , 2: 4 , 3: 9 , 4: 16 , 5: 25}

pass_only = { name : mark for name , mark in scores . items () if mark >=
90}
# { ' Anya ': 91 , ' Ravi ': 95}

inverted = { v : k for k , v in { " a " : 1 , " b " : 2}. items () }


# {1: 'a ', 2: 'b '}

20
Python Programming for AI & Data Analytics CHAPTER 4. DICTIONARIES

4.7 Nested Dictionaries

EXAMPLE — Working with Nested Dictionaries

students = {
" S101 " : { " name " : " Anya " , " dept " : " AIDA " , " cgpa " : 8.7} ,
" S102 " : { " name " : " Kavin " , " dept " : " CSE " , " cgpa " : 9.1} ,
}
print ( students [ " S101 " ][ " cgpa " ]) # 8.7

for sid , info in students . items () :


print ( sid , " ->" , info [ " name " ] , info [ " dept " ])

NOTE — Design Insight

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.

4.8 Practice Exercises

• 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

DEFINITION — Key Takeaways

• A dictionary is a mutable collection of unique keys mapped to values.


• Use .get() for safe lookups and .items() to iterate key-value pairs together.
• Dictionary comprehensions build new dictionaries concisely from existing iterables.

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.

“If you need to look things up by name, make it a dictionary.”

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.

5.1 What is a Set?


A set is an unordered collection of unique elements, written with curly braces { } or built
using the set() constructor.

DEFINITION — Set

A set is a built-in Python collection type that is:


• Unordered — elements have no fixed position and cannot be indexed.
• Mutable — elements can be added or removed (the set itself can change).
• Unique — duplicate elements are automatically discarded.
• Hashable elements only — items must be immutable types (numbers, strings, tu-
ples); a set cannot contain lists or dictionaries.

EXAMPLE — Your First Set

unique_ids = {101 , 102 , 103 , 102}


print ( unique_ids ) # {101 , 102 , 103} -- duplicate '102 '
dropped
print ( type ( unique_ids ) ) # < class ' set '>

NOTE — Everyday Analogy

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

5.2 Creating Sets

EXAMPLE — Ways to Create a Set

empty = set () # empty set -- NOT {} ( that creates


an empty dict !)
literal = {1 , 2 , 3}
from_list = set ([1 , 2 , 2 , 3]) # {1 , 2 , 3}
from_str = set ( " SRET " ) # { ' S ', 'R ', 'E ', 'T '}
comprehension = { n * n for n in range (5) } # set comprehension --
{0 , 1 , 4 , 9 , 16}

NOTE — Common Pitfall

{} creates an empty dictionary, not an empty set. To create an empty set you must use
set().

5.3 Adding and Removing Elements

EXAMPLE — Basic Operations

ids = {101 , 102}


ids . add (103) # {101 , 102 , 103}
ids . update ([104 , 105]) # adds multiple elements at once
ids . remove (101) # removes 101 -- raises KeyError if
absent
ids . discard (999) # removes if present , no error if
absent
ids . pop () # removes and returns an arbitrary
element

NOTE

Because sets are unordered, there is no indexing (ids[0] raises a TypeError) and pop()
removes an arbitrary element, not a specific one.

5.4 Mathematical Set Operations


Sets support the operations you know from set theory, both as operators and as named meth-
ods.

24
Python Programming for AI & Data Analytics CHAPTER 5. SETS

Operation Operator Method


Union a | b [Link](b)
Intersection a & b [Link](b)
Difference a - b [Link](b)
Symmetric Difference a  b a.symmetric_difference(b)
Subset test a <= b [Link](b)
Superset test a >= b [Link](b)

EXAMPLE — Set Operations in Action

aida_students = { " Anya " , " Kavin " , " Ravi " , " Priya " }
cse_students = { " Ravi " , " Priya " , " Meena " }

aida_students | cse_students # union -- everyone in either group


aida_students & cse_students # intersection -- students in BOTH
groups : { ' Ravi ', ' Priya '}
aida_students - cse_students # difference -- only in AIDA : { ' Anya
', ' Kavin '}
aida_students ^ cse_students # symmetric diff -- in exactly one
group , not both

5.5 Membership and Length

EXAMPLE — Membership Testing

nums = {4 , 8 , 15 , 16 , 23 , 42}
16 in nums # True -- membership testing in a set is very fast
len ( nums ) # 6

NOTE — Why Sets Are Fast

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.

5.6 set vs. frozenset


A frozenset is an immutable version of a set. It supports all the read-only set operations but
cannot be modified after creation, which also makes it hashable and usable as a dictionary key
or as an element of another set.

EXAMPLE — frozenset

fixed_ids = frozenset ({101 , 102 , 103})


fixed_ids . add (104) # AttributeError -- frozensets have no add ()

25
Python Programming for AI & Data Analytics CHAPTER 5. SETS

group_lookup = { frozenset ({1 , 2}) : " Group A " } # usable as a dict


key

5.7 Real-World Use Cases

EXAMPLE — Removing Duplicates from Data

readings = [23.5 , 24.0 , 23.5 , 25.1 , 24.0 , 23.5]


unique_readings = set ( readings )
print ( unique_readings ) # {23.5 , 24.0 , 25.1}

EXAMPLE — Finding Common Records Across Two Datasets

dataset_a_ids = set ( range (1 , 1000) )


dataset_b_ids = set ( range (500 , 1500) )
common_records = dataset_a_ids & dataset_b_ids # overlap between
two datasets

• Try It Yourself

Given a = {1, 2, 3, 4} and b = {3, 4, 5, 6}, predict the result of a & b, a | b, a -


b, and a  b before running them.

5.8 Practice Exercises

• 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

DEFINITION — Key Takeaways

• A set is an unordered, mutable collection of unique, hashable elements.


• Sets support fast membership testing and standard mathematical set operations:
union, intersection, difference, and symmetric difference.
• frozenset is the immutable counterpart, usable as a dict key or set element.
• Sets are ideal for de-duplication and comparing collections of records.

“If you only care whether something is there, and only once, make it a set.”

27
Chapter 6

Conditional Statements
Learning Objectives

➤ Explain how Python evaluates truthy and falsy values.


➤ Write if, if-else, and if-elif-else statements.
➤ Build nested conditionals and compound boolean conditions.
➤ Use the conditional (ternary) expression for concise assignments.
➤ Apply Python 3.10+ match-case for structured pattern matching.

6.1 What is a Conditional Statement?


Conditional statements let a program choose which block of code to execute based on whether
a condition is True or False.

DEFINITION — Conditional Statement

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.

6.2 Truthy and Falsy Values


Every Python object has an inherent boolean value when used in a condition.

Falsy Truthy
False, None, 0, 0.0 Any non-zero number
"" (empty string) Any non-empty string
[], (), {}, set() Any non-empty collection

EXAMPLE — Truthiness in Practice

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

6.3 The if Statement

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.

EXAMPLE — Grading System

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 + '

NOTE — Common Pitfall

Using a chain of independent if statements instead of elif means every condition is


checked, even after one has already matched – this can produce multiple branches ex-
ecuting when only one was intended.

29
Python Programming for AI & Data Analytics CHAPTER 6. CONDITIONAL STATEMENTS

6.6 Nested Conditionals

EXAMPLE — Nested if

age = 20
has_id = True

if age >= 18:


if has_id :
print ( " Entry allowed " )
else :
print ( " ID required " )
else :
print ( " Entry denied -- underage " )

6.7 Compound Conditions

EXAMPLE — and, or, not

age , has_id = 20 , True

if age >= 18 and has_id :


print ( " Entry allowed " )

cgpa , backlogs = 6.5 , 0


if cgpa >= 6.0 or backlogs == 0:
print ( " Eligible for placement drive " )

if not has_id :
print ( " ID required " )

NOTE — Short-Circuit Evaluation

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.

6.8 Conditional (Ternary) Expression

DEFINITION — Ternary Expression

value_if_true if condition else value_if_false

30
Python Programming for AI & Data Analytics CHAPTER 6. CONDITIONAL STATEMENTS

EXAMPLE — Ternary in Action

marks = 55
status = " Pass " if marks >= 40 else " Fail "
print ( status ) # ' Pass '

# Equivalent to :
if marks >= 40:
status = " Pass "
else :
status = " Fail "

6.9 Pattern Matching with match-case (Python 3.10+)


Python 3.10 introduced match-case, a structured alternative to long if-elif chains, especially
useful for matching against multiple discrete values or shapes of data.

EXAMPLE — match-case

def describe_grade ( grade ) :


match grade :
case " O " | " A + " :
return " Outstanding "
case " A " | " B " :
return " Good "
case _ : # '_ ' is the wildcard / default
case
return " Needs Improvement "

print ( describe_grade ( " A + " ) ) # ' Outstanding '

• Try It Yourself

Write an if-elif-else chain that classifies a temperature reading temp as "Freezing"


(≤ 0), "Cold" (1–15), "Mild" (16–25), or "Hot" (> 25). Then rewrite the same logic using
match-case.

6.10 Practice Exercises

• Exercise Set

1. Write a program that checks whether a number is positive, negative, or zero.


2. Write a program that determines if a given year is a leap year using compound
conditions.
3. Rewrite the following using a ternary expression: if x % 2 == 0: result =
"Even" else: result = "Odd".
4. Explain why [] and print("hi") does not print anything, using the concept of

31
Python Programming for AI & Data Analytics CHAPTER 6. CONDITIONAL STATEMENTS

short-circuit evaluation.

6.11 Summary

DEFINITION — Key Takeaways

• Conditionals route execution using if, elif, and else.


• Every object has a truthy/falsy value even outside explicit boolean expressions.
• and/or short-circuit; not inverts a boolean.
• The ternary expression offers a one-line alternative to simple if-else assignments.
• match-case (3.10+) offers structured, readable multi-branch matching.

“Explicit is better than implicit.” — The Zen of Python

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.

7.1 Why Loops?


Loops let a program repeat a block of code multiple times without duplicating it. Python
provides two loop constructs: for (iterate over a known sequence) and while (repeat while a
condition holds).

DEFINITION — Loop

A loop is a control-flow construct that repeatedly executes a block of statements. A for


loop iterates over the items of an iterable; a while loop repeats as long as a boolean con-
dition remains True.

7.2 The for Loop

EXAMPLE — Iterating Over a Sequence

subjects = [ " DL " , " GML " , " PE " ]


for s in subjects :
print ( s )

for ch in " AIDA " :


print ( ch )

33
Python Programming for AI & Data Analytics CHAPTER 7. LOOPS

7.2.1 range()

EXAMPLE — range() Patterns

for i in range (5) : # 0, 1, 2, 3, 4


print ( i )

for i in range (2 , 10) : # 2 , 3 , ... , 9


print ( i )

for i in range (10 , 0 , -2) : # 10 , 8 , 6 , 4 , 2 -- step of -2


print ( i )

NOTE — Common Pitfall

range(n) produces values from 0 to n-1, not n. This off-by-one confusion is one of the
most frequent beginner mistakes.

7.3 The while Loop

EXAMPLE — Basic while

count = 0
while count < 5:
print ( count )
count += 1

EXAMPLE — Sentinel-Controlled Loop

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 )

NOTE — Avoiding Infinite Loops

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

7.4 break and continue

EXAMPLE — break: Exit the Loop Early

for n in range (1 , 20) :


if n == 7:
break # stop the loop entirely
print ( n )
# prints 1 to 6 , then stops

EXAMPLE — continue: Skip to the Next Iteration

for n in range (1 , 10) :


if n % 2 == 0:
continue # skip even numbers , keep looping
print ( n )
# prints 1 , 3 , 5 , 7 , 9

7.5 The Loop else Clause


Python loops support an optional else block, which runs only if the loop completed without
hitting a break.

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

print ( is_prime (7) ) # True


print ( is_prime (8) ) # False

7.6 Nested Loops

EXAMPLE — Multiplication Table

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

EXAMPLE — Processing a 2-D List

matrix = [[1 , 2 , 3] , [4 , 5 , 6] , [7 , 8 , 9]]


total = 0
for row in matrix :
for value in row :
total += value
print ( total ) # 45

7.7 Useful Looping Idioms

EXAMPLE — enumerate() and zip()

subjects = [ " DL " , " GML " , " PE " ]


for index , name in enumerate ( subjects , start =1) :
print ( index , name )

names = [ " Anya " , " Kavin " , " Ravi " ]
scores = [91 , 87 , 95]
for name , score in zip ( names , scores ) :
print ( f " { name }: { score } " )

NOTE — Pythonic Style

Avoid for i in range(len(my_list)): print(my_list[i]). Prefer for item in


my_list: print(item), and reach for enumerate() only when the index itself is gen-
uinely needed.

7.8 Loops in Comprehensions


Comprehensions (covered in the Lists, Dictionaries, and Sets chapters) are, under the hood,
compact loop expressions.

EXAMPLE — Comprehension as Compact Loop

# Loop version
squares = []
for n in range (1 , 6) :
squares . append ( n ** 2)

36
Python Programming for AI & Data Analytics CHAPTER 7. LOOPS

# Comprehension version -- equivalent , more concise


squares = [ n ** 2 for n in range (1 , 6) ]

• 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.

7.9 Practice Exercises

• 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

DEFINITION — Key Takeaways

• 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.

“Flat is better than nested.” — The Zen of Python

37
Chapter 8

String Manipulation
Learning Objectives

➤ Explain what a string is and why strings are immutable in Python.


➤ Access characters and substrings using indexing and slicing.
➤ Apply common string methods for cleaning and transforming text.
➤ Format strings using f-strings and the .format() method.
➤ Split, join, and search text – essential skills for data preprocessing.

8.1 What is a String?


A string is an ordered, immutable sequence of characters, enclosed in single, double, or triple
quotes.

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).

EXAMPLE — Your First Strings

name = " Anya "


greeting = ' Hello '
paragraph = """ This spans
multiple lines . """
print ( type ( name ) ) # < class ' str '>

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

8.2 Indexing and Slicing

EXAMPLE — Indexing and Slicing

text = " AIDA2026 "


text [0] # 'A '
text [ -1] # '6 '
text [0:4] # ' AIDA '
text [4:] # '2026 '
text [:: -1] # '6202 ADIA ' -- reversed

8.3 Concatenation and Repetition

EXAMPLE — Building Strings

first , last = " Anya " , " Rao "


full_name = first + " " + last # ' Anya Rao '
border = " -" * 20 # '--------------------'

8.4 Common String Methods

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

EXAMPLE — Methods in Action

raw = " Anya Rao "


raw . strip () # ' Anya Rao '
raw . strip () . lower () # ' anya rao '

sentence = " Python is fun "


sentence . replace ( " fun " , " powerful " ) # ' Python is powerful '

" AIDA " . startswith ( " AI " ) # True


" data123 " . isalnum () # True
" data123 " . isdigit () # False

39
Python Programming for AI & Data Analytics CHAPTER 8. STRING MANIPULATION

8.5 Splitting and Joining

EXAMPLE — split() and join()

csv_row = " 101 , Anya , AIDA ,8.7 "


fields = csv_row . split ( " ," )
# [ '101 ' , ' Anya ', ' AIDA ', '8.7 ']

words = " Python is fun " . split () # splits on whitespace by default


# [ ' Python ', ' is ', ' fun ']

" -" . join ([ " 2026 " , " 08 " , " 16 " ]) # '2026 -08 -16 '

NOTE — Design Insight

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.

8.6 String Formatting

EXAMPLE — f-strings (Recommended)

name , cgpa = " Anya " , 8.712


print ( f " { name } has a CGPA of { cgpa :.2 f } " )
# ' Anya has a CGPA of 8.71 '

print ( f " { name ! r } " ) # " ' Anya '" -- repr form
print ( f " {2 ** 10 = } " ) # '2 ** 10 = 1024 ' -- self -
documenting expression

EXAMPLE — .format() and % (Older Styles)

" {} scored {} " . format ( name , cgpa )


" { n } scored { c :.2 f } " . format ( n = name , c = cgpa )
" % s scored %.2 f " % ( name , cgpa )

40
Python Programming for AI & Data Analytics CHAPTER 8. STRING MANIPULATION

8.7 Membership and Searching

EXAMPLE — in, find(), and count()

" AI " in " AIDA " # True


" data123 " . find ( " 123 " ) # 4 -- index of first match
" data123 " . find ( " xyz " ) # -1 -- not found
" mississippi " . count ( " ss " ) # 2

8.8 Iterating Over Strings

EXAMPLE — Looping Over Characters

vowel_count = 0
for ch in " Artificial Intelligence " . lower () :
if ch in " aeiou " :
vowel_count += 1
print ( vowel_count )

8.9 Strings as Sequences: A Summary

Aspect String List


Mutability Immutable Mutable
Element type Characters only Any type
Concatenation + creates a new string + creates a new list
Typical use Text data General collections

• 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".

8.10 Practice Exercises

• 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

DEFINITION — Key Takeaways

• Strings are ordered, immutable sequences of characters; all “modifying” methods


return new strings.
• split() and join() are the core tools for parsing and rebuilding delimited text.
• f-strings are the modern, preferred way to format text with embedded expressions.
• String indexing and slicing work identically to lists and tuples.

“Text is data, and data is text.”

42
Chapter 9

Functions and Modules


Learning Objectives

➤ 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.

9.1 Why Functions?


A function is a named, reusable block of code that performs a specific task. Functions avoid
code duplication and let large programs be broken into small, testable pieces.

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).

9.2 Defining and Calling Functions

EXAMPLE — Basic Function

def greet ( name ) :


print ( f " Hello , { name }! " )

greet ( " Anya " ) # Hello , Anya !

EXAMPLE — Returning a Value

def square ( n ) :
return n ** 2

result = square (5) # 25

43
Python Programming for AI & Data Analytics CHAPTER 9. FUNCTIONS AND MODULES

NOTE — Functions Without return

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.

9.3 Parameters and Arguments

9.3.1 Default Arguments

EXAMPLE — Default Values

def power ( base , exponent =2) :


return base ** exponent

power (5) # 25 -- uses default exponent


power (5 , 3) # 125 -- overrides default

9.3.2 Positional vs. Keyword Arguments

EXAMPLE — Keyword Arguments

def student_record ( name , dept , cgpa ) :


return f " { name } ({ dept }) : { cgpa } "

student_record ( " Anya " , " AIDA " , 8.7) # positional


student_record ( name = " Anya " , cgpa =8.7 , dept = " AIDA " ) # keyword --
order doesn 't matter

9.3.3 *args and **kwargs

EXAMPLE — Variable-Length Arguments

def total (* nums ) : # collects extra positional args into


a tuple
return sum ( nums )

total (1 , 2 , 3) # 6
total (1 , 2 , 3 , 4 , 5) # 15

def build_profile (** info ) : # collects extra keyword args into a


dict
return info

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

NOTE — Naming Convention

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.

9.4 Variable Scope

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.

EXAMPLE — Local vs. Global

counter = 0 # global

def increment () :
global counter # required to MODIFY a global
inside a function
counter += 1

increment ()
print ( counter ) # 1

9.5 Lambda Functions


A lambda is a small, anonymous, single-expression function, useful when a full def would be
overkill.

DEFINITION — Lambda

lambda parameters: expression


A lambda always returns the value of its single expression implicitly.

EXAMPLE — Lambda in Action

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

9.5.1 map(), filter(), and sorted() with Lambdas

EXAMPLE — Functional Idioms

nums = [1 , 2 , 3 , 4 , 5]

doubled = list ( map ( lambda n : n * 2 , nums ) ) # [2 , 4 , 6 , 8 ,


10]
evens = list ( filter ( lambda n : n % 2 == 0 , nums ) ) # [2 , 4]
sorted_desc = sorted ( nums , key = lambda n : -n ) # [5 , 4 , 3 , 2 ,
1]

NOTE — Comprehension vs. map/filter

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

EXAMPLE — Documenting a Function

def bmi ( weight_kg , height_m ) :


""" Return the Body Mass Index given weight in kg and height in
metres . """
return weight_kg / ( height_m ** 2)

print ( bmi . __doc__ )

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.

EXAMPLE — Import Styles

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...

from math import sqrt , pi


sqrt (16) # 4.0 -- no prefix needed

from math import * # imports everything -- use sparingly

EXAMPLE — Commonly Used Standard Library Modules

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...

9.8 Creating and Using Your Own Module

EXAMPLE — [Link]

# --- utils . py ---


def celsius_to_fahrenheit ( c ) :
return c * 9 / 5 + 32

PI_APPROX = 3.14159

EXAMPLE — [Link]

# --- main . py , in the same folder as utils . py ---


import utils

print ( utils . celsius_to_fahrenheit (30) ) # 86.0


print ( utils . PI_APPROX )

47
Python Programming for AI & Data Analytics CHAPTER 9. FUNCTIONS AND MODULES

NOTE — The if __name__ == "__main__" Idiom

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 " )

if __name__ == " __main__ " :


main ()

• Try It Yourself

Write a function describe_stats(*nums) that accepts any number of numeric arguments


and returns a tuple of (minimum, maximum, average). Then write a lambda that sorts
a list of dictionaries [{"name": ..., "cgpa": ...}, ...] by "cgpa" in descending
order.

9.9 Practice Exercises

• Exercise Set

1. Write a function is_prime(n) that returns True or False.


2. Write a function with a default argument that computes simple interest, and call it
both with and without overriding the default rate.
3. Explain the difference between *args and **kwargs with a short example of each.
4. Create your own module with two utility functions and import it into a separate
script.

9.10 Summary

DEFINITION — Key Takeaways

• 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.

10.1 Why File Handling?


Real programs rarely keep all their data in variables that vanish when the program ends. File
handling lets a program persist data to disk and read data produced by other programs – an
essential skill for any data pipeline.

DEFINITION — File Handling

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.

10.2 Opening and Closing Files

EXAMPLE — open() and close()

f = open ( " students . txt " , " r " ) # open in read mode
content = f . read ()
f . close () # must be closed explicitly to
free resources

NOTE — Common Pitfall

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

10.3 The with Statement

DEFINITION — Context Manager

with open(filename, mode) as file_variable:


The with block automatically closes the file when the block ends, even if an error occurs
inside it.

EXAMPLE — Recommended Pattern

with open ( " students . txt " , " r " ) as f :


content = f . read ()
# file is automatically closed here , even if an exception occurred
above

10.4 File Modes

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

NOTE — "w" Overwrites!

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.

10.5 Reading Files

50
Python Programming for AI & Data Analytics CHAPTER 10. FILE HANDLING

EXAMPLE — Reading Strategies

with open ( " students . txt " ) as f :


whole_text = f . read () # entire file as one string

with open ( " students . txt " ) as f :


all_lines = f . readlines () # list of lines , each ending in
'\ n '

with open ( " students . txt " ) as f :


for line in f : # memory - efficient : reads one
line at a time
print ( line . strip () ) # strip () removes the
trailing newline

NOTE — Why Line-by-Line Iteration Matters

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.

10.6 Writing and Appending Files

EXAMPLE — write() and writelines()

with open ( " output . txt " , " w " ) as f :


f . write ( " Name , Dept , CGPA \ n " )
f . write ( " Anya , AIDA ,8.7\ n " )

with open ( " output . txt " , " a " ) as f :


f . write ( " Kavin , CSE ,9.1\ n " ) # appended without erasing prior
content

lines = [ " Row 1\ n " , " Row 2\ n " , " Row 3\ n " ]
with open ( " output . txt " , " w " ) as f :
f . writelines ( lines )

10.7 Working with CSV Files


The csv module handles the quoting and delimiter rules of CSV files correctly, which manual
split(",") parsing often gets wrong.
EXAMPLE — Reading and Writing CSV

import csv

with open ( " students . csv " , newline = " " ) as f :

51
Python Programming for AI & Data Analytics CHAPTER 10. FILE HANDLING

reader = csv . reader ( f )


header = next ( reader ) # first row -- often the
header
for row in reader :
print ( row ) # each row is a list of
strings

with open ( " students . csv " , " w " , newline = " " ) as f :
writer = csv . writer ( f )
writer . writerow ([ " Name " , " Dept " , " CGPA " ])
writer . writerow ([ " Anya " , " AIDA " , 8.7])

EXAMPLE — DictReader / DictWriter

with open ( " students . csv " , newline = " " ) as f :


reader = csv . DictReader ( f ) # each row becomes a dict
using the header
for row in reader :
print ( row [ " Name " ] , row [ " CGPA " ])

10.8 Working with JSON Files


JSON (JavaScript Object Notation) maps naturally onto Python dictionaries and lists, making
the json module central to working with web APIs and configuration files.

EXAMPLE — Reading and Writing JSON

import json

data = { " name " : " Anya " , " dept " : " AIDA " , " scores " : [88 , 92 , 79]}

with open ( " student . json " , " w " ) as f :


json . dump ( data , f , indent =4) # write a dict to a JSON file

with open ( " student . json " ) as f :


loaded = json . load ( f ) # read a JSON file back into
a dict
print ( loaded [ " name " ]) # ' Anya '

json_text = json . dumps ( data ) # dict -> JSON string ( in


memory )
parsed = json . loads ( json_text ) # JSON string -> dict

52
Python Programming for AI & Data Analytics CHAPTER 10. FILE HANDLING

10.9 Checking File Existence and Handling Errors

EXAMPLE — [Link] and try-except

import os

if os . path . exists ( " students . txt " ) :


print ( " File found " )

try :
with open ( " missing . txt " ) as f :
content = f . read ()
except FileNotFoundError :
print ( " The file does not exist . " )

NOTE — Design Insight

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.

10.10 Putting It Together: A Small Data Pipeline

EXAMPLE — Reading a CSV, Filtering, and Writing JSON

import csv , json

toppers = []
with open ( " students . csv " , newline = " " ) as f :
for row in csv . DictReader ( f ) :
if float ( row [ " CGPA " ]) >= 8.5:
toppers . append ( row )

with open ( " toppers . json " , " w " ) as f :


json . dump ( toppers , f , indent =2)
This short pipeline reads structured tabular data, filters it using ordinary Python condi-
tionals, and writes the result out in a different structured format – the same pattern used
throughout real-world data analytics workflows.

• 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

10.11 Practice Exercises

• 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

DEFINITION — Key Takeaways

• Always prefer with open(...) as f: over manual open()/close().


• File mode ("r", "w", "a", . . . ) determines whether content is read, overwritten, or
appended.
• Iterate for line in f to process large files without loading them entirely into mem-
ory.
• The csv and json modules handle structured data formats correctly and are essential
tools for data analytics pipelines.
• Wrap file operations in try-except to handle missing or inaccessible files gracefully.

“Errors should never pass silently.” — The Zen of Python

54

You might also like