0% found this document useful (0 votes)
161 views218 pages

Object-Oriented Python Programming Guide

The document is a comprehensive guide on Object-Oriented Programming using Python, edited by Prof. Ajay Jaiswal and written by various contributors from the University of Delhi. It covers topics such as the basics of Python programming, control structures, error handling, user-defined functions, built-in data structures, and file handling. The material is designed for self-learning and includes lessons, objectives, and problem-solving strategies to aid learners in understanding Python programming.

Uploaded by

sensuharto88
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)
161 views218 pages

Object-Oriented Python Programming Guide

The document is a comprehensive guide on Object-Oriented Programming using Python, edited by Prof. Ajay Jaiswal and written by various contributors from the University of Delhi. It covers topics such as the basics of Python programming, control structures, error handling, user-defined functions, built-in data structures, and file handling. The material is designed for self-learning and includes lessons, objectives, and problem-solving strategies to aid learners in understanding Python programming.

Uploaded by

sensuharto88
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

OBJECT ORIENTED PROGRAMMING USING PYTHON

Editor

Prof. Ajay Jaiswal


Content Writers

Pratibha Yadav, Dr. Mansi Sood


Academic Coordinator

Deekshant Awasthi

© Department of Distance and Continuing Education


ISBN: 978-81-19169-95-5
E-mail: ddceprinting@[Link]
computerscience@[Link]

Published by:
Department of Distance and Continuing Education
Campus of Open Learning, School of Open Learning,
University of Delhi, Delhi-110007

Printed by:
School of Open Learning, University of Delhi
OBJECT ORIENTED PROGRAMMING USING PYTHON

Reviewer

Dr. Reema Thareja


External Reviewer

Ms. Bhavya Ahuja Grover


Ramanujan College, University of Delhi

Corrections/Modifications/Suggestions proposed by Statutory Body, DU/


Stakeholder/s in the Self Learning Material (SLM) will be incorporated in
WKH QH[W HGLWLRQ +RZHYHU WKHVH FRUUHFWLRQVPRGL¿FDWLRQVVXJJHVWLRQV ZLOO EH
uploaded on the website [Link] Any feedback or suggestions may
be sent at the email- feedbackslm@[Link]

Printed at: Taxmann Publications Pvt. Ltd., 21/35, West Punjabi Bagh,
New Delhi - 110026 (250 Copies, 2025)

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Contents

PAGE
UNIT-I
Introduction to Python Programming
Lesson 1: Introduction to Python Programming 3–22

UNIT-II
Creating Python Programs
Lesson 2: Fundamentals of Python Programming 25–49

Lesson 3: Control Structures 50–69

Lesson 4: Error and Exception Handling in Python 70–89

UNIT-III
User Defined Functions
Lesson 5: User Defined Functions in Python 93–115

UNIT-IV
Built-in Data Structures

Lesson 6: Built-in Data Structures in Python 119–150

Glossary 151–154

READING NOTES FOR EXTRA TOPICS


Lesson 7: Object Oriented Programming 157–191

UNIT-V
File and Exception Handling

Lesson 8: File and Exception Handling 195–211

PAGE i
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_TOC.indd 1 15-10-2025 [Link]


PFUP_TOC.indd 2 15-10-2025 [Link]
UNIT - I
Introduction to Python
Programming

PAGE 1
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 1 15-10-2025 [Link]


PFUP_Unit_01_Lesson [Link] 2 15-10-2025 [Link]
L E S S O N

1
Introduction to Python
Programming
Pratibha Yadav
Assistant Professor
Shyama Prasad Mukherji College
Email-Id: pratibha.123@[Link]

STRUCTURE
1.1 Learning Objectives
1.2 Introduction to Computers
1.3 Understanding Programming
1.4 What is Python
1.5 Why Use Python
1.6 Problem Solving Strategies
1.7 Structure of a Python Program
1.8 Syntax and Semantics of Python
1.9 Python Interpreter and Shell
1.10 Executing Simple Python Programs
1.11 Summary
1.12 Answers to In-Text Questions
1.13 Self-Assessment Questions
1.14 References

1.1 Learning Objectives


After completion of this lesson, you will be able to learn about:
‹ Basics of Computer and Programming.
‹ Features of Python.
‹ Problem Solving strategies for any programming language.

PAGE 3
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 3 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ‹ Structure of a Python Program.


‹ Complied vs Interpreted languages.
‹ Installation of Python.
‹ Using Python Interpreter.
‹ Executing First Python Program.

1.2 Introduction to Computers


A computer is an electronic device that can receive, process, store, and
output data. It consists of hardware (physical components) and software
(programs that run on the hardware). Computers use a fetch-decode-
execute cycle to execute instructions. The CPU fetches instructions from
memory, decodes to understand what operation has to be performed them,
and executes (perform the operation) the corresponding operations.
The basic components of a computer are:
‹ Central Processing Unit (CPU): It is the core of any computer
device which executes instructions and performs calculations. It is
also called the Brain of the Computer.
‹ Memory Unit: It is used to store data, instructions and information.
Primary and secondary are the two categories of memory.
Secondary memory is used to store data permanently and is
involatile in nature. Primary memory is also known as principal
or internal memory which is volatile in nature. There are two
types of primary memory:
‹ Read-Only Memory (ROM): ROM is a component of the
memory unit. This memory is read-only and cannot be used
for writing.
‹ Random-Access Memory (RAM): RAM is a component of the
memory unit which is used to store program data in temporary
manner.
‹ Input Devices: These allow people to send data to the computer
so that it can carry out specific commands. Examples include
keyboards, mouse, and scanners.

4 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 4 15-10-2025 [Link]


INTRODUCTION TO PYTHON PROGRAMMING

Notes
‹ Output Devices: After the computer has done processing the
instructions, these devices display the processed data. For instance:
speakers, plotters, projectors, printers, or monitors.

1.3 Understanding Programming


Programming is the process of instructing a computer to perform specific
tasks. It provides a set of instructions in a systematic manner. Developers
or programmers utilize a programming language as a means of commu-
nication with the computer. Learning programming enables you to create
software applications, websites, games, and much more. It allows you to
automate tasks, solve problems, and unleash your creativity. Programming
Languages are broadly classified into two categories: low level Language
and high level Language.

1.3.1 Low Level Language


Low-level languages are programming languages closely resemble the
machine code understood by the computers. They provide a direct
interface to the hardware and are difficult to understand and write.
Examples of low level programming language include assembly lan-
guage and machine code.

1.3.2 High Level Language


High level languages are programming languages designed to be human-
readable and are easier to understand and write. They offer abstractions
that make programming easier and are independent of the underlying
hardware. Examples of high level languages include Python, Java, C++,
C#, PHP, JavaScript and many more.

1.4 What is Python


Python is a widely used high level programming language that is well-
known for being easy to understand and simple to use. It is similar to a
tool that enables you to instruct a computer to carry out numerous tasks.

PAGE 5
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 5 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes Python is flexible and may be used for a variety of tasks, including de-
signing games, websites, data analysis, and repetitive task automation.
Python allows you to develop understandable code because of its clear
and easily readable syntax. This makes it an excellent choice for entry
level coders. Overall, Python is a powerful and user-friendly language
that helps people solve problems and create all sorts of interesting things
using a computer.

1.5 Why Use Python


Python is a programming language that is widely used and loved by
developers for a variety of reasons. Here are some key advantages of
using Python:
‹ Open Source: Since Python is open source, anyone can use it by
just downloading it. Users can openly share Python with others also
and distribute it without restriction.
‹ Ease of Use: Python’s syntax is simple and clear. It’s clear syntax
and statements that mimic English make it simpler to create, debug,
and maintain.
‹ Versatility: Python is a very flexible language that can be used for
a variety of tasks, including machine learning and web development.
Programming paradigms including procedural, object-oriented, and
functional programming are all supported.
‹ Robust Standard Library: Python has a vast collection of libraries
and frameworks that extend its capabilities. Developers can utilize
existing solutions and save time by using these libraries, which
offer pre-written code for particular tasks. Popular libraries include
NumPy for scientific computing, pandas for data analysis, Django
for web development, TensorFlow for machine learning, and Flask
for building web applications.
‹ Easy Integration and Interoperability: Python easily integrates
with other programming languages and systems. It can interface with
C/C++, Java, and other languages, allowing developers to utilize
existing codebases and extend functionality. Python also offers

6 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 6 15-10-2025 [Link]


INTRODUCTION TO PYTHON PROGRAMMING

modules for connecting to databases, accessing web services, and Notes


working with different file formats.
‹ Strong Community and Support: Python has a large and active
community of developers who contribute to its growth. Through forums,
online resources, and documentation, this community offers considerable
support. It’s likely that you will receive assistance from the Python
community if you run into any problems or have any inquiries.
‹ Rapid Development and Prototyping: Python’s simplicity and
readability contribute to faster development cycles. Rapid prototyping
is made possible by it, enabling developers to design and test
concepts quickly.
‹ Job Opportunities and Career Growth: Python is highly sought
after in the employment market and has been gaining popularity
quickly. Python expertise is valued across a wide range of industries,
including technology, finance, data science, and machine learning.
Learning Python increases your opportunities for employment and
for career advancement.
Overall, Python is a great option for developers thanks to its readability,
adaptability, collection of library, rapid development, and strong community
support. Its wide range of applications and ease of use have contributed
to its widespread adoption and popularity.

1.6 Problem Solving Strategies


The problem-solving process in Python programming involves a systematic
approach to tackle programming challenges. Here are the key steps to follow:
1. Understanding the Problem: Problem understanding is essential
to find solution to any problem. Problem understanding means
analyzing: what should be the desired code output and how can
that be produced?
2. Plan and Design: A proper action plan must be created to address
a problem after it has been identified. We refer to this as designing
the plan. This stage often entails computing the outcome from the
inputs that have been provided.

PAGE 7
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 7 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 3. Pseudocode: Without concentrating on the syntax of Python, write


pseudocode or list the steps of your approach in simple language. This
aids in streamlining the logic of the solution and organizing your thoughts.
4. Translate Pseudocode into Python Code: Start implementing your
solution in Python by translating your pseudocode into actual code.
Start with small sections and test them as you find any problems
or mistakes.
5. Test and Debug: Test your code using various inputs to ensure
it produces the desired results. Debug any errors or unexpected
behaviour by identifying and fixing issues in your code.
6. Optimize: Examine your code for any potential improvements or
optimizations. Look for areas where you can make the code more
efficient or eliminate redundancies.
7. Documentation: Document your code by adding useful comments
to make your code easier to understand and maintain.
8. Repeat and Iterate: If your solution does not meet the requirements
or you encounter new problems, go back to the previous steps
and make necessary adjustments. Problem-solving is an iterative
process, and it’s common to refine and improve your code based
on feedback and new insights.

9. Finalize: Once you have a working solution, review and finalize


your code. Make sure it adheres to best practices for coding, is
adequately documented, and is organized correctly.
8 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 8 15-10-2025 [Link]


INTRODUCTION TO PYTHON PROGRAMMING

Remember that addressing problems in Python requires more than just Notes
writing code; it also requires applying reasoning, comprehending the
problem area, and successfully converting your solution into executable
code. Your Python programming skills will improve with practice, expe-
rience, and exposure to various problem-solving situations.

1.7 Structure of a Python Program


Python program is structured in a way that allows it to be easily under-
stood and modified by other programmers. By following best practices
for program structure and organization, programmers can create code that
is efficient, maintainable, and easy to debug.

1.7.1 Components of a Python Program


1. Comments: Comments are lines of text that are used to make
the code more readable. These are not executed by the Python
interpreter. Comments start with the hash symbol (#) and can be
placed anywhere in the code.
For Example:
# This is a comment placed above the python
statement
print(“Python is a programming language”)
print(“Hello World”) # Another comment.
2. Import Statements: These are used to bring in external modules
or libraries that contain pre-written code for specific tasks. Import
statements are usually placed at the beginning of the code.
For Example:
import sys
3. Variable Declarations: Variables hold the values or data throughout
the program. Variables can be assigned values using the assignment
operator (=).
For Example:
x = “Lily”
y = 123
Here, x and y are variables holding data
PAGE 9
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 9 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 4. Function Definitions: Functions are used for defining reusable code
blocks to carry out specific tasks. We can pass data to functions as
input parameters. Functions can return result as well.
For Example:
def sum(x,y)
result = x + y
return(result)
sum(10,20)
Output
30
5. Output Statements: Output statements are used to display data or
results to the user. In addition to reporting text or values to the
console, output statements can write data to files or other output
devices. print() function is the most often used function for printing
the message on the screen or any other standard output device.
For Example:
print(“This is an example of print statement”)
print(1, 2, 3, ‘Hello’, ‘World’)

1.7.2 Documentation
Python documentation is a way to explain the code to other programmers
who may read it in the future. Python code documentation can be done
in various ways:
1. Documentation Strings or Docstrings: These multi-line strings are
used at the start of the definition of a module, class, or function.
They give a thorough explanation of the actions the code takes, the
parameters it requires, and the results it produces. The docstrings are
GHFODUHGXVLQJေေေWULSOHVLQJOHTXRWHVƍƍƍRUဲဲဲWULSOHGRXEOHTXRWHVƎƎƎ
For Example:
‘‘‘This is an example of
Docstrings in Python’’’
“““This is another example
of Docstrings
in Python”””
10 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 10 15-10-2025 [Link]


INTRODUCTION TO PYTHON PROGRAMMING

2. Comments: As mentioned above, comments can be used to provide Notes


information about the code. However, they are usually used for
brief explanations and are less structured than docstrings.
3. Type Hints: Python 3.5 introduced type hints, which are annotations
that provide a means of statically providing information about the
type of values within the Python code.
4. External Documentation: The code may have external documentation,
such as user guides, technical specifications, or design documents,
if it is a component of a bigger project. These can offer further
context and details about how the code fits into the bigger picture.
In addition to helping, you maintain and share your code, good docu-
mentation can also make it simpler for other developers to understand
and utilize your code.

1.7.3 Indentation and Code Blocks


Python relies heavily on indentation to define code blocks and specify
the scope of statements. It does not use {} for code blocks as we had
in C, C++, Java. Indentation is used to organize the code and group
statements together. A number of spaces or tabs are used to indent the
blocks of code. The standard convention in Python is to use four spaces
for indentation. Loops and conditional statements are examples of control
flow statements that are frequently used in code blocks.
Here’s an example that demonstrates indentation and code blocks in Python:
For Example:
Consider the following if-else statement
x = 50
if x > 40:
print(“x is greater than 40”) # This line
is indented, part of the if block
else:
print(“x is not greater than 40”) # This
line is indented, part of the else block

PAGE 11
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 11 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes It’s important to maintain consistent indentation using spaces or tabs


throughout your code to avoid syntax errors and ensure proper code
execution. If bad indentation is found by the interpreter, it will result
in a syntax error.

1.8 Syntax and Semantics of Python


Syntax describes the guidelines and standards that help to construct any
statement in a programming language whereas semantics refers to the
meaning of the associated lines of code.

1.8.1 Syntax
Syntax refers to the structure, grammar, and rules of a programming
language. It defines how code should be written and the order in which
statements should appear. A program with incorrect syntax will result in
a syntax error and won’t be executed.
For Example:
x = 30
y = 15
if x < y:
print(“y is greater”)
else:
print(x is greater) #This statement will
generate syntax error since the print
statement is expected to be in quotes
A syntax error typically results from missing reserved keywords, spaces,
incorrectly placed quotations, indentations and block usage, erroneous
declarations, inappropriate function calls, and improper function definitions.

1.8.2 Semantics
Semantics is concerned with the interpretation and meaning of code.
It focuses on determining whether the code follows logic and results
in the desired result. Even when a program’s syntax and semantics

12 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 12 15-10-2025 [Link]


INTRODUCTION TO PYTHON PROGRAMMING

are accurate, it could still produce false results even though it runs Notes
without errors.
For Example:
# user defined function to calculate division of
two numbers
def divide(a, b):
result = a / b
return result
x = int(input(“enter the value of x”))
y = int(input(“enter the value of y”))
quotient = divide(x, y) # This statement might
result in Semantics Error when we pass y as 0
print(quotient)
Note: This above code is syntactically correct. However, it might raise
a semantic error whenever we pass denominator as zero. As division by
zero is not possible mathematically.
Let’s consider an example for better understanding of importance of
semantics in code.
For Example:
num1 = int(input(“enter the first number”))
num2 = int(input(“enter the second number”))
# find the average of two numbers
average_of_numbers = num1+num2 /2 # This
statement is semantically incorrect
print(average_of_numbers)
Note: This above code is again syntactically correct. However, when we
try to execute the above code, python interpreter will read the expression
for average computation as:
num1 + (num2 / 2) instead of ( num1 + num2 ) / 2
Understanding both the syntax and semantics of Python is necessary to
write code that is accurate and meaningful. While syntax guarantees that
your code is appropriately constructed, semantics ensures that your code
behaves as intended and produces the desired outcome.

PAGE 13
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 13 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes IN-TEXT QUESTIONS


1. Which of the following is not a Low Level Language?
(a) X86 assembly
(b) ARM assembly
(c) Machine Code
(d) PHP
2. Who is the creator of Python programming Language?
3. What is the full form of PEP?
4. What is PEP 20 – The Zen of Python?
5. What is the file extension of a Python file?

1.9 Python Interpreter and Shell


In Python, the interpreter and shell are two separate components that
work together to execute Python code. Let’s understand each of them:
‹ Python Interpreter: A program that reads and runs Python code is
known as the Python interpreter. It is in charge of reading the code line
by line, running it, and creating the desired result. The interpreter can
be seen as the engine that powers the execution of Python programs.
‹ Python Shell: The Python shell is an interactive interface that
allows you to enter and execute Python code interactively. When
you type Python commands or expressions into the prompt, the shell
immediately executes them and outputs the results. The Python shell
is helpful for performing fast experiments, testing brief sections of
code, and learning how Python constructs behave.
In conclusion, the Python shell is a user-friendly interface that offers an
interactive way to deal with the interpreter, whereas the Python interpreter
is the underlying program that runs Python code.

1.9.1 Interpreted vs. Compiled Languages


Python is generally categorized as an interpreted language, but it is more
accurate to describe it as a hybrid language. Let’s explore the characteristics

14 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 14 15-10-2025 [Link]


INTRODUCTION TO PYTHON PROGRAMMING

of interpreted and compiled languages and understand how Python fits into Notes
this distinction:
‹ Interpreted Languages: In an interpreted language, the source
code is directly executed by an interpreter without the need for
a separate compilation step. The interpreter reads and executes
the code line by line, translating and executing each statement in
real-time. Interpreted languages offer advantages such as dynamic
typing, easy code modification, and portability across different
platforms. However, they can be slower in execution compared to
compiled languages.
‹ Compiled Languages: In a compiled language, the source code is
translated into machine code (executable code) before execution.
This translation process, called compilation, is performed by a
compiler. The resulting machine code can be directly executed
by the computer’s hardware. Compiled languages tend to offer
faster execution speeds but may require more effort and time for
development and debugging due to the compilation step.
Python is a hybrid language as it combines the flexibility and ease of
use of an interpreted language with performance optimizations similar
to compiled languages. When you run a Python program, the source
code is first compiled into an intermediate representation called by-
tecode. This bytecode is then executed by the Python interpreter. The
bytecode compilation occurs automatically and transparently in the
background, allowing for rapid development and easy modification
of the code.

1.9.2 Installing Python and Setting up the Interpreter on Windows


Step 1: Downloading the Python Installer
‹ Go to the official Python download page: [Link]
downloads/windows/ for Windows.
‹ Find a stable Python 3 release and click the appropriate link for
your system to download the executable file: Windows installer
(64-bit) or Windows installer (32-bit).

PAGE 15
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 15 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes

Step 2: Running the Executable Installer


‹ We assume you have chosen 64-bit windows installer. After the
installer is downloaded, double-click the .exe file, for example
[Link], (whichever is latest version) to run the
Python installer.
‹ Select the “Install launcher for all users” checkbox, which enables
all users of the computer to access the Python launcher application.
‹ It is advisable to select the “Add [Link] to PATH” checkbox,
which enables users to launch Python from the command line.

‹ Click Next to continue.


16 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 16 15-10-2025 [Link]


INTRODUCTION TO PYTHON PROGRAMMING

Step 3: Locate the Python directory in your system Notes


‹ C:\Program Files\Python310: If you selected “Install launcher for
all users” during installation, then the directory will be system wide.
‹ C:\Users\Your_Name\AppData\Local\Programs\Python\Python310:
If you didn’t select “Install for all users” during installation, then
the directory will be in the Windows user path.
Step 4: Verify the Python Installation
You can verify whether the Python installation is successful either through
the command line or through the Integrated Development Environment
(IDLE) application, if you chose to install it.
‹ Using Command Prompt
Go to Start and enter “cmd” in the search bar. Click Command
Prompt.
Enter the following command in the command prompt:
python —version #This command is used to check
which python version has been installed on your
machine

‹ Using Python IDLE application


Go to Start and enter “python” in the search bar and then click the
IDLE app, for example IDLE (Python 3.10 64-bit).

PAGE 17
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 17 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes The first line identifies the operating system, interpreter and its ver-
sion that is being used, hence it could vary for you. The last line is
a prompt which means that the interpreter is ready for you to enter
code there.

1.10 Executing Simple Python Programs


To execute Python programs, multiple options are available. Let’s discuss
them in detail below:
1. Using the Python Interpreter: You can run a Python program by
executing it directly using the Python interpreter from the command
line or terminal. To open the interactive mode, command line or
terminal and type python command.
It will open the following prompt where we can execute the Python
statement.

At the Python prompt, you can directly type Python statements or


expressions and press Enter to execute them. For example, you can
perform simple arithmetic calculations, assign values to variables,
define functions, import modules, etc.

18 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 18 15-10-2025 [Link]


INTRODUCTION TO PYTHON PROGRAMMING

2. Using an Integrated Development Environment (IDE): If you Notes


wish to execute the python program inside an IDE like Visual Studio
Code, PyCharm, Spyder or Atom, you can create a new Python file,
enter your code in it. The “Run” or “Execute” button is typically
present in IDEs, however you can alternatively run programs by
utilizing keyboard shortcuts as well.
3. Using a Code Editor: First, create Python file using any editor
like Notepad, Notepad++, or Vim. Then, write your code, and save
it with a .py extension. Open a command prompt or terminal, go
to the directory where the file is located, and use the python or
python3 command followed by the filename to run the program.
$ python [Link]
Regardless of the method you choose, the Python interpreter will read
your code, interpret it, and execute it, producing any desired output or
performing the actions specified in the program. Make sure that Python
is installed and properly set up on your system before attempting to
execute Python programs.

1.10.1 Writing Your First Python Program


Here’s an example of a simple Python program that prints “Hello, World”
to the console:
Option 1: Using direct print command in Python Shell
௑6WHS  Open the Python IDLE/Shell
௑6WHS  At Python prompt, type the following print statement and press
Enter print(“Hello, World”)

The Python interpreter will execute the print statement, and you should
see the output Hello World displayed on console.

PAGE 19
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 19 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes Option 2: Using code Editor


To run this program, you can follow these steps:
1. Open a text editor and create a new file.
2. Type the following statement into the file.
print(“Hello World !!”)

3. Click on Save As option and save the file with a .py extension,
say [Link].

Now, you have a Python program saved as [Link]. To


execute it, follow these instructions:
1. Open a command prompt (Windows) or a terminal (macOS/Linux).
2. Navigate to the directory where file named [Link]
is located. You can use the cd command to change directories.
20 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 20 15-10-2025 [Link]


INTRODUCTION TO PYTHON PROGRAMMING

Notes

3. Type python [Link] and press Enter.

4. The Python interpreter will execute the code, and the output Hello
World !! displayed in the console.
Congratulations! You’ve just run your first Python program that prints
“Hello World!!” to the console.

1.11 Summary
Python is a popular programming language that enables you to create
code that is easy to understand. It is a great pick for beginners due to
its simplicity and use. Overall, Python is a strong and user-friendly lan-
guage that enables users to use computers to solve problems and produce
a wide range of fascinating things. Python relies heavily on indentation
to define code blocks and statement scope.
Python is a hybrid language that combines performance enhancements similar
to compiled languages with the adaptability and simplicity of an interpreted
language. Python interpreter, which reads and executes the Python commands
line by line, is needed for the seamless running of Python programs. The
Python shell enables interactive use of the Python interpreter.

PAGE 21
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 21 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes
1.12 Answers to In-Text Questions
1. (d) PHP
2. Guido van Rossum
3. Python Enhancement Proposals
4. The Zen of Python, authored by Tim Peters, are 20 guiding design
principles for Python.
5. The file extension of python file is .py

1.13 Self-Assessment Questions


1. What are the features of Python?
2. Differentiate between Compiled and Interpreted Language?
3. What do you understand by the terms syntax and semantics in
programming language?
4. What is a bytecode?
5. What is the purpose of Python interpreter?
6. Why documentation is required in code?
7. What is the difference between comments and docstrings?
8. Write a program in python that print following statement on screen
“This is my first program in PYTHON” ?
9. What are the various problem solving strategies in any programming
language?

1.14 References
‹ Kamthane, A. N., & Kamthane, A. A. (2020). Programming and
Problem Solving with Python. McGraw-Hill Education.
‹ Balaguruswamy, E. (2018). Introduction to Computing and Problem
Solving using Python, 2nd edition, McGraw Hill Education.
‹ Saeed, A., Ayeva, A., Ayeva, K. (2020). Python In - Depth: Use
Python Programming Features, Techniques, and Modules to Solve
Everyday Problems. India: BPB PUBN.

22 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_01_Lesson [Link] 22 15-10-2025 [Link]


UNIT - II
Creating Python Programs

PAGE 23
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 23 09-10-2025 [Link]


PFUP_Unit_02_Lesson [Link] 24 09-10-2025 [Link]
L E S S O N

2
Fundamentals of Python
Programming
Pratibha Yadav
Assistant Professor
Shyama Prasad Mukherji College
Email-Id: pratibha.123@[Link]

STRUCTURE
2.1 Learning Objectives
2.2 Introduction
2.3 Tokens
2.4 Literals
2.5 Data Types
2.6 Variables
2.7 .H\ZRUGV  ,GHQWL¿HU
2.8 Expressions & Operators
2.9 Statements vs Expressions
2.10 Strings
2.11 Input Output Statements
2.12 Summary
2.13 Answers to In-Text Questions
2.14 Self-Assessment Questions
2.15 References

2.1 Learning Objectives


After completion of this lesson, you will be able to learn about:
‹ Tokens.
‹ Literals and their usage in representing data.

PAGE 25
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 25 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ‹ Identifiers and keywords in Python and their significance.


‹ Data types available in Python.
‹ Operators and expressions in Python.
‹ String declaration.
‹ Capturing user input and displaying output in Python.

2.2 Introduction
Python is one of the most popular languages used today. Amidst the
various features it provides, a key advantage is that it has a simple
syntax and it is very easy to learn. In the previous chapter, we saw how
easy it was to print a statement onto the screen. The syntax of Python
is readily adaptable and bears a number of similarities with the English
language constructs. In this chapter, we will understand the basic build-
ing blocks of the Python language that can be used to write programs
suited for the application at hand. We will learn about the concept of
tokens and the different types of Python literals and available built-in
data types. Then, we will explore the usage of variables, keywords and
identifiers in Python. We will further see how to write expressions in
Python and the different operators available, their usage, precedence
and associativity with the help of several examples. The chapter also
covers basics on strings and how to use them in your program. Finally
we discuss on the essential component of handling input and output in
Python programs.

2.3 Tokens
In Python, a token refers to the smallest individual unit of a program
that the Python interpreter can understand. It can be thought of as a
building block of the Python language. Python programs are made up of
various tokens, which include identifiers, keywords, operators, literals,
and punctuations.
1. Identifiers: These are names given to variables, functions, classes,
or other entities. They must follow certain naming rules and
conventions. For example: x = 5

26 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 26 09-10-2025 [Link]


FUNDAMENTALS OF PYTHON PROGRAMMING

2. Keywords: These are reserved words that have special meanings Notes
in Python and cannot be used as identifiers. For Example: while,
for, if, else etc.
3. Operators: These are symbols used to perform operations on
operands. Python supports various operators, such as arithmetic
operators (+, -, *, /), assignment operators (=, +=, -=), comparison
operators (==, !=, <, >), logical operators (and, or, not), and more.
4. Literals: These are fixed values that are directly specified in the
code.
5. Punctuations: These are symbols used for grouping, separating, or
marking different parts of the code. Examples of punctuations in
Python include parentheses (()), commas (,), colons (:), semicolons
(;), and more.
Tokens are important for the Python interpreter to correctly parse and
understand the program structure. They help in determining the syntax
and semantics of the code, allowing the interpreter to execute the pro-
gram accordingly.

2.4 Literals
Literals are representations of fixed values in a program. They can be
numbers, strings, boolean, etc. For example, ‘This is a string’, 10, 3.14, True,
-78 etc. Literals are often used to assign values to variables or constants.
There are five types of literals in Python, which are as follows:
‹ Numeric Literals
‹ String Literals
‹ Boolean Literals
‹ Literal Collection
‹ Special Literals

2.4.1 Numeric Literals


Numeric literals represent numerical values and falls under three catego-
ries: integer, float and complex.

PAGE 27
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 27 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes [Link] Integer Literals


The numerical literals that are zero, positive or negative natural num-
bers and contain no decimal points are integers. The different types of
integers are:
‹ Decimal: It contains digits from 0 to 9. The base for decimal
values is 10.
For Example:
# Decimal literal
x = 10
y = -5
‹ Binary: It contains only two digits - 0 and 1. The base for binary
values is 2 and prefixed with “0b or 0B”.
For Example:
# Binary literal
b1 = 0B1010 # this is binary representation of
decimal value 10
b2 = 0b00111 # this is binary representation of
decimal value 7
‹ Octal: It contains the digits from 0 to 7. The base for octal values
is 8. In Python, such values are prefixed with “0o or 0O”.
For Example:
# Octal literals
x = 0o123 # this is octal representation of
decimal value 83
x = 0O34 # this is octal representation of
decimal value 28
‹ Hexadecimal: It contains digits from 0 to 9 and alphabets from
[A-F] or [a-f]. It starts with “0x or 0X”
For Example:
# Hexadecimal literals

28 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 28 09-10-2025 [Link]


FUNDAMENTALS OF PYTHON PROGRAMMING

x = 0xA1 # this is hexadecimal representation Notes


of decimal value 161
y = 0X9b # this is hexadecimal representation
of decimal value 155
y = 0x20 # this is hexadecimal representation
of decimal value 32

[Link] Floating-Point Literals


A floating-point literal represents a real number that includes both the
integer part as well as the fractional part.
For Example:
# Floating-Point literal
price = 3013.12
weight = 54.2

2.4.2 String Literals


String literals are groups of characters surrounded by a single, double,
or triple quotes. By using triple quotes, we can write multi-line strings
or display them in the desired way.
For Example:
# String literals
firstName = ‘Peter’ #using single quotes
lastName = “Smith” #using double quotes
# using triple quotes
mailingAddress = ‘‘‘Mr. Peter Smith
24, My Street,
Kingston, New York’’’
In the above examples, Peter, Smith and Mr. Peter Smith 24, My Street,
Kingston, New York are string literals.

PAGE 29
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 29 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes
2.4.3 Boolean Literals
Boolean literals represent the truth values: True or False.
For Example:
# Boolean literals
flag = True
x = False

2.4.4 Literal Collections


Python provides literals for representing collections of values, such as
OLVWV >  @  WXSOHV ဲ-RKQƎ ဲ0DU\Ǝ ဲ0LNHƎ  GLFWLRQDULHV ^ေNH\ƍ
ေYDOXHƍ`  DQG VHWV ^  ` 
For Example:
# List literal
fruits = [“Apple”, “Mango”, “Orange”]
print(fruits)
————— OUTPUT —————
[‘Apple’, ‘Mango’, ‘Orange’]

2.4.5 Special Literals


In Python there is special literal None which represents the absence of
a value.
For Example:
# Special literal
var = None

2.5 Data Types


Data Types represents the information about the data. It basically denotes
what type of operations can be carried out on the data. Python has various
built-in data types which are discussed below.

30 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 30 09-10-2025 [Link]


FUNDAMENTALS OF PYTHON PROGRAMMING

'DWD7\SH &DWHJRU\ 'HVFULSWLRQ ([DPSOH Notes


1XPHULF ,QW XVHGWRVWRUHVLJQHG DJH 
LQWHJHUV VHP 
)ORDW XVHGWRVWRUHIORDWLQJ ZHLJKW 
SRLQW UHDO QXPEHUV DYHUDJH 
&RPSOH[ XVHGWRVWRUHFRPSOH[ F M
QXPEHUV D ±M
7H[W 6WU XVHGWRVWRUHVHTXHQFHRI QDPH -RKQ
FKDUDFWHUV DGGUHVV 1HZ<RUN86
%RROHDQ %RRO KROGVHLWKHURIWKHWZR IODJ )DOVH
YDOXHV7UXHRU)DOVH LVB$YDLODEOH 7UXH
6HTXHQFH OLVW KROGVRUGHUHGFROOHFWLRQRI O >@
LWHPVDQGDUHPXWDEOH QDPHV >3UHHWL$VKD
-DPHV@
WXSOH KROGVRUGHUHGFROOHFWLRQRI W  
LWHPVEXWDUHLPPXWDEOH
UDQJH UHWXUQVDVHTXHQFHRI D UDQJH 
QXPEHUV >@
6HW VHW KROGVXQRUGHUHGFROOHFWLRQ V ^`
RIXQLTXHLWHPVDQGDUH
PXWDEOH
IUR]HQVHW KROGVXQRUGHUHGFROOHFWLRQ V ^`
RIXQLTXHLWHPVDQGDUH I] IUR]HQVHW V 
LPPXWDEOH V IUR]HQVHW ^ $  %  &
``
0DSSLQJ GLFW +ROGVNH\YDOXHSDLU SHUVRQ ^ QDPH  -DQH 
FRXQWU\  86$  DJH `
1RQH 1RQH XVHGWRGHILQHDQXOORUQR D 1RQH
YDOXH

2.6 Variables
Variable is a reserved memory location that is used to store and manipulate
the data. It can be thought of as a name attached to a memory location.

2.6.1 Variable Assignment


Variable assignment is done using a single equals sign (=). To assign a
value to a variable, you just assign the variable name on the left hand
side of ‘=’ and value on the right hand side of ‘=’ and then start using it.
Python supports chained assignment as well which means we can assign
same value to multiple variables.

PAGE 31
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 31 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes For Example:


age = 25 # age is a variable which is assigned value 25
print(age)
————— OUTPUT —————
25
# Example of chained assignment
a = b = c = 40 # a, b and c are three variables and
all have been assigned value 40
print(a, b, c)
————— OUTPUT —————
40 40 40

2.6.2 Variable Types


Unlike many programming languages, Python, is a dynamically typed
language which means variables need not be declared or defined in
advance. The python interpreter binds the data type of a variable on the
basis of the value assigned to it.
In Python, we can check the type of the variable via type() function. This
function returns the type of the data passed to it as argument.
For Example:
a = 10 # a is a variable which is assigned value 10
print(a)
print(type(a)) # Since 10 is an integer value, here
type of variable a is integer
————— OUTPUT —————
10
<class ‘int’>

a = “Hello World!!”
print(a)

32 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 32 09-10-2025 [Link]


FUNDAMENTALS OF PYTHON PROGRAMMING

print( type(a)) # Since “Hello World!!” is a string, Notes


hence type of variable a is now string not integer
————— OUTPUT —————
Hello World!!
<class ‘str’>
In Python programming, everything is an object, therefore variables are
actually instances (objects) of data types, which are classes.

2.7 Keywords & Identifier


A keyword is a predefined word that has special meaning to compilers
and identifier is a user defined word given to a variable, function or
class etc.

2.7.1 Keywords
Keywords are reserved words in Python that have predefined meanings.
These keywords are used to define the syntax and structure of the lan-
guage. Here are some commonly used keywords in Python:
)DOVH GHI LI UDLVH
1RQH GHO LPSRUW UHWXUQ
7UXH HOLI LQ WU\
aQG HOVH LV ZKLOH
aV H[FHSW ODPEGD ZLWK
aVVHUW ILQDOO\ QRQORFDO \LHOG
bUHDN IRU QRW
cODVV IURP RU
cRQWLQXH JOREDO SDVV

2.7.2 Identifier
A name assigned to an entity, such as a variable, a function, a class, etc.,
is called an identifier. It acts as a unique identifier within the program and
is used to access and control these entities. Identifiers are case-sensitive

PAGE 33
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 33 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes i.e., sum and Sum are different identifiers. There are some rules for naming
the identifiers which have been discussed below:
‹ An identifier can only be a combination of letters [a-z, A-Z], digits
[0-9] or underscore (_)
‹ It must not start with a digit
‹ It should not be a reserved word i.e., keyword
‹ It should not contain whitespace or any special character except
underscore
Let’s see some examples of valid and invalid identifiers:
9DOLG,GHQWLILHUV ,QYDOLG,GHQWLILHUV
ILUVW1DPH ILUVW1DPH
QXP QXP
WUXH 7UXH
BYDU YDU
ILQGBODUJHVW ILQGODUJHVW
FDOFXODWHBVXP &DOFXODWHVXP

Although above are strict guidelines for writing identifiers, there are
some naming conventions that are recommended but not required. These
naming conventions are as follows:
‹ Class names should start with an uppercase letter and rest identifiers
with a lowercase letter
‹ Always assign meaningful names to identifiers
‹ Multiple words can be separated using an underscore

IN-TEXT QUESTIONS
1. Is python a static or dynamic typed language?
2. Which of the following a not a valid identifier in python?
‹ pass
‹ age_of_person
‹ minute
‹ 10th_student
‹ My-income
‹ Return

34 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 34 09-10-2025 [Link]


FUNDAMENTALS OF PYTHON PROGRAMMING

Notes
2.8 Expressions & Operators
Operators are special symbols that perform some operation on data or
variables. The values that an operator acts upon are called operands. An
expression is a combination of operands and operators.
For Example:
a = 5
a + 5 # this is an expression where a and 5 are oper-
ands and + is operator
Python provides many built-in operators to perform computations on data
values. There are primarily 7 types of operators:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment operators
6. Identity operators
7. Membership operators

2.8.1 Arithmetic Operators


Arithmetic operators are used to perform basic mathematical operations
like addition, subtraction, multiplication, and division on the operands.

2SHUDWRU 'HVFULSWLRQ
 DGGLWLRQ
 VXEWUDFWLRQ
 PXOWLSOLFDWLRQRUSURGXFW
 GLYLVLRQ
 IORRUGLYLVLRQUHWXUQVIORRUHGYDOXHRIWKH
TXRWLHQW
 PRGXORUHWXUQVWKHUHPDLQGHU
 H[SRQHQW

PAGE 35
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 35 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes For Example:


a = 10
b = 3
print(a + b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
————— OUTPUT —————
13
3.3333
3
1
1000

2.8.2 Relational Operators


Relational operators compared two operands and accordingly returns Bool-
ean value i.e, True or False depending on the outcome of the comparison.
2SHUDWRU 'HVFULSWLRQ
! JUHDWHUWKDQ
!  JUHDWHUWKDQRUHTXDO
 OHVVWKDQ
  OHVVWKDQRUHTXDO
 HTXDOWR
 QRWHTXDOWR

For Example:
a = 10
b = 3
c = 10
print(a == c)
print(a <= b)

36 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 36 09-10-2025 [Link]


FUNDAMENTALS OF PYTHON PROGRAMMING

print(b != c) Notes
print(c > b)
————— OUTPUT —————
True
False
True
True

2.8.3 Logical Operators


Logical operators are used for decision making and returns True or False
depending on the condition. They are generally used to combine multiple
conditional statements.
2SHUDWRU 'HVFULSWLRQ
DQG UHWXUQV7UXHLIERWK/+6DQG5+6RSHUDQGVDUH7UXH
RU UHWXUQV7UXHLIHLWKHURIWKH/+6RU5+6RSHUDQGLV7UXH
QRW UHWXUQV7UXHLIRSHUDQGLV)DOVHDQGYLFHYHUVD

For Example:
a = 10
b = 30
c = 15
print(( c >= 15) and (b < a))
print( not(a <= c))
print(( b != c) or (a == 11))
————— OUTPUT —————
False
False
True

2.8.4 Bitwise Operators


Bitwise operators act on bits and allows a programmer to access and
manipulate individual bits of the operands.

PAGE 37
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 37 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 2SHUDWRU 1DPH 'HVFULSWLRQ


%LWZLVH$1' SURGXFHVLIERWKWKHELWVRIWKHRSHUDQGV
DUHDQGRWKHUZLVH
_ %LWZLVH25 SURGXFHVLIERWKWKHELWVRIWKHRSHUDQGV
DUHDQGRWKHUZLVH
A %LWZLVH;25 SURGXFHVLIERWKWKHELWVRIWKHRSHUDQGV
DUHGLIIHUHQWDQGRWKHUZLVH
a %LWZLVH127 LWLQYHUWVDOOWKHELWVRIRSHUDQG
!! 5LJKW6KLIW VKLIWVWKHYDOXHRIWKHOHIWKDQGVLGHRSHUDQG
WRWKHULJKWDVPDQ\WLPHVDVWKHYDOXHRQWKH
ULJKWRIWKHRSHUDWRU
 /HIW6KLIW VKLIWVWKHYDOXHRIWKHOHIWKDQGVLGHRSHUDQG
WRWKHOHIWDVPDQ\WLPHVDVWKHYDOXHRQWKH
ULJKWRIWKHRSHUDWRU

For Example:
a = 10 # binary representation of the value 10 : 0000 1010

b = 20 # binary representation of the value 20 : 0001 0100

c = 15 # binary representation of the value 15 : 0000 1111

print(a & b) # binary representation of result after & : 0000 0000

print(a | c) # binary representation of result after | : 0000 1111

print(a ^ b) # binary representation of result after ^ : 0001 1110

print(a >> 2) # binary representation of result after >> : 0000 0010

print(b << 3) # binary representation of result after << : 1010 0000

print(~a) # binary representation of result after ~ : 1111 0101

———— OUTPUT —————


0
15
30
2
160
-11

38 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 38 09-10-2025 [Link]


FUNDAMENTALS OF PYTHON PROGRAMMING

2.8.5 Assignment Operators Notes


Assignment operators are used to assign values to the variables.
2SHUDWRU 'HVFULSWLRQ
$VVLJQPHQWRSHUDWRUDVVLJQVWKHYDOXHRIWKHULJKW
H[SUHVVLRQWRWKHOHIWKDQGVLGHRSHUDQG
 DGGOHIWDQGULJKWRSHUDQGVDQGDVVLJQVWKHUHVXOWWRWKHOHIW
RSHUDQG
 VXEWUDFWOHIWDQGULJKWRSHUDQGVDQGDVVLJQVWKHUHVXOWWRWKH
OHIWRSHUDQG
PXOWLSO\OHIWDQGULJKWRSHUDQGVDQGDVVLJQVWKHUHVXOWWRWKH
OHIWRSHUDQG
 GLYLGHOHIWDQGULJKWRSHUDQGVDQGDVVLJQVWKHUHVXOWWRWKHOHIW
RSHUDQG
 SHUIRUPVIORRUGLYLVLRQRIWKHOHIWDQGULJKWRSHUDQGVDQG
DVVLJQVWKHUHVXOWWRWKHOHIWRSHUDQG
 SHUIRUPVGLYLVLRQRIWKHOHIWDQGULJKWRSHUDQGVDQGDVVLJQV
WKHUHPDLQGHUWRWKHOHIWRSHUDQG
SHUIRUPVH[SRQHQWLDWLRQRIWKHOHIWRSHUDQGE\WKHYDOXHRI
ULJKWRSHUDQGDQGDVVLJQVWKHUHVXOWWRWKHOHIWRSHUDQG
SHUIRUPVELWZLVH$1'WRWKHOHIWDQGULJKWRSHUDQGVDQG
DVVLJQVWKHUHVXOWWRWKHOHIWRSHUDQG
_ SHUIRUPVELWZLVH25WRWKHOHIWDQGULJKWRSHUDQGVDQG
DVVLJQVWKHUHVXOWWRWKHOHIWRSHUDQG
A SHUIRUPVELWZLVH;25WRWKHOHIWDQGULJKWRSHUDQGVDQG
DVVLJQVWKHUHVXOWWRWKHOHIWRSHUDQG
a SHUIRUPVELWZLVH127WRWKHOHIWDQGULJKWRSHUDQGVDQG
DVVLJQVWKHUHVXOWWRWKHOHIWRSHUDQG
!! SHUIRUPVELWZLVHULJKWVKLIWWRWKHOHIWRSHUDQGXVLQJWKHULJKW
RSHUDQGDQGDVVLJQVWKHUHVXOWWRWKHOHIWRSHUDQG
 SHUIRUPVELWZLVHOHIWVKLIWWRWKHOHIWRSHUDQGXVLQJWKHULJKW
RSHUDQGDQGDVVLJQVWKHUHVXOWWRWKHOHIWRSHUDQG
For Example:
a = 5
b = 50
c = 10

PAGE 39
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 39 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes a +=c # a = a + c
b *=2 # b = b * 2
c %=4 # c = c % 4
print(a)
print(b)
print(c)
————— OUTPUT —————
15
100
2

2.8.6 Identity Operators


Identity operators compare the memory location of two objects. It returns
True or False depending on whether both the objects refer to same memory
or not. Python provides a built-in id() function to fetch the unique id of an
object.
2SHUDWRU 'HVFULSWLRQ
LV UHWXUQV7UXHLIERWK/+6DQG5+6RSHUDQGVSRLQWVWRVDPH
PHPRU\ORFDWLRQ
LVQRW UHWXUQV7UXHLIERWK/+6DQG5+6RSHUDQGVSRLQWVWR
GLIIHUHQWPHPRU\ORFDWLRQ

For Example:
a = 10
b = 10
c = [3, 4, 5]
d = [3, 4, 5]
print(id(a))
print(id(b))
print(a is b)
print(a is not b)
print(id(c))

40 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 40 09-10-2025 [Link]


FUNDAMENTALS OF PYTHON PROGRAMMING

print(id(d)) Notes
print(c is d)
————— OUTPUT —————
1865754018320 # unique id assigned to variable a
1865754018320 # unique id assigned to variable b
True
False
1865791630400 # unique id assigned to c
1865791630080 # unique id assigned to d
False

2.8.7 Membership Operators


Membership operators checks the presence of a value in a sequence. It
returns True or False as outcome after checking whether a given value
exists in a sequence or not.
2SHUDWRU 'HVFULSWLRQ
LQ UHWXUQV7UXHLIYDOXHLVSUHVHQWLQVHTXHQFHDQG)DOVH
RWKHUZLVH
QRWLQ UHWXUQV7UXHLIYDOXHLVQRWSUHVHQWLQVHTXHQFHDQG
)DOVHRWKHUZLVH

For Example:
a = [100, 34, 19, 45, 67]
b = 10
c = 34
print(b in a)
print(c in a)
print(19 not in a)
———-—— OUTPUT —————
False
True
False

PAGE 41
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 41 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 2.8.8 Operators Precedence


The sequence in which operations are carried out is referred to as operator
precedence. If the expression contains two operators of equal precedence,
then associativity rule is applied to break the tie. Almost all operators
obey left to right associativity, with the exception of ** (Exponentia-
tion). Associativity from left to right mea ns that an expression will be
evaluated in a left to right fashion.
2SHUDWRU 'HVFULSWLRQ
 3DUHQWKHVHV
 ([SRQHQWLDWLRQ
a 8QDU\SOXVXQDU\PLQXVDQGELWZLVH127
0XOWLSOLFDWLRQGLYLVLRQIORRUGLYLVLRQDQG

PRGXOXV
 $GGLWLRQDQGVXEWUDFWLRQ
!! %LWZLVHOHIWDQGULJKWVKLIWV
 %LWZLVH$1'
A %LWZLVH;25
_ %LWZLVH25
 !!  LVLV 5HODWLRQDORSHUDWRUVLGHQWLW\RSHUDWRUV
QRWLQQRWLQ DQGPHPEHUVKLSRSHUDWRUV
1RW /RJLFDO127
$QG /RJLFDO$1'
2U /RJLFDO25

Understanding operator precedence and associativity is crucial for writing


correct and predictable expressions in Python. It helps ensure that the ex-
pressions are evaluated in the intended order and produce the desired results.

2.9 Statements vs Expressions


In Python, a statement is a line of code that performs an action or a
command. It usually doesn’t produce a value or return anything. Some
examples of statements in Python include variable assignments, function
definitions, control flow structures (such as if-else statements and loops),
and import statements.

42 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 42 09-10-2025 [Link]


FUNDAMENTALS OF PYTHON PROGRAMMING

On the other hand, an expression is a piece of code that evaluates to a Notes


value. It can be a combination of variables, literals, operators, and function
calls that produce a result. Expressions can be used within statements
or on their own.

2.10 Strings
String is a sequence of characters enclosed within single quotes ", double
quotes " ", or triple quotes '" '". It is one of the built-in data types in
Python which is used to represent textual data. String is an immutable
object which means that once a string is created, it cannot be changed.
However, you can perform various operations on strings to manipulate
and extract information.
For Example:
name = ‘Jade’
city = “ New York “
country = ‘‘‘US’’’
print(name)
print(city)
print(country)
————— OUTPUT —————
Jade
New York
US
In later chapters, you will learn about indexing and slicing in strings,
concatenating strings, and various string manipulation methods.

IN-TEXT QUESTIONS
3. Find output of the following program
a = ‘hello’
print(a*5)
4. What is the output of Logical Operators ?
5. Is Python case sensitive when dealing with identifiers?

PAGE 43
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 43 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes
2.11 Input Output Statements
Input and output are essential concepts in programming that allow com-
munication between a program and its users. Input refers to the data or
information provided to a program, while output refers to the information
produced or displayed by the program.

2.11.1 Input
input() function is used to capture the user input from the console. It
displays a prompt, waits for the user to enter a value, and returns the
input as a string.
The syntax of the input function is:
input( ‘prompt string’ )
# prompt is an optional string which we wish to
display on screen
When using the input() function, it is advisable to include descriptive
prompts to guide the user on what to enter. The descriptive prompts help
in enhancing the user experience.
For Example:
userName = input(“Enter the name of user:”)
When you run the above statement in Python IDLE,
it will wait until user enters some input.

The input() function can be used to accept various types of input,


such as numbers, strings, or even expressions. However, the input

44 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 44 09-10-2025 [Link]


FUNDAMENTALS OF PYTHON PROGRAMMING

is always stored as a string, so you may need to convert it to the Notes


desired data type.
Try executing the below statements in python IDLE:
num1 = input(“Enter the first number:”)
print(type(num1))
Irrespective of the value entered by the user, input() function always
returns string value. Hence, if you check the data type of the value re-
turned by input(), outcome will always be ‘str’ only.

Now, to convert the user input to a specific data type, you can use type
casting functions like int(), float(), or bool(). Type casting is necessary
when performing calculations or comparisons with the input.
Try executing the below statements in python IDLE:
num1 = int(input(“Enter the value :”))
print(type(num1))
# int() will change the data type of user
input from string to integer.

2.11.2 Eval Function


In Python, the eval() function is used to evaluate a string as a Python
expression and returns the result. It can be used to dynamically execute
code represented as a string. The eval() function takes a single argument,
which is the string expression to be evaluated.
The general syntax of eval() function is:
eval( string expression )

PAGE 45
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 45 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes For Example:


result = eval(“4 + 5”)
print(result)
result = eval(‘3 ** 3’)
print(result)
print(eval(‘7 - 6’))
————— OUTPUT —————
9
27
1

2.11.3 Output
Python provides print() function to display the output on console or any
other standard output device.
The syntax of the output function is:
print (value(s), sep = “,”, end = “ “, file
= file, flush = flush)
‹ value(s) are the values to be printed on the screen
‹ sep specifies how values will be separated inside the same print
statement. Default is ‘ ’ i.e., space
‹ end specifies what to print at the end of the print statement. Default
is ‘\n’ i.e., new line
‹ file specifies where to display the output. Default is [Link] i.e.,
screen
‹ flush specifies whether output will be flushed (True) or buffered
(False). Default is False
For Example:
print(‘Hello’, ‘World’)
print(‘Hello’, ‘World’, ‘!!’, sep = ‘-’)
print(‘Hello’, ‘World’ , sep = ‘\t’, end = ‘$$’)

46 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 46 09-10-2025 [Link]


FUNDAMENTALS OF PYTHON PROGRAMMING

————— OUTPUT ————— Notes


Hello World # values are separated by
default with space and new
line is added after print
Hello-World-!! # values are now separated
by ‘-’ and new line is added
after print
Hello World$$ # values separated by tab and
‘$$’ added after print
Input and output are crucial for building interactive and dynamic pro-
grams. Input can be used to gather user preferences and output allows
programs to display results or save data to files.

2.12 Summary
In Python, the constant values that can’t be mutated are called literals.
Variable is the name of a memory location and are used to store and
manipulate data values. Python is a dynamically typed language, meaning
that the type of a variable is decided based on the data that is provided
to it. In Python, variables are actually objects and data types are actually
classes. Operators are widely used to perform computations on the vari-
ables or data values. Integration of input and output functions are required
to build an interactive and dynamic program. User preferences can be
captured by input() functions, and print() can be used to display results.

2.13 Answers to In-Text Questions


1. Python is a dynamic typed language.
2. Following are not valid identifier
‹ 10th_student
‹ My-income
‹ Return
3. hello hello hello hello hello
4. The logical operators give output : true or false
5. Yes

PAGE 47
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 47 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes
2.14 Self-Assessment Questions
1. What is the difference between following operators:
‹ == and =
‹ // and /
‹ >> and <<
‹ is and in
‹ ~ and not
2. How can we check the identity of a variable?
3. Which operator would you choose to find whether a specific value
is present in a sequence or not?
4. What is the associativity of the exponentiation operator?
5. What is the difference between logical AND and bitwise AND
operators? Explain with the help of an example.
6. Write a program to add and multiply two numbers in Python. Take
input from the user.
7. Write a program to compute area of a circle. Take input from the
user.
8. What will be the output of the following code:
(i) a = b = 15
b *= 4
c = b / a
d = a>>2
print(a,b,c,d, sep = ‘::’, end = ‘.’)
(ii) x = 100
y = 15
print(x // y % 5)
(iii) print(5 * 5 ** 4 * 6)
(iv) a = -1
b = 9
c = 0

48 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 48 09-10-2025 [Link]


FUNDAMENTALS OF PYTHON PROGRAMMING

print(a and b) Notes


print(c and a)
print(a or c)
print(not c)
(v) a = 35
b = 19
print(a | b)
print(a >> 2)
print(b << 3)
(vi) x = 10
y = 20
z = -5
x += z
y -= x
x =+8
print(x, y, z)

2.15 References
‹ Kamthane, A. N., & Kamthane, A. A. (2020). Programming and
Problem Solving with Python. McGraw Hill Education.
‹ Balaguruswamy, E. (2018). Introduction to Computing and Problem
Solving using Python, 2nd edition, McGraw Hill Education.
‹ Saeed, A., Ayeva, A., Ayeva, K. (2020). Python In - Depth: Use
Python Programming Features, Techniques, and Modules to Solve
Everyday Problems. India: BPB PUBN.

PAGE 49
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 49 09-10-2025 [Link]


L E S S O N

3
Control Structures
Pratibha Yadav
Assistant Professor
Shyama Prasad Mukherji College
Email-Id: pratibha.123@[Link]

STRUCTURE
3.1 Learning Objectives
3.2 Introduction
3.3 Conditional Statements
3.4 Loops in Python
3.5 Loop Control Statements
3.6 Summary
3.7 Answers to In-Text Questions
3.8 Self-Assessment Questions
3.9 References

3.1 Learning Objectives


In this chapter, you will be able to explore about:
‹ Conditional statements and their significance.
‹ Iterative statements.
‹ Loop control statements.

3.2 Introduction
Programs in the real world almost always need the ability to check some conditions and
respond accordingly. In order to bring out this effect, programming languages have condi-
tional statements that help incorporate change of flow of control on the basis of decisions
taken as per the conditions outlined by real world scenarios. In Python, if-elif-else are
the conditional constructs that help achieve conditional execution of code. Also, we often
need to repeat a set of statements until a particular condition is satisfied. Looping hence
50 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 50 09-10-2025 [Link]


CONTROL STRUCTURES

is also an essential programming construct. Python provides two state- Notes


ments for implementing loops: for and while. In this chapter, we explore
the conditional and loop statements in Python with the help of various
examples. Further, we also look at the loop control statements provided
in Python to alter the flow of iterations. Python has three loop control
commands: break, continue and pass. These are frequently used to manage
the controlled execution of iterative statements. An adequate knowledge
of these constructs is quintessential for writing efficient, compact and
powerful code.

3.3 Conditional Statements


Conditional statements as the name implies allow us to execute different
blocks of code based on specific conditions. In Python, we have three
types of conditional statements: if statement, if - else statements, if - elif
- else ladder. Let’s discuss each of the conditional statements in detail.

3.3.1 If Statement
The if statement determines whether a block of code will be executed or
not on the basis of a specified condition.

PAGE 51
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 51 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes The general syntax is as follows:


if condition:
Statement 1
Statement 2
Statement 3
Statement 4
# In the above syntax, Statement 1, Statement
2, and Statement 3 will execute only if the
condition associated with the if statement is
True.
Let’s understand the working of if statement using an example.
For Example:
age = int(input(“Enter the age of person”))
#input function is used to capture user input
if age >= 18:
print(“Congratulations !!”)
print(“You are eligible to vote”)
print(“You are Outside if block now”)
Let’s understand the working of above example based on different
scenarios.
Scenario 1:
If user enters the value of age = 20
Output:
Congratulations !!
You are eligible to vote
You are Outside if block now
Scenario 2:
If user enters the value of age = 10.
Output:
You are Outside if block now

52 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 52 09-10-2025 [Link]


CONTROL STRUCTURES

Working of if statement Notes

3.3.2 If - Else Statement


The if - else statement executes one block of code if a condition is true,
and another block of code if the condition is false. The general syntax
is as follows.
if condition:
# Code to be executed if the condition is true
else:
# Code to be executed if the condition is false

PAGE 53
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 53 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes For Example:


age = int(input(“Enter the age of person”))
if age >= 18:
print(“Congratulations!!”)
print(“You are eligible to vote”)
else:
print(“You are not eligible”)

print(“You are outside of if-else block now”)


Let’s understand the working of above example based on different scenarios.
Scenario 1:
If user enters the value of age = 35.
Output:
Congratulations!!
You are eligible to vote
You are outside of if-else block now
Scenario 2:
If user enters the value of age = 16.
Output:
You are not eligible
You are outside of if-else block now
Working of if - else statement

54 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 54 09-10-2025 [Link]


CONTROL STRUCTURES

3.3.3 If – ELIF - Else LADDER Notes


The if - elif - else ladder is used when we need to make a choice between
more than two. It allows you to check if multiple expressions are true and
execute a block of code as soon as one of the conditions evaluates to true.
if condition:
# Code to be executed if the condition is
true
elif condition:
# Code to be executed if the above condi-
tion is false
.
.
.
else:
# Code to be executed if none of the above
conditions are true

PAGE 55
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 55 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes For Example:


marks = int(input(“Enter the marks of student”))

if marks >= 60:


print(“You scored First Division”)
elif marks >= 40 and marks < 60:
print(“You scored Second Division”)
else:
print(“You scored Third Division”)

print(“You are outside if - elif block now”)


Let’s understand the working of above example based on different
scenarios.
Scenario 1:
If user enters the marks = 85
Output:
You scored First Division
You are outside if - elif block now
Scenario 2:
If user enters the marks = 58.
Output:
You scored Second Division
You are outside the if - elif block now
Scenario 3:
If user enters the marks = 35.
Output:
You scored Third Division
You are outside if - elif block now

56 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 56 09-10-2025 [Link]


CONTROL STRUCTURES

Working of if - elif statement Notes

3.4 Loops in Python


Loops allow us to repeatedly execute a block of code until a certain
condition is met. We can run a single statement or set of statements
repeatedly using a loop command.

3.4.1 For Loop


Python’s for loop is designed to iterate over a sequence such as list,
tuple, dictionary, or other iterable objects of Python. The for loop it-
erates over a sequence and executes a block of code for each element
present in the sequence. The process of traversing a sequence is known
as iteration. The for loop is usually used when the number of iterations
is known.
The general syntax is as follows:
for item in sequence:
# block of code to be executed for each item

PAGE 57
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 57 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes

For each item


in sequence

If no item is remaining in
the sequence

If there is an item
in the sequence

Exit Loop

Here, item variable will access each item of sequence one by one for
each iteration. The loop will continue to execute until we access the last
item of the sequence.
For Example:
colors = [“Red”, “Yellow”, “Green”, “Blue”,
“Black”]

for color in colors:


print(color)

58 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 58 09-10-2025 [Link]


CONTROL STRUCTURES

————— OUTPUT ————— Notes


Red
Yellow
Green
Blue
Black
In the above example, we have created a list of colors. Initially, the color
variable is assigned the first element of the list, i.e., Red. Then, the print
statement inside the loop is executed and “Red” will be displayed on the
output screen. For the next iteration, color variable is updated with the
next element of the list, and the print statement is executed again. The
above for loop will execute until the last element of the list has been
accessed and after that loop will terminate.
Let’s have a look on another example to have a better understanding of
the for loop.
For Example:
numbers = range(4) # range function will cre-
ate a sequence of numbers from 0 to 3 i.e.,
[0, 1, 2, 3]
for i in numbers:
print(i)
————— OUTPUT —————
0
1
2
3
In the above example, first a sequence of numbers have been generated
using range() function and stored in numbers variable. Now, i will iter-
ate over the sequence and will process elements of the list one by one.

3.4.2 While Loop


In Python, while loops are used to iterate over a block of code until a
certain condition is satisfied. It repeatedly checks the condition before

PAGE 59
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 59 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes each iteration and the statement that comes after the while loop is exe-
cuted as soon as the condition becomes false. The while loop is usually
used when the number of iterations is unknown.
The general syntax is as follows:
while condition:
# Code to be executed while the condition is
true

For Example:
count = 10 # initializing the loop variable
while count <= 15:
print(count)
count += 1

print(“Outside While Loop”)


————— OUTPUT —————
10
11
12
13

60 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 60 09-10-2025 [Link]


CONTROL STRUCTURES

14 Notes
15
Outside While Loop
In the above example, count variable is initialized with 10. For 1st itera-
tion, condition is True since 10 is less than 15. Hence, the block of code
associated with while loop will execute. First the print statement will
execute and then value of count variable will be increased by 1, making
count = 11. Now, for next iteration, again condition will be checked
which is True as 11 <= 15. Again, block of code associated with while
loop will execute and count will be incremented by 1. This process will
repeat until value of count exceeds 15. When the value of count = 16,
the loop will terminate and program control will come outside the loop.
For Example:
counter = 5
while counter >= 0:
print(counter)
counter = counter - 2
print(“Exit”)
————— OUTPUT —————
5
3
1
Exit
In this example, counter variable is initially set to 5 and value has been
decremented by 2 for each iteration. The loop will keep running until
value of counter is >= 0. When the condition becomes False, loop will
terminate and program control will jump outside of the loop.

3.4.3 Nested Loop


A nested loop is a loop inside the body of the outer loop. The inner or outer
loop can be of any type, such as a while loop or for loop. For example, the
outer for loop can contain a while loop and vice versa. There is no limitation
on the chaining of loops.

PAGE 61
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 61 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes The number of iterations in the nested loop is determined by multiplying


the number of iterations in the outer loop by the number of iterations
in the inner loop.
Syntax of using a nested for loop in Python
for element in sequence: # outer for loop
for element in sequence: # inner for loop
body of inner for loop
body of outer for loop
For Example:
#Printing multiplication table of 2 to 5
for i in range(2, 6):
# outer loop iterates 4 times
for j in range(1, 11):
# nested loop iterates 10 times for each occurrence
of i
print(i * j, end = ‘ ’ )
print() # empty print displays a blank line
print(“Exit”)
————— OUTPUT —————
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
Exit
Let’s try to understand the flow of loops given in above example.
L - 2XWSXW
  LVSULQWHG
  LVSULQWHG
  LVSULQWHG
  LVSULQWHG
  LVSULQWHG

  LVSULQWHG
  LVSULQWHG
  LVSULQWHG
  LVSULQWHG
  LVSULQWHG
62 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 62 09-10-2025 [Link]


CONTROL STRUCTURES

  LVSULQWHG Notes
  LVSULQWHG
  LVSULQWHG
  LVSULQWHG
  LVSULQWHG

  LVSULQWHG
  LVSULQWHG
  LVSULQWHG
  LVSULQWHG
  LVSULQWHG
L MH[SUHVVLRQZLOOEHH[HFXWHG
 MZLOOH[HFXWHWHQWLPHV
DFFRUGLQJWRYDOXHRILDQGM
L MH[SUHVVLRQZLOOEHH[HFXWHG
 MZLOOH[HFXWHWHQWLPHV
DFFRUGLQJWRYDOXHRILDQGM

In the above example, we have an outer loop that iterates over the range
of numbers from 2 to 5. For each iteration of the outer loop, the inner
loop is executed 10 times, printing the values of i * j on screen.

IN-TEXT QUESTIONS
1. Which keyword is used to execute a block of code if the
condition in the if statement is false?
2. In python which operator is used after condition of if statement?
3. Which of the following is the correct syntax for a ‘for’ loop?
(a) for i = 0 to 10:
(b) for i in range (0, 10):
(c) for (i = 0; i < 10; i++):
(d) for (i in range (0, 10))
4. What are loop control statements ?
5. Write a python code to print names of week days.

3.5 Loop Control Statements


Using loop control statements, we can manage how loops are executed.
Control statements can change the flow of iterations. Three loop control
statements are available in Python: break, continue, and pass.

PAGE 63
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 63 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 3.5.1 Break Statement


The break statement is used to terminate a loop prematurely. When en-
countered, it immediately exits the loop, and the program continues with
the next statement after the loop. When we wish to terminate the loop’s
execution depending on a given circumstance, we frequently utilize the
break statement.
The syntax of the break statement is:
break
Working of break statement

For Example:
for num in range(1,6):
if num == 4:
print(“break”)
break
print(num)
print(“Exit from Loop”)
————— OUTPUT —————
1
2
3
break
Exit from Loop

64 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 64 09-10-2025 [Link]


CONTROL STRUCTURES

In the above example, for first three iterations, num will be printed as Notes
if condition is not satisfied. Once the value of num is 4, the break is
encountered and loop will be terminated immediately. The control flow
of program will jump outside of the loop.
Here’s an example that demonstrates the usage of break statement within
a loop:
languages = [ “JAVA” , “C”, “Python”, “C++”]
# list of programming language

for lang in languages:


if lang == “Python”:
break
print(lang)
print(“Exit from Loop”)
————— OUTPUT —————
JAVA
C
Exit from Loop
In the above example, for loop that iterates over the list of program-
ming languages. The if statement checks if the value of lang is equal to
“Python” or not. When the lang variable holds the value “Python”, the
break statement is encountered, and the loop is immediately exited. As a
result, “Python” is not printed, and the loop is terminated. The program
then continues with the statement after the loop.

3.5.2 Continue Statement


The continue statement is used to skip the current iteration of a loop
and move to the next iteration. When encountered, it skips the remaining
statements in the loop body and jumps to the next iteration. The continue
statement is typically used when we want to skip certain iterations based
on a specific condition.
The syntax of the continue statement is:
continue

PAGE 65
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 65 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes Working of continue statement

Example:
for num in range(1,6):
if num == 4:
print(“continue”)
continue
print(num)
print(“Exit”)
————— OUTPUT —————
1
2
3
continue
5
Exit
In the above example, the loop will execute 5 times staring from 1 till
5. When value of num = 4, the continue statement is encountered and
loop control will skip executing the current iteration and immediately
jump to beginning of the loop.

3.5.3 Pass Statement


The pass statement, which is a null statement, is frequently used as a
placeholder for creating empty loops. The pass statement is also used
to create classes, statements, and functions that are empty. When pass

66 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 66 09-10-2025 [Link]


CONTROL STRUCTURES

statement is encountered, nothing happens. Pass statements are typically Notes


used when a loop or function has not yet been implemented but may be
done in the future.
The syntax of the pass statement is:
pass
For Example:
for num in range(1,6):
pass
print(num)
print(“Exit”)
————— OUTPUT —————
5
Exit
In the above example, for loop does nothing. It will be iterated 5 times
and once the program control reaches the end of sequence, loop will
terminate.
Note: pass statement and comment are entirely different. Comments are
completely ignored by the interpreter whereas pass is not.

3.6 Summary
The most crucial feature of practically all programming languages is
decision-making. Decision structures enable you to alter the execution
path of your program based on the outcome of numerous expressions that
return True or False. While loop control statements are used to regulate
the execution of loops, conditional statements are used to execute certain
code blocks based on specific criteria. To change the behaviour of loops
and conditional statements, utilize the break, continue, and pass statements.
Programmers can create Python programs that are more potent and efficient
by knowing these control structures.

PAGE 67
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 67 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes
3.7 Answers to In-Text Questions
1. else
2. colon :
3. (b) for i in range (0, 10):
4. The loop control statements are break, continue, pass
5. weekdays=[“sunday”, “monday”, “tuesday”, “wednesday”, “thursday”,
“friday”, “saturday”]
for weekday in weekdays:
print(weekday)

3.8 Self-Assessment Questions


1. Which loop control statement would you choose to exit from a loop
early?
2. What is the difference between the break and continue statements
in Python?
3. Write a program to find the largest among three numbers. Take input
from the user.
4. Write a program to check whether a given number is even or odd.
5. What is the usage of pass statement in Python?
6. Write a program to check whether a given number is prime or not.
7. Write a program to compute factorial of a number.
8. Write a program to compute factors of a given number.
9. Write a program to find the sum of following series:
‹ 1 + 2 + 3 + ... + n

‹ 1 – 3 + 5 – 7 + ...
1 1 1 1
‹   "
1 2 3 n
1 1 1 1
‹   "
1! 2 ! 3! n!

68 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 68 09-10-2025 [Link]


CONTROL STRUCTURES

10. Write a program to print the following patterns on output screen: Notes
           
           
           
           
          
D E F

        
            
              
               
            

G H I

11. Write a program to print the Fibonacci series up to n terms.

3.9 References
‹ Kamthane, A. N., & Kamthane, A. A. (2020). Programming and
Problem Solving with Python. McGraw-Hill Education.
‹ Balaguruswamy, E. (2018). Introduction to Computing and Problem
Solving using Python, 2nd edition, McGraw Hill Education.
‹ Saeed, A., Ayeva, A., Ayeva, K. (2020). Python In - Depth: Use
Python Programming Features, Techniques, and Modules to Solve
Everyday Problems. India: BPB PUBN.

PAGE 69
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 69 09-10-2025 [Link]


L E S S O N

4
Error and Exception
Handling in Python
Mansi Sood
Assistant Professor
Shyama Prasad Mukherji College
Email-Id: [Link]@[Link]

STRUCTURE
4.1 Learning Objectives
4.2 Introduction
4.3 What is Error
4.4 What is Exception
4.5 Handling Exceptions
4.6 Raising Exceptions
4.7 Nested Try Block
4.8 Exception Chaining
4.9 Common Built-in Exceptions
4.10 Best Practices for Exception Handling
4.11 Summary
4.12 Answers to In-Text Questions
4.13 Self-Assessment Questions
4.14 References

4.1 Learning Objectives


After completion of this lesson, readers will be equipped to understand:
‹ Difference between Error and Exception.
‹ Mechanisms available in Python for handling exceptions.
‹ Advanced exception handling techniques like exception chaining.

70 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 70 15-10-2025 [Link]


ERROR AND EXCEPTION HANDLING IN PYTHON

‹ Different types of errors and exceptions that can occur in Python Notes
programs.
‹ Best practices and guidelines for writing reliable and robust code.

4.2 Introduction
An error occurs when the code encounters issues with its syntax, pre-
venting successful execution of the program and potentially leading to
abrupt termination. In contrast, an exception is an abnormal situation
that arises while the program is running. Exceptions are usually trig-
gered by unexpected circumstances during program execution. When
an exception arises, it disrupts the regular flow of the program and
can be managed using exception-handling mechanisms to avoid pro-
gram crashes.
Error and exception handling play a crucial role in software development.
When writing code, it is essential to anticipate and handle the potential
errors and exceptions that may arise during program execution. Failing
to handle these situations can lead to unexpected and unbearable program
behaviour, crashes, and even data loss. Appropriate error and exception
handling ensure that a program can gracefully handle errors, provide
meaningful feedback to users, and recover from exceptional situations.
Also, if termination is inevitable, it does the necessary bookkeeping
before terminating.
This chapter provides a comprehensive overview of error and exception
handling in Python. It introduces different types of errors and exceptions
that can occur in Python programs. It also covers exception-handling tech-
niques like try-except blocks, raising and catching exceptions, and handling
multiple exceptions. It also covers a few advanced exception-handling
techniques such as nested try blocks, and exception chaining.

4.3 What is Error


Software development treats errors and exceptions as two distinct concepts.
Errors are syntax errors that are also known as parsing errors. They are
in fact the first and most common errors encountered when a user starts
with Python programming or rather any programming language.

PAGE 71
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 71 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes For example:


x = 1
if x == 1
print(“True”)
————-— OUTPUT —————
File “< >”, line 2
if x == 1
^
SyntaxError: expected ‘:’
The parser repeats the statement at fault and marks the point where the
error was found with the symbol ‘^’. In the given example, the error
is detected at line 2, after the token ‘1’, since a colon (‘:’) is missing
there. File name (blank in the example to avoid any confusion) and line
number are also printed to make the error handling easier.
Another very common example of a syntax error is indentation error which
occurs due to incorrect indentation in the program. For instance, in the
given example the print(i) statement should be indented inside for loop.
For example:
count = 10
for i in range (count):
print(i)
————— OUTPUT —————
File “<ipython-input-1-a11740cc5449>”, line 3
print(i)
^
Indentation Error: expected an indented block
after ‘for’ statement on line 2

4.4 What is Exception


Even if a piece of code does not have a syntax error, it may still cause
a logical error during execution, an error that could not be detected be-
fore execution. Exceptions are raised when a logical error occurs during
72 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 72 15-10-2025 [Link]


ERROR AND EXCEPTION HANDLING IN PYTHON

program execution. For example, attempt to divide a number by zero, Notes


performing an operation on incorrect variable types like adding an integer
with a string. When an exception occurs, the normal flow of the program
is interrupted and an exception handler is looked for. If no handler is
found, the program terminates, and an error message is displayed. Dif-
ferent types of exceptions exist in Python. The type of exception that
has occurred in the program is printed as part of the error message. For
instance, in the given example, the last line of the error message indicates
the type of exception that occurred and a little detail based on the type
of exception. ZeroDivisionError is the name of the exception that deals
with the logical error of dividing any number by zero.
For example:
x = 10
y = 0
print(x / y)
————— OUTPUT —————
ZeroDivisionError Traceback (most recent call
last)
< > in <cell line: 3>()
1 x = 10
2 y = 0
——> 3 print(x / y)
ZeroDivisionError: division by zero
Exceptions can be caused by various factors, including invalid input,
resource unavailability, or any other unexpected behaviour. For instance,
the below given example expects an integer as an input and raises a
ValueError on receiving a string instead.
For example:
x = int(input(“Enter an integer value:”))
print(x)
————— OUTPUT —————
Enter an integer value: a
—————————————————————————————————————
PAGE 73
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 73 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ValueError Traceback (most recent call last)


<ipython-input-6-bccae38e0109> in <cell line:
1> ()
——> 1 x = int(input(“Enter an integer value:”))
2 print(x)
ValueError: invalid literal for int() with base
10: ‘a’
Exceptions may not be unconditionally fatal if handled appropriately in
the program. This ensures that a program can gracefully handle errors
and provide meaningful feedback to the users.

4.5 Handling Exceptions


Exceptions can be handled gracefully in Python programs through a
try-except statement. Exception handling not only improves the reliability
of the code but also allows for graceful error recovery and user-friendly
error messages.

4.5.1 The try-except Block


The try-except block is a fundamental construct in Python used for man-
aging exceptions. It provides a way to designate a code section where
exceptions may occur and offers a mechanism for capturing and handling
those exceptions. The try block encompasses the code segment that might
generate exceptions, while the except block outlines the approach for catching
and handling them. The try-except block operates in the following manner:
1. Initially, the try block, which consists of the statement(s) positioned
between the try and except keywords, are executed.
2. If no exception arises the execution of the try block is completed
and the except block is bypassed.
3. However, if an exception occurs during the execution of the try
block, the remaining portion of the try block is skipped, and the
program flow moves to the except block.
Python provides the ability to capture specific exceptions by specifying
the type of exception after the except keyword. By doing so, users can

74 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 74 15-10-2025 [Link]


ERROR AND EXCEPTION HANDLING IN PYTHON

customize the handling of different exceptions and implement quite specific Notes
error management. When the type of exception that occurred matches the
one specified after the except keyword, the corresponding except block
is executed, and the program execution continues after the try/except
block. For instance, as shown in the example below, ZeroDivisionError
is an exception name used to handle the logical error of division by zero.
For Example:
try:
# Code that might raise exceptions
x = int(input(“Enter Numerator:”))
y = int(input(“Enter Denominator:”))
print(x / y)
except ZeroDivisionError:
# Exception handling
print(“Denominator is Zero: Division by Zero
Error”)
print(“Done”)
————— OUTPUT —————
Enter Numerator: 5
Enter Denominator: 0
Denominator is Zero: Division by Zero Error
Done
————— OUTPUT —————
Enter Numerator: 5
Enter Denominator: 5
1.0
Done
By enclosing a specific set of statements within a try block and including
an except block without any specific label, we can effectively capture
any potential errors. This broad except clause is designed to handle all
possible exceptions that may arise as shown in the given example.

PAGE 75
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 75 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes For Example:


try:
x = int(input(“Enter Numerator:”))
y = int(input(“Enter Denominator:”))
print(x / y)
except:
print(“Invalid input”)
print(“Done”)
————— OUTPUT —————
Enter Numerator: 5
Enter Denominator: 0
Invalid input
Done
————— OUTPUT —————
Enter Numerator: 5
Enter Denominator: a
Invalid input
Done

4.5.2 Multiple Except Blocks


A try statement can consist of multiple except blocks, each serving as a
handler for distinct exceptions. However, only one handler will be ex-
ecuted at most. Additionally, an except clause has the option to specify
multiple exceptions by enclosing them in a tuple within parentheses.
For Example:
try:
x = int(input(“Enter Numerator:”))
y = int(input(“Enter Denominator:”))
print(x / y)

76 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 76 15-10-2025 [Link]


ERROR AND EXCEPTION HANDLING IN PYTHON

except ZeroDivisionError: Notes


print(“Denominator is Zero: Division by Zero
Error”)
except ValueError:
print(“Input not a number”)
print(“Done”)
————— OUTPUT —————
Enter Numerator: a
Input not a number
Done
For Example:
try:
x = int(input(“Enter Numerator:”))
y = int(input(“Enter Denominator:”))
print(x / y)
except(ZeroDivisionError, ValueError):
print(“Either Denominator is Zero or input
not a number”)
print(“Done”)
————— OUTPUT —————
Enter Numerator: a
Either Denominator is Zero or input not a number
Done

4.5.3 Else Block


The try-except statement can include an optional else clause, which must
appear after all the except clauses. This clause is beneficial for code that
needs to be executed when the try block does not raise any exceptions.
The else clause within a try-except block is triggered solely if no ex-
ceptions occur during the execution of the try block. If an exception is
raised within the try block, the else clause is skipped.

PAGE 77
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 77 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes For Example:


try:
x = int(input(“Enter Numerator:”))
y = int(input(“Enter Denominator:”))
z = x / y
except ZeroDivisionError:
print(“Denominator is Zero”)
else:
print(z)
————— OUTPUT —————
Enter Numerator: 3
Enter Denominator: 1
3.0

4.5.4 Finally Block


The try statement includes an optional clause known as the finally block.
It is designed to define cleanup actions that must be executed regardless
of whether an exception occurred or not. If a finally block is present,
it will be executed as the final step before the try statement completes,
irrespective of whether an exception was raised or not.
For Example:
try:
x = int(input(“Enter a number:”))
except ValueError as V:
print(“You had to enter a valid number”)
else:
print(x)
finally:
print(“the code completed”)

78 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 78 15-10-2025 [Link]


ERROR AND EXCEPTION HANDLING IN PYTHON

————— OUTPUT ————— Notes


Enter a number: a
You had to enter a valid number
the code completed
————— OUTPUT —————
Enter a number: 1
1
the code completed

4.6 Raising Exceptions


Python provides a mechanism for explicitly raising exceptions using the
raise statement. When a raise statement is encountered, it interrupts the
normal flow of the program and triggers the specified exception. This
capability is valuable when dealing with scenarios that are not covered by
existing built-in exceptions. By raising exceptions, you can communicate
the occurrence of a specific condition, allowing the program to handle it
appropriately. For example, the given program asks the user to input a
positive number and raises an exception if the input number is negative.
The argument provided with the raise statement determines the type of
exception to be raised.
For Example:
try:
x = int(input(“Enter a positive number:”))
if x < 0:
raise ValueError
except ValueError:
print(“Negative number not allowed”)
else:
print(x)
————— OUTPUT —————
Enter a positive number: -1
Negative number not allowed
PAGE 79
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 79 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ————— OUTPUT —————


Enter a positive number: 5
5

IN-TEXT QUESTIONS
1. What is an exception?
2. How many except statements can a try-except block have?
3. When is the finally block executed?
(a) when there is no exception
(b) when there is an exception
(c) only if some condition that has been specified is satisfied
(d) always
4. What is the purpose of the try block in Python error handling?
5. Which error is raised when an import statement fails to find
or load a module?
6. Which error/exception will be raised in the following code ?
a = [1, 2, 3]
print(a[4])

4.7 Nested Try Block


In Python, a nested try block is a construct where one try block is placed
within another try block. This allows for a more granular and fine-grained
exception handling approach. The nested try block is useful when you want
to handle exceptions separately at different levels of your code. In case there
is no handler available to handle the exception raised in a try block, the pro-
gram will initiate a search for a suitable handler in the outer try-except block.
Here is an example to illustrate the concept of nested try blocks in Python.
For Example:
try:
# Outer try block
x = int(input(“Enter the numerator:”))
y = int(input(“Enter the denominator:”))
80 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 80 15-10-2025 [Link]


ERROR AND EXCEPTION HANDLING IN PYTHON

try: Notes
# Inner try block
if y == 0:
print(“Denominator should not be zero”)
y = int(input(“Enter the denominator
again:”))
print(x / y)
except ZeroDivisionError:
# Exception handling specific to the in-
ner try block
print(“Denominator was zero”)
except ValueError:
# Exception handling specific to the outer
try block
print(“Numerator and Denominator should be
numbers”)
————— OUTPUT —————
Enter the numerator: 5
Enter the denominator: 0
Denominator should not be zero
Enter the denominator again: a
Numerator and Denominator should be numbers
Here in this example, on receiving zero as input for the denominator
initially, the program asks the user to enter the denominator again in
the inner try block. Since the user entered a string instead of a number
for the denominator, a ValueError is raised from the inner try block.
However, inner try block has no except block to handle ValueError and
hence outer try-except block is searched and executed.

4.8 Exception Chaining


To indicate that one exception is a direct result of another, the ‘raise’
statement offers an optional ‘from’ clause. By using exception chaining, the
code can retain the original exception context when raising a new exception.

PAGE 81
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 81 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes In the given example, the program asks the user to enter a positive number.
However, on receiving a string instead of a number, it raises an exception
and asks the user to re-enter the number from the except block. However,
if the re-entered number is zero a new exception is raised.
For Example:
try:
x = 5
y = int(input(“Enter a positive number:”))
except ValueError as V:
print(“You had to enter a valid number. Do
it again.”)
y = int(input(“Enter a positive number:”))
if y == 0:
raise ZeroDivisionError from V
else:
print(x / y)
————— OUTPUT —————
Enter a positive number: a
You had to enter a valid number. Do it again.
Enter a positive number: 0
————— OUTPUT —————
ValueError Traceback (most recent call last)
<ipython-input-5-490acdc67a58> in <cell line:
1> ()
2 x = 5
——> 3 y = int(input(“Enter a positive number:”))
4 except ValueError as V:
ValueError: invalid literal for int() with base
10: ‘a’
The above exception was the direct cause of
the following exception:

82 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 82 15-10-2025 [Link]


ERROR AND EXCEPTION HANDLING IN PYTHON

ZeroDivisionError Traceback (most recent Notes


call last)
<ipython-input-5-490acdc67a58> in <cell line:
1>()
6 y = int(input(“Enter a positive
number: “))
7 if y == 0:
——> 8 raise ZeroDivisionError from V
9 else:
10 print(x / y)
ZeroDivisionError:

4.9 Common Built-in Exceptions


Python has a comprehensive collection of built-in exceptions that encom-
pass a wide range of error types and exceptional circumstances. Famil-
iarity with these common exceptions is essential for effectively handling
exceptions and debugging. In this section, we will delve into some of
the commonly encountered built-in exceptions in Python.

4.9.1 TypeError
The ‘TypeError’ exception occurs when an operation or function is ap-
plied to an object of an unsuitable type. This situation can arise when
incompatible data types are combined or when a function is invoked with
incorrect arguments. For example, if the division operation is invoked
with string arguments
For Example:
try:
x = “ABC”
y = “DEF”
z = x/y

PAGE 83
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 83 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes except TypeError as T:


print(“Exception Detail:”, T)
print(“Incorrect type for division operation”)
else:
print(z)
————— OUTPUT —————
Exception Detail: unsupported operand type(s)
for /: ‘str’ and ‘str’
Incorrect type for division operation

4.9.2 ValueError
The ‘ValueError’ exception is triggered when a function is provided
with an argument of the correct type but with an unsuitable value. This
situation arises when a function anticipates a certain range of values
and receives a value that falls outside that range. For instance, the int()
function raises a ValueError on receiving a string as input as a string
cannot be converted to an integer.
For Example:
try:
x = “ABC”
y = int(x)
except ValueError as V:
print(“Exception Detail:”, V)
else:
print(z)
————— OUTPUT —————
Exception Detail: invalid literal for int()
with base 10: ‘ABC’

4.9.3 NameError
This exception occurs whenever a name being referenced in a statement
is not found globally. For instance, trying to access a variable that has

84 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 84 15-10-2025 [Link]


ERROR AND EXCEPTION HANDLING IN PYTHON

not been defined. The given program defines a variable num1, but ac- Notes
cidentally uses the variable num and hence the error. Another common
error scenario is when the developer mistakenly uses an incorrect function
name like ‘prints’ instead of ‘print.’
For Example:
num1 = int(input(“Enter an integer:”))
print(“Received integer is:”, num)
————— OUTPUT —————
Enter an integer: 5
—————————————————————————————————————
NameError Traceback (most recent call last)
<ipython-input-30-91408e397ce0> in <cell line:
2>()
1 num1 = int(input(“Enter an integer”))
——> 2 print(“Received integer is:”, num)
3
NameError: name ‘num’ is not defined
For Example:
num1 = int(input(“Enter an integer:”))
prints(“Received integer is:”, num1)
————— OUTPUT —————
Enter an integer: 5
—————————————————————————————————————
NameError Traceback (most recent call last)
<ipython-input-31-94b319a8effa> in <cell line:
2>()
1 num1 = int(input(“Enter an integer”))
——> 2 prints (“Received integer is:”, num1)
3
NameError: name ‘prints’ is not defined

PAGE 85
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 85 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 4.9.4 Most used Built-in Exceptions


Following are some of the most used built-in exceptions available in Python.
Exception Name Description
ZeroDivisionError Occurs when the denominator in division operation
is zero
ArithmeticError Occurs when an error is encountered during numeric
calculations
FloatingPointError Occurs when a floating-point calculation encoun-
ters an error
ImportError Occurs when an attempt is made to import a module
that does not exist
IndexError Occurs when trying to access an index of a sequence
(such as a list, tuple, or string) that is out of range
OSError Occurs when a system-related operation encounters
an error
OverflowError Occurs when the result of a numeric calculation
exceeds the maximum representable value

4.10 Best Practices for Exception Handling


The following are the best practices for efficient exception handling in
the code:
‹ Practicing good exception handling involves narrowing the scope
of your try block. This means focusing on the specific code that
may raise exceptions, rather than encompassing larger sections of
code in try block.
‹ By narrowing the scope, you can effectively isolate and handle
exceptions, which improves the readability and maintainability of
your code.
‹ Meaningful error messages including the relevant variables and
the execution context should be provided to clearly communicate
the cause of the exception to the user or developer, helping them
understand the issue and how to resolve it.

86 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 86 15-10-2025 [Link]


ERROR AND EXCEPTION HANDLING IN PYTHON

‹ It is crucial to gracefully close resources when your code utilizes Notes


external resources like files, network connections, or database
connections, ensuring proper release even in the presence of exceptions
to prevent resource leaks and maintain program integrity.
‹ Offering alternative paths or fallback mechanisms when an exception
occurs can be beneficial. For instance, if an incorrect input is given
by the user, the program could prompt the user to enter a different
value or provide default values.
‹ By handling exceptions gracefully and striving for recovery, you
can develop more robust and user-friendly software applications.

4.11 Summary
Error and exception handling are indispensable aspects of software
development. It enables developers to effectively manage unexpected
circumstances and ensure the reliability of their code. Python distin-
guishes between two types of errors: syntax errors and exceptions.
Developers employ try-except blocks to handle exceptions in Python. A
try block can have multiple except blocks to address various types of
exceptions. In addition to exception handling, Python allows the use of
the else and finally clauses within a try-except block. Python provides
a wide range of built-in exceptions that cover common error scenarios,
such as ValueError, TypeError, ZeroDivisionError, etc. By understanding
the different types of exceptions, developers can appropriately handle
specific error conditions.
Adhering to best practices when handling exceptions can help to create
robust and maintainable code. A crucial guideline is to limit the scope
of the try block to the code that may raise an exception. This approach
isolates potential errors and enhances code readability. It is also advisable
to provide meaningful error messages that convey relevant information
to users or developers, facilitating the debugging and troubleshooting
process. Anticipating potential errors and providing alternative logic,
developers can enhance their code’s resilience and enhance the user
experience.

PAGE 87
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 87 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes
4.12 Answers to In-Text Questions
1. An exception occurs when a logical error occurs during program
execution. Example: Division by Zero exception
2. There has to be at least one except statement.
3. (d) always [The finally block is always executed.]
4. The purpose of the try block in Python error handling is to define
the block of code where an exception may occur.
5. ImportError
6. IndexError

4.13 Self-Assessment Questions


1. Create a Python program that requests the user to input two numbers
and performs their division. Implement exception handling to deal
with non-numeric input values.
2. Implement a Python program that asks the user to enter a negative
number and prints its absolute value. Utilize exception handling to
handle scenarios where the user inputs a positive number.
3. What are the different types of errors and exceptions that can occur
in Python programs?
4. State best practices for writing reliable and robust code using exception
handling.
5. What is the role of the finally block in exception handling?
6. How can you raise exceptions explicitly using the raise statement in
Python?
7. What is exception chaining?
8. Provide examples of commonly encountered built-in exceptions in
Python.
9. Why is it important to provide meaningful error messages when
handling exceptions?
10. How does effective exception handling contribute to the development
of more robust and user-friendly software applications?

88 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 88 15-10-2025 [Link]


ERROR AND EXCEPTION HANDLING IN PYTHON

Notes
4.14 References
‹ Balagurusamy E., (2018). Introduction to Computing and Problem
Solving using Python (2 ed.). McGraw Hill Education.
‹ Taneja, S., & Kumar, N. (2018). Python Programming- A modular
Approach. India: Pearson Education.
‹ Saeed, A., Ayeva, A., Ayeva, K. (2020). Python In - Depth: Use
Python Programming Features, Techniques, and Modules to Solve
Everyday Problems. India: BPB PUBN.
‹ Kamthane, A. N., & Kamthane, A. A. (2020). Programming and
Problem Solving with Python. McGraw-Hill Education.

PAGE 89
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_02_Lesson [Link] 89 15-10-2025 [Link]


PFUP_Unit_02_Lesson [Link] 90 15-10-2025 [Link]
UNIT - III
User Defined Functions

PAGE 91
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 91 09-10-2025 [Link]


PFUP_Unit_03_Lesson [Link] 92 09-10-2025 [Link]
L E S S O N

5
User Defined Functions
in Python
Mansi Sood
Assistant Professor
Shyama Prasad Mukherji College
Email-Id: [Link]@[Link]

STRUCTURE
5.1 Learning Objectives
5.2 Introduction
5.3 'H¿QLQJ )XQFWLRQV
5.4 3DVVLQJ $UJXPHQWV WR )XQFWLRQV
5.5 Scope of Variables
5.6 3XUSRVH RI )XQFWLRQV
5.7 5HFXUVLYH )XQFWLRQV
5.8 Summary
5.9 Answers to In-Text Questions
5.10 Self-Assessment Questions
5.11 References

5.1 Learning Objectives


After completion of this lesson, you will be able to:
‹ Understand the concept of function definition in Python and its role in code
organization and reusability.
‹ Explore the significance of docstrings in documenting functions and improving code
readability.
‹ Recognize the different ways to pass arguments to functions, including positional
and keyword arguments.

PAGE 93
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 93 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ‹ Understand the concept of default arguments and their role in


allowing functions to be called with fewer arguments.
‹ Define recursive functions.

5.2 Introduction
To create a programming application, it is best to break down a big program
into smaller modules and use them repeatedly wherever possible. Functions
act as independent modules within the program, making the code easier
to read and manage. In Python programming, functions are like building
blocks that help organize and reuse code. They let you give a name to a
block of code so you can use it again later. Instead of writing the same
code over and over, you can just use the function. In this chapter, you
will learn how to create functions, pass information to them, use default
values, and get results back from them in Python programming.

5.3 Defining Functions


In Python, the ‘def’ keyword marks the beginning of a function defini-
tion. It is followed by the function name, a set of parentheses that may
contain the comma-separated formal parameters, followed by a colon (:).
The parentheses may contain zero or more parameters (also called argu-
ments) that the function requires. The function’s body starts on the next
line and must be indented. Generally, a function’s body consists of a
block of statements to be executed. Optionally, the first statement in the
function body can be a docstring, which is a string literal that serves as
documentation to state the function’s purpose. The given example defines
a function named ‘func’ that prints the message “My first function’’ This
function does not require any parameters.
For Example:
def func():
‘‘‘ This is an example function named as ‘func’
to demonstrate how to define functions in Python’’’
print(“My first function”)
func()

94 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 94 09-10-2025 [Link]


USER DEFINED FUNCTIONS IN PYTHON

————— OUTPUT ————— Notes


My first function
Here is another example of a function that takes two numbers as input
from the user and displays their sum as the result.
For Example:
def func():
‘‘‘this is an example function
to demonstrate how to define functions
in python’’’
a = int(input(“Enter first number:”))
b = int(input(“Enter second number:”))
print(“The sum of the two numbers:”, a + b)

func()
————— OUTPUT —————
Enter first number: 5
Enter second number: 7
The sum of the two numbers: 12
When a function is defined, its name becomes associated with the corre-
sponding function object in the symbol table. This association allows the
interpreter to identify the function as a user-defined entity. Additionally,
multiple names can refer to the same function object, providing alternative
ways to access it as shown in the given example.
For Example:
def func():
‘‘‘this is an example function
to demonstrate how to define functions
in python’’’
print(“My first function”)

func2 = func

PAGE 95
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 95 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes func()
func2()
————— OUTPUT —————
My first function
My first function
The return statement is employed to explicitly specify the single or mul-
tiple values to be returned from a user-defined function. The function in
the given example returns two values.
For Example:
def func():
‘‘‘this function returns an integer and a string’’’
x = 5
y = “test”
return x, y

a,b = func()
print(“a, b:”, a, b)
————— OUTPUT —————
a, b: 5 test
Functions without a return statement implicitly return the None object
i.e., if a function reaches its end without encountering a return statement,
it returns None. The interpreter usually hides the None value when it is
the only return value. However, if desired, it can be displayed using the
print() function as shown in the example below.
For Example:
def func():
‘‘‘this function implicitly returns None’’’
x = 5
y = “test”
a = func()
print(“a:”, a)

96 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 96 09-10-2025 [Link]


USER DEFINED FUNCTIONS IN PYTHON

————— OUTPUT ————— Notes


a: None
It is recommended to use descriptive names for functions that reflect
their purpose clearly and follow the Python naming conventions (i.e.,
use lowercase letters with underscores for function names). Also, it is
advisable to use verb-noun combinations to convey the actions performed
by the function. For example, calculate_sum to find the sum of the input
parameters.

IN-TEXT QUESTIONS
1. In python, which keyword is used to declare user-defined
functions?
2. The location where we can find a variable and also access it
if required is called the ______________.
3. Which variables are defined and declared outside any function,
are not specified to any function and can be used by any part
of the program?
4. What is the purpose of the return statement in a function?
5. Which of the following refers to mathematical function in
python?
(a) sqrt
(b) rhombus
(c) add
(d) rhombus

5.4 Passing Arguments to Functions


Functions in Python have the flexibility to accept zero or more arguments.
Multiple arguments can be included, separated by commas. Arguments are
used to pass values or data into functions for processing. These arguments
are specified within the parentheses of the function definition. The given
example accepts a single argument and displays its value.

PAGE 97
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 97 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes For Example:


def Display(str):
‘‘‘ This function accepts a parameter and displays
it’’’
print(str)

Display(“Hello there!”)
————— OUTPUT —————
Hello there!

The terms parameter and argument are generally used interchangeably to


refer to the information passed into a function. However, formal parameters
are the variables declared inside the parenthesis of a function definition
and serve as placeholders for the actual values to be passed when the
function is called. In contrast, arguments refer to the actual values(also
called actual arguments) that are provided when the function is invoked.
For instance, in the given example, a and b are formal parameters. Num-
bers 10 and 20 are actual parameters or arguments.
For Example:
def calculate_sum(a, b): # Formal parameters are a
and b
‘‘‘ This function takes two parameters and displays
their sum’’’
print(“The sum of the received parameters is:”, a
+ b)

calculate_sum(10, 20) # Actual parameters are 10


and 20
————— OUTPUT —————
The sum of the received parameters is: 30
By default, when calling a function, the correct number of arguments
must be provided. This means that if a function expects two arguments,
it should be called with exactly two arguments, neither more nor less. In
98 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 98 09-10-2025 [Link]


USER DEFINED FUNCTIONS IN PYTHON

the given example, the function calculate_sum has two arguments a and Notes
b. When the function is called, the values passed for these arguments
will be used to compute the sum of passed values. The example also
shows the error message on receiving a single argument instead of two
as specified by the function definition.
For Example:
def calculate_sum(a, b):
‘‘‘ This function calculates the sum of its
input arguments’’’
sum = a + b
print(“sum of the arguments:”, sum)

calculate_sum(3, 4)
calculate_sum(3)
————— OUTPUT —-————
sum of the arguments: 7
—————————————————————————————————————
TypeError Traceback (most recent call last)
<ipython-input-4-00bd304967dc> in <cell line: 6>()
4 print(“sum of the arguments:”, sum)
5 calculate_sum(3,4)
——> 6 calculate_sum(3)

TypeError: calculate_sum() missing 1 required


positional argument: ‘b’

5.4.1 Positional and Keyword Arguments


Python has two mechanisms for passing arguments to a function: Positional
arguments and Keyword arguments. Positional arguments are passed based
on their position in the function call. The order and number of arguments
in the function call must match the order and number of parameters in
the function definition.

PAGE 99
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 99 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes Keyword arguments allow arguments to be specified by their corresponding


parameter names during a function call. This approach eliminates the need
to remember the order of arguments. The given example demonstrates
using positional and keyword arguments while invoking a function. In
the first invocation of the function param_order, keyword arguments are
used to pass the values. However, the second invocation uses positional
arguments. This implies that the first argument is assigned to the first
formal parameter, the second argument to the second formal parameter,
and so on. In the third invocation, again positional arguments are being
used but a string is passed to the first formal parameter (a) and an in-
teger to the second formal parameter (b). Hence, it causes an error as a
string is being added to an integer variable.
For Example:
def param_order(a, b, str):
‘‘‘ This function demonstrates that order of
parameters is important’’’
sum = a + b
print(str, sum)
param_order(str = “sum of the arguments:”, b=3, a=4)
#keyword arguments
param_order(3, 4, “sum of the arguments:”) #positional
arguments in correct order
param_order(“sum of the arguments:”, 3, 4) #positional
arguments
————— OUTPUT —————
sum of the arguments: 7
sum of the arguments: 7
—————————————————————————————————————
TypeError Traceback (most recent call last)
<ipython-input-5-c9bbf26647ce> in <cell line: 6>()
4 print(str, sum)
5 param_order(str = “sum of the arguments:”, b
= 3, a = 4)
——> 6 param_order(“sum of the arguments:”, 3, 4)

100 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 100 09-10-2025 [Link]


USER DEFINED FUNCTIONS IN PYTHON

<ipython-input-5-c9bbf26647ce> in param_order(a, Notes


b, str)
1 def param_order(a, b, str):
2 ‘‘‘this function demonstrates that order
of parameters is important’’’
——> 3 sum = a + b
4 print(str, sum)
5 param_order(str = “sum of the arguments:”,
b=3,a=4)
TypeError: can only concatenate str(not “int”)
to str
Important points to note:
1. When making a function call, keyword arguments should come after
positional arguments as shown in the given example.
For Example:
def param_order(a, b, str):
‘‘‘this function demonstrates Positional and
Keyword arguments’’’
print(a, b, str)
param_order(a = 3, b = 4.0, “test string”)
————— OUTPUT —-————
File “<ipython-input-11-0b6d29383af3>”, line 6
param_order(a = 3, b = 4.0, “test string”)
^
SyntaxError: positional argument follows keyword
argument
2. All the provided keyword arguments must correspond to one of the
function’s defined arguments. For example, in the following code,
“strng” would not be a valid argument for the defined “str” variable
in the function.
For Example:
def param_order(a, b, str):
‘‘‘this function demonstrates Positional and
Keyword arguments’’’
PAGE 101
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 101 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes print(a, b, str)


param_order(3, 4.0, strng = “test string”)
————— OUTPUT —————
TypeError Traceback (most recent call last)
<ipython-input-12-3972ec4284eb> in <cell line:
5>()
3 print(a, b, str)
4
——> 5 param_order(3, 4.0, strng = “test string”)
TypeError: param_order() got an unexpected keyword
argument ‘strng’
3. It is not permissible to assign a value to an argument more than
once. The following example demonstrates a failure that occurs
when this restriction is violated
For Example:
def param_order(a, b, str):
‘This function demonstrates Positional and Keyword
arguments’’’
print(a, b, str)
param_order(3, 4.0, str = “test string”, b = 4.0)
————— OUTPUT ——-———
TypeError Traceback (most recent call last)
<ipython-input-13-b3dcd8654e2e> in <cell line:
5>()
3 print(a, b, str)
4
——> 5 param_order(3, 4.0, str = “test string”, b
= 4.0)

TypeError: param_order() got multiple values for


argument ‘b’

102 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 102 09-10-2025 [Link]


USER DEFINED FUNCTIONS IN PYTHON

5.4.2 Default Arguments Notes


One of the most valuable forms of defining functions involves specifying
default values for one or more arguments. This allows the function to
be called with fewer arguments than it is originally defined to accept.
Default arguments are assigned a predetermined value in the function
definition, serving as a fallback option if no argument is provided during
the function call.
To set default arguments, values are assigned to the corresponding pa-
rameters in the function definition. Functions with default arguments can
then be invoked without explicitly providing values for those specific
arguments. In such cases, if no value is passed for a particular argument,
the default value specified in the function definition will be utilized. For
instance, the default_values function defined in the given example can
be called in three different ways:
1. It can be called by passing values to all three parameters.
2. Passing values to the first two parameters and using the default
value for the third parameter.
3. Passing value to only the first mandatory parameter and using the
default values for the second and third parameters.
Passing no parameters at all causes an error condition as the first param-
eter is a mandatory parameter and does not have a default value. Also,
notice the fourth call to the function default_values, it is called by passing
two values as the arguments. The second argument passed is sent to the
second formal parameter and the third one is set to use the default value.
For Example:
def default_values(a, b=4.0, str = “basic string”):
‘‘‘ This function demonstrates how default_values
are passed to function arguments’’’
print(a, b, str)

default_values(3, 5.0, “new string”)


default_values(3, 5.0)
default_values(3)

PAGE 103
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 103 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes default_values(3, “new string”)


default_values()
3 5.0 new string
3 5.0 basic string
3 4.0 basic string
3 new string basic string
————— OUTPUT —————
TypeError Traceback (most recent call last)
<ipython-input-15-9731a7f56f81> in <cell line: 9>()
7 default_values(3)
8 default_values(3, “new string”)
——> 9 default_values()
TypeError: default_values() missing 1 required
positional argument: ‘a’
In function definition, a mandatory argument can not follow a default
argument. For instance, defining the optional or the default argument
before a mandatory argument in the given example causes an error
scenario.
For Example:
def default_values(a, b = 4.0, c):
‘‘‘ This function demonstrates default_values’’’
print(a, b, c)
default_values(3, 5.0, 6.0)
————— OUTPUT —————
File “<ipython-input-16-be3a4b62be68>”, line 1
def default_values(a, b=4.0, c):
^
SyntaxError: non-default argument follows default
argument
A function having default arguments can also be called using positional
arguments. There could be many ways to call such a function. The given

104 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 104 09-10-2025 [Link]


USER DEFINED FUNCTIONS IN PYTHON

example demonstrates the same using one mandatory argument a and Notes
three optional (default) arguments b, c, and str.
For Example:
def default_values_pos_arg(a, b = 4, c = 5.0, str =
“test string”):
‘‘‘This function demonstrates how default_
values can be used when passing positional
arguments’’’
print(a, b, c, str)

default_values_pos_ #1 positional argument for


arg(1) mandatory parameter
default_values_pos_ #1 Keyword argument for
arg(a = 1) mandatory parameter
default_values_pos_ #2 Keyword arguments (for
arg(a = 1, c = 6.0) mandatory parameter a and
optional parameter c)
default_values_pos_ # 2 Keyword arguments (for
arg(c = 6.0, a = 1) mandatory a and optional c
but not in defined order)
default_values_pos_ #2 Positional parameter
arg(1, 2) for a and b
default_values_pos_ #1 positional and 1
arg(1, c = 6.0) keyword parameter

————— OUTPUT -—————


1 4 5.0 test string
1 4 5.0 test string
1 4 6.0 test string
1 4 6.0 test string
1 2 5.0 test string
1 4 6.0 test string

PAGE 105
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 105 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes
5.5 Scope of Variables
In Python programming, variables can have either local or global scope,
which determines their accessibility and visibility in different parts of
the program. The properties of a local variable are as follows:
1. When variables are declared within a function, they have a local
scope, meaning they are only accessible within that specific function.
2. Local variables are created when the function is called and cease
to exist once the function completes its execution. They are useful
for storing temporary or intermediate values that are specific to a
particular function.
3. Trying to access a local variable outside of its function will result
in an error since it is out of scope.
For Example:
def demo_local_scope(a): # a is a local variable
‘‘‘This function demonstrates the local scope
of a variable’’’
print(“value of a is:”, a)

demo_local_scope(5)
print(“a is:”, a) # This line will generate an error
as a is a local variable, can’t be accessed here
————— OUTPUT —————
value of a is: 5
—————————————————————————————————————
NameError Traceback (most recent call last)
<ipython-input-15-a3d655af4260> in <cell line:
7>()
5
6 demo_local_scope(5)
——> 7 print(“value of a is:”, a) # this line will
generate an error as a is a local variable and does
not exist here
106 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 106 09-10-2025 [Link]


USER DEFINED FUNCTIONS IN PYTHON

8 Notes
9
NameError: name ‘a’ is not defined
4. These variables are independent of other variables with the same
name in other functions or the global scope. For instance, in the
given example, local variable a defined inside function demo_local_
scope receives a value of 5 and the one defined inside function
demo_local_scope_again receives a value of 10. They both come
into existence when their corresponding functions are invoked and
then cease to exist.
For Example:
def demo_local_scope(a): # a is a local variable
‘‘‘ This function demonstrates the local scope
of a variable’’’
print(“value of a is:”, a)

def demo_local_scope_again(a): # a is a local


variable
‘‘‘ This function demonstrates the local scope
of a variable’’’
print(“value of a is:”, a)
demo_local_scope(5)
demo_local_scope_again(10)
————— OUTPUT —————
value of a is: 5
value of a is: 10
The properties of a global variable are as follows:
1. Variables declared outside of any function, at the top level of the
program, have a global scope.
2. Global variables are accessible from anywhere within the program,
including inside functions.
3. Global variables retain their values throughout the program’s
execution until they are explicitly changed.

PAGE 107
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 107 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 4. Global variables are handy for storing information that needs to be
shared and accessed across multiple functions or modules.
For Example:
b = 10 # This is global variable b
def demo_local_scope(a): # a is a local variable,
b is global
print(“value of a is:”, a)
print(“b is accessible inside function:”, b)

demo_local_scope(5)
print(“b is accessible outside function:”, b)
————— OUTPUT —————
value of a is: 5
b is accessible inside function: 10
b is accessible outside function: 10
5. To modify a global variable inside a function, you need to use the
‘global’ keyword to indicate that the variable refers to the global
scope. Without using the ‘global’ keyword, assigning a value to a
variable inside a function will create a new local variable with the
same name, leaving the global variable unchanged.
For Example:
a = 5
def global_var_in_func():
a = 15 # A local variable a has been defined
and allocated a value 15
print(‘The value of a in function:’, a) # This
will print local variable a i.e. 15

global_var_in_func()
print(‘The value of a outside function:’, a) #local
a doesn’t exist here, it prints global a

108 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 108 09-10-2025 [Link]


USER DEFINED FUNCTIONS IN PYTHON

————— OUTPUT ————— Notes


The value of a in function: 15
The value of a outside function: 5

For Example:
a = 5
def global_var_in_func():
global a
print(‘The value of a in function:’, a) # this
will print global variable a having value 5
a = 15 # Accessing global a and its value is
changed to 15
print(‘The value of a in function:’, a) # this
will print global variable a having value 15
global_var_in_func()
print(‘The value of a outside function:’, a) # prints
global a and the value is 15 as set in the func
————— OUTPUT —————
The value of a in function: 5
The value of a in function: 15
The value of a outside function: 15
It is recommended to limit the use of global variables to maintain code clarity
and prevent unintended side effects and accidental changes to the variables.
Understanding variable scope in Python is essential for writing well-
structured and maintainable code. By managing variable scope effectively,
you can control their visibility and ensure their values are accessible
where needed, promoting code clarity, and avoiding naming conflicts.

5.6 Purpose of Functions


Functions in Python programming serve the purpose of performing spe-
cific tasks by encapsulating a block of code and giving it a name. They
offer several advantages:
PAGE 109
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 109 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 1. Organization: Functions help break down programs into smaller,


manageable parts, improving clarity and ease of maintenance.
2. Reusability: Once defined, functions can be called multiple times
from different parts of the program, avoiding repetition, and promoting
efficiency.
3. Modularity: Functions enable the separation of different tasks into
independent modules, enhancing code readability and simplifying
testing and debugging (the process of finding and removing errors
from code).
4. Abstraction: Functions hide the internal details, allowing users to
focus on high-level functionality rather than implementation specifics.
The following example demonstrates all the above advantages. The pro-
gram is divided into small and manageable parts. First, a display function
is created to print the arguments along with the custom messages passed
as arguments to the function. This helps to reuse the code of the display()
function every time a variable and the associated description is to be printed.
get_input function is defined to make a separate module that asks the user,
the required input. Functions – sum() and divide() add and divide the input
arguments. The divide() function is reused to calculate the average of two
numbers. get_input_and_process() function can be exposed to the users to
find the sum, division, and average of two numbers taken as inputs from the
user. Users need not know the details of how the function is implemented.
For Example:
‘‘‘ a program to display the benefits of using
functions in programming ’’’
def Display(a, str1, b = None, str2 = None):
print(str1, a)
if b != None:
print(str2, b)

def get_input():
a = int(input(“Enter first number:”))
b = int(input(“Enter second number:”))
return a, b
110 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 110 09-10-2025 [Link]


USER DEFINED FUNCTIONS IN PYTHON

def sum(a, b): Notes


return a + b

def divide(a, b):


return a / b

def get_input_and_process():
x, y = get_input()
Display(x, “first number:”, y, “second number:”)
sum_x_y = sum(x, y)
Display(sum_x_y, “sum of the input numbers:”)
Display(divide(x, y), “division of the input
numbers:”)
Display(divide(sum_x_y, 2), “average of the input
numbers:”)

get_input_and_process()
————— OUTPUT —————
Enter first number: 20
Enter second number: 10
first number: 20
second number: 10
sum of the input numbers: 30
division of the input numbers: 2.0
average of the input numbers: 15.0

5.7 Recursive Functions


Recursive functions in Python provide a powerful approach to solving
complex problems by breaking them down into smaller subproblems. Here
are some key points to grasp about recursive functions:
1. Recursive functions consist of two vital parts: the recursive case
and the base case.

PAGE 111
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 111 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 2. The recursive case determines when the function calls itself, usually
with smaller input.
3. The base case acts as the stopping condition, ending the recursive
calls and producing a result.
For Example:
‘‘‘ this function calculates the sum of n natural
numbers recursively ’’’
def sum(n):
if n == 1: # base case: terminate recursion
when n is 1
return 1
ans = n + sum(n-1) # recursive step: call sum
function recursively to find sum of n-1 natural
numbers
return ans

sum(5)
————— OUTPUT —————
15
The given example calculates the sum of n natural numbers. For n = 5,
sum(5) is called sum (5) calls sum(4); sum(4) calls sum(3); sum(3) calls
sum(2) and sum(2) calls the base case sum(1). The sequence of execution
can be depicted as follows:

15
sum (5)
10
ans = 5 + sum (4) 6
ans = 4 + sum (3)
3
ans = 3 + sum (2) 1
ans = 2 + sum (1)
ans = 1

112 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 112 09-10-2025 [Link]


USER DEFINED FUNCTIONS IN PYTHON

4. Ensuring that the recursive calls eventually reach the base case is Notes
crucial to avoid infinite recursion. For example, the given programs
always execute the recursive step first and hence the base case is
never reached.
For Example:
‘‘‘ this function calculates sum of n natural
numbers recursively
however, the base case is never reached as it
always executes after recursive step
hence this code causes infinite recursion’’’
def sum(n):
ans = n + sum(n-1) # recursive step: call sum
function recursively to find sum of n-1 natural
numbers
if n == 1: # base case: terminate recursion
when n is 1
return 1
return ans

sum(5)
————— OUTPUT —————
RecursionError Traceback (most recent call last)
<ipython-input-45-2eb14de6246f> in <cell line:
9>()
7 return ans
8
——> 9 sum(5)

1 frames
... last 1 frames repeated, from the frame below ...

<ipython-input-45-2eb14de6246f> in sum(n)

PAGE 113
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 113 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 2 however, the base case is never reached as


it always execute after recursive step and hence
this code causes infinite recursion’’’
3 def sum (n):
——> 4 ans = n + sum(n-1) # recursive step: call
sum function recursively to find sum of n-1 natural
numbers
5 if n == 1: # base case: terminate
recursion when n is 1
6 return 1
RecursionError: maximum recursion depth
exceeded
When utilizing recursive functions, it is essential to design them carefully
and have a good understanding of the problem at hand.

5.8 Summary
Functions are an essential aspect of Python programming, allowing for code
organization, reusability, and modularity. They provide a way to encap-
sulate a block of code and invoke it whenever needed. By understanding
how to define functions, pass arguments, utilize default arguments, and
return values, users can gain the ability to create powerful and flexible
code. With this knowledge, they can enhance their Python programs and
write robust and efficient code.

5.9 Answers to In-Text Questions


1. def
2. scope of a variable.
3. Global variable
4. to return a value to the caller
5. (a) sqrt

114 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 114 09-10-2025 [Link]


USER DEFINED FUNCTIONS IN PYTHON

Notes
5.10 Self-Assessment Questions
1. Create a Python function that determines whether a given number
is prime or not.
2. Implement a Python function to identify the largest number among
two or three given numbers.
3. What are the different ways to pass arguments to functions in Python?
Describe the differences between positional and keyword arguments.
4. What are default arguments, and how do they allow functions to be
called with fewer arguments? Provide an example.
5. How can you determine the order and number of arguments required
for a function call based on its definition?
6. Can a function be called with more arguments than specified in its
definition? Explain why or why not.
7. What is a docstring, and why is it beneficial to include it in function
definitions? How does it improve code readability?

5.11 References
‹ Balagurusamy E., (2018). Introduction to Computing and Problem
Solving using Python (2 ed.). McGraw Hill Education.
‹ Saeed, A., Ayeva, A., Ayeva, K. (2020). Python In - Depth: Use
3\WKRQ 3URJUDPPLQJ )HDWXUHV 7HFKQLTXHV DQG 0RGXOHV WR 6ROYH
Everyday Problems. India: BPB PUBN.
‹ Kamthane, A. N., & Kamthane, A. A. (2020). Programming and
Problem Solving with Python. McGraw-Hill Education.

PAGE 115
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_03_Lesson [Link] 115 09-10-2025 [Link]


PFUP_Unit_03_Lesson [Link] 116 09-10-2025 [Link]
UNIT - IV
Built-in Data Structures

PAGE 117
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 117 09-10-2025 [Link]


PFUP_Unit_04_Lesson [Link] 118 09-10-2025 [Link]
L E S S O N

6
Built-in Data Structures
in Python
Mansi Sood
Assistant Professor
Shyama Prasad Mukherji College
Email-Id: [Link]@[Link]

STRUCTURE
6.1 Learning Objectives
6.2 Introduction
6.3 Strings
6.4 Lists
6.5 Tuples
6.6 Sets
6.7 Dictionaries
6.8 Data Structures with Loop and Conditional Statements
6.9 Summary
6.10 Answers to In-Text Questions
6.11 Self-Assessment Questions
6.12 References

6.1 Learning Objectives


After completion of this lesson, you will be able to:
‹ Understand the characteristics and properties of built-in data structures in Python
including strings, lists, tuples, sets, and dictionaries.
‹ Manipulate and access data stored in built-in data structures using indexing, slicing,
and built-in functions.
‹ Apply built-in functions, methods, and operators specific to strings, lists, tuples, sets,
and dictionaries effectively in Python programming.
PAGE 119
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 119 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ‹ Recognize the appropriate use cases for each data structure and
choose the most suitable one based on specific requirements.
‹ Develop problem-solving skills by applying the knowledge of data
structures in practical programming scenarios.

6.2 Introduction
Python is known for its versatility and power as a programming language,
providing an extensive selection of pre-existing data structures that fa-
cilitate efficient organization, manipulation, and storage of data. Among
these fundamental data structures in Python are strings, lists, tuples,
sets, and dictionaries. Each of these data structures possesses distinct
qualities, properties, and functions designed to cater to diverse program-
ming requirements. With each data structure serving specific purposes,
they offer unique benefits in terms of performance, adaptability, and
functionality. Developing proficiency in utilizing these data structures,
and comprehending their properties along with operations is essential to
write optimized and effective code capable of addressing a wide array
of programming tasks.

6.3 Strings
One of the most frequently used data structures in Python - strings,
represent collections of characters and can be enclosed either in single
quotes (' ') or double quotes (" "). You may check the type of a variable
by using type() function.
For example:
str1 = “test string”
str2 = ‘another string’
str3 = ‘ ’ #creates an empty string
print(type(str1), type(str2))
————— OUTPUT —————
Str(<class ‘str’> <class ‘str’>

120 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 120 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

The example below shows another method to create a string. Notes


For example:
str1 = str(“test string”)
str2 = str() #empty string
print(type(str1), type(str2))
print(str1, str2)
————— OUTPUT —————
<class ‘str’> <class ‘str’>
test string
Strings are immutable, which implies that they cannot be modified once
created. This is explained in detail below.
If a string includes a single quote but no double quotes, it is enclosed
within double quotes. Otherwise, if it contains double quotes, it is en-
closed within single quotes. Also, ‘\’ can be used to escape quotes. This
implies that ‘\’ or a double quote can be used to treat a single quote (‘)
as a part of the string. For instance, the example below prints a string
“It’s easy’’ using the two mentioned methods.
For example:
print(“It’s easy”)
print(‘It\’s easy’)
————— OUTPUT —————
It’s easy
It’s easy
Special characters like ‘\n’ for representing a newline have a back-
slash (‘\’) character to identify them. To prevent special characters
from being interpreted when preceded by a backslash, you can utilize
raw strings by adding an ‘r’ before the initial quote as shown in the
example below.
For example:
print(“Read the file in C:\new_folder”)
# \n in C:\new_folder is treated as a
special character here

PAGE 121
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 121 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes print(r“Read the file in C:\new_folder”)


#adding r (raw string) prevents \n to be
treated as a special character
————— OUTPUT —————
Read the file in C:
ew_folder
Read the file in C:\new_folder
Strings offer a range of operations, such as concatenation, indexing,
slicing, etc. which empower users with robust string manipulation and
text processing abilities.

6.3.1 Concatenation
The process of merging multiple strings into a single string is known as string
concatenation. ‘+’ operator is used to concatenate strings and ‘*’ operator is
used to repeat strings. The given example shows the usage of ‘+’ and ‘*’.
For Example:
str1 = “First String”
str2 = “Second String”
print(str1+str2)
print(str1*2)
—————- OUTPUT —————
First StringSecond String
First StringFirst String
When two or more string literals (i.e., those enclosed between quotes) are
placed consecutively, they are automatically combined into a single string.
This capability proves especially handy when you need to split lengthy strings.
However, it is important to note that this concatenation feature only applies to
literals and does not work with variables. The below example displays the same.
For Example:
str1 = (“Long strings literals can be”
“broken down into multiple lines like this”)
str2 = “two strings” “concatenated”

122 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 122 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

print(str1) Notes
print(str2)
#str3 = str1 str2 - string variable cannot be
concatenated like this
————— OUTPUT —————
Long strings literals can be broken down into
multiple lines like this
two stringsconcatenated

6.3.2 In and Not In Operator


The in and not in operators are utilized to determine if a string exists
within another string. It evaluates to True if the string is found, and False
if the string is not found.
For Example:
string = “TestString”
if ‘Test’ in string:
print(‘Test found’)
if ‘test’ not in string: #Python is case
sensitive, test does not exist in string
print(‘test not found’)
————— OUTPUT —————
Test found
test not found

6.3.3 String comparison


In Python, operators like ==, <, >, <=, >=, and != are used to compare
strings. String comparison involves comparing each character of the
strings in consideration as shown by the example below.
For Example:
str1 = “ABCD”
str2 = “WXYZ”

PAGE 123
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 123 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes if str1 == str2:


print(‘two strings equal’)
elif str1 < str2:
print(‘str1 < str2’)
elif str1 > str2:
print(‘str1 > str2’)
————— OUTPUT —————
str1 < str2

6.3.4 Indexing and Slicing


String indexing allows us to access specific characters within a string by using
subscripts. The first character is assigned an index of 0. In Python, there is no
distinct character type, as a character is essentially a string with a length of
one. Additionally, negative numbers (starting from -1) can be used as indices
to count from the right side of the string as shown in the example below.
For Example:
str = “This is test string”
print(str[0], str[1], str[2])
print(str[-1], str[-2], str[-3])
————— OUTPUT —————
T h i
g n i
Indexing is used to retrieve individual characters from a string, where-
as slicing enables you to extract substrings. Slices are given in square
brackets like [a:b], where the first number a denotes the starting index
and the second number b denotes where to end the slice. It is important
to note that when slicing, the starting index is always inclusive, while
the ending index is always exclusive as shown in the example.
For Example:
str = “This is test string”
print(str[0 : 2]) # string slicing extracts
character at index 0 and 1

124 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 124 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

————— OUTPUT ————— Notes


Th
Slices in Python come with convenient default values: if the first index
is omitted, it defaults to zero, and if the second index is omitted, it
defaults to the size of the string being sliced as shown in the example.
For Example:
str = “This is test string”
print(str[ : 4]) # starting index defaults to 0
print(str[ 4: ]) # ending index defaults to
end of string. Notice the first space in the
output
print(str[-3 : ]) # starting index is the third
last character in the string
print(str[:6] + str[6:]) # this will print the
entire string
————— OUTPUT —————
This
is test string
ing
This is test string
If you attempt to use an index that exceeds the string’s length, an error
will occur. However, when employing slice indexes that are out of range,
Python handles them gracefully when performing slicing operations.
For Example:
str = “This is test string”
print(str[ : 50]) # ending index is way beyond
the length of string
print(str[50])
————— OUTPUT —————
This is test string
———————————————————————

PAGE 125
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 125 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes IndexError Traceback (most recent call last)


<ipython-input-7-4f9dbce744d7> in <cell line:
3> ()
1 str = “This is test string”
2 print(str [ : 50]) # ending index is
way beyond the length of string
——> 3 print(str [50])
4
IndexError: string index out of range

6.3.5 Built-in Function – Len, Min, Max


len() function returns the length of the string; min() function retrieves the
smallest character (in chronological sequence starting from a) found within
a string; max() function retrieves the largest character found within a string.
For Example:
str = “TestString”
print(len(str))
print(min(str))
print(max(str))
————— OUTPUT —————
10
S
t

6.3.6 Strings are Immutable


Python strings cannot be changed by using an indexing operation. For
example, changing a character in the string is not possible. However new
strings can be created using the existing ones.
For Example:
str1 = “This is test string”
str2 = ‘t’ + str1[1:]

126 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 126 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

print(str2) Notes
str1[0] = ‘t’
————— OUTPUT —————
this is test string
———————————————————————
TypeError Traceback (most recent call last)
<ipython-input-11-710a1afe6261> in <cell line:
2>()
1 str1 = “This is test string”
——> 2 str1[0] = ‘t’
3
TypeError: ‘str’ object does not support
item assignment

6.4 Lists
Lists are collections of elements that are ordered and enclosed in square
brackets ([]). It is represented using a series of comma-separated val-
ues(elements) enclosed in square brackets. They have the flexibility to
store elements of different data types. Although lists can accommodate
items of varying types, it is common for the items within a list to share
the same data type. Lists are majorly utilized for tasks that involve
organizing and manipulating related data.
For Example:
list1 = [1, 2, 3, ‘a’]
list2 = [] #empty list
print(list1)
print(list2)
print(type(list1))
————— OUTPUT —————
[1, 2, 3, ‘a’]
[]
<class ‘list’>
PAGE 127
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 127 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes The example below shows another method to create lists.


For Example:
list1 = list([1,2.0,’test’])
list2 = list() #create empty list
print(list1)
print(list2)
print(type(list1)))
————— OUTPUT —————
[1, 2.0, ‘test’]
[]
<class ‘list’>
A list can be created from the characters of a string.
For Example:
string = “Test String”
list1 = list(string)
print(list1)
————— OUTPUT —————
[‘T’, ‘e’, ‘s’, ‘t’, ‘ ’, ‘S’, ‘t’, ‘r’, ‘i’,
‘n’, ‘g’]
Unlike strings, lists can be modified, making them mutable. This is further
explained below in detail. Python Programming offers a range of operations
on Lists, including appending, inserting, removing, sorting, and slicing.

6.4.1 Concatenation
Lists can be concatenated in the same way as that of strings.
For Example:
list1 = [1, 2, 3]
list2 = [4, 5]
list3 = list1 + list2
list4 = list1 * 2

128 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 128 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

print(list3) Notes
print(list4)
————— OUTPUT —————
[1, 2, 3, 4, 5]
[1, 2, 3, 1, 2, 3]

6.4.2 In and Not in operator


The in and not in operators are utilized to determine if an element be-
longs to the list or not.
For Example:
list1 = [1, 2, 3]
list2 = [[0, 1], 2, 3] # Note that a list can
have another list as a member element.
if [0,1] in list2:
print(“list element found in list”)
if 4 not in list1:
print(“element not found”)
————— OUTPUT —————
list element found in list
element not found

6.4.3 del Operator - Remove Element


The ‘del’ operator is utilized to eliminate elements from a list. By ac-
cessing the elements of the list through their index position and placing
the ‘del’ operator before them, the desired element can be deleted.
For Example:
list1 = [1, 2, 3]
del list1[:1] # uses slicing to access the
first element
print(list1)

PAGE 129
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 129 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ————— OUTPUT —————


[2, 3]

6.4.4 Indexing and Slicing


Lists can be indexed and sliced in the same way as that of strings. It
evaluates to True if the element is found in the list, and False if the
element is not found.
For Example:
list1 = [1, 2, 3]
print(list1[0], list1[1], list1[2])
print(list1[-1], list1[-2], list1[-3])
print(list1[1 : ], list1[ :1 ], list1[ : ])
————— OUTPUT —————
1 2 3
3 2 1
[2, 3] [1] [1, 2, 3]

6.4.5 Lists are Mutable


Lists are mutable and can be modified unlike strings.
For Example:
list1 = [1, 2, 3]
list1[0] = 5
print(list1)
————— OUTPUT —————
[5, 2, 3]

6.4.6 Adding and Removing Elements


append() function is used to append elements to the list, insert(i, a) func-
tion is used to insert element ‘a’ at index ‘i’. remove(a) function is used
to remove first element that matches ‘a’. It raises a ValueError if ‘a’ is

130 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 130 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

not found in the list. Slices of lists can also be assigned values, which can Notes
modify the list. The example given below demonstrates all these functions.
For Example:
list1 = [2, 3]
print(list1)
[Link](4) # this will add 4 to the last
position
print(list1)
[Link](0,1) # this will add element 1 at
index 0
print(list1)
[Link](2) # This will remove element 2
print(list1)
list1[0 : 2] = [0, 1, 2, 3] # this will modify
slice [0:2] to contain 4 elements - 0,1,2, and 3
print(list1)
————— OUTPUT —————
[2, 3]
[2, 3, 4]
[1, 2, 3, 4]
[1, 3, 4]
[0, 1, 2, 3, 4]

6.4.7 Built-in Functions – len, max, min, sum


Just like strings, len() function can be used to find length of a list, max()
function returns the element that has the highest value, min() function
returns the element that has the lowest value, and sum() function calcu-
lates the total sum of all the elements in a list.
For Example:
list1 = [1, 2, 3]
list2 = [[0, 1], 2, 3] # Note that a list can
have another list as a member element.

PAGE 131
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 131 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes print(len(list2))
print(max(list1))
print(min(list1))
print(sum(list1))
————— OUTPUT —————
3
3
1
6

6.5 Tuples
Tuples are commonly utilized to represent collections of diverse data
enclosed in parentheses (). They act as containers for storing related
pieces of information. Tuples, when displayed, are always encompassed
within parentheses to ensure the proper interpretation of nested tuples.
When inputting tuples, parentheses may or may not be included, although
they are frequently necessary, particularly when the tuple forms part of
a larger expression.
For Example:
tup1 = (1, ‘a’, 4.0)
tup2 = 3, 4, “test”, (1, 2) # Parenthesis not
necessary at the time of input
tup3 = tuple([1,2]) # a tuple may be created
through a list
print(tup1)
print(tup2)
print(tup3)
————— OUTPUT —————
(1, ‘a’, 4.0)
(3, 4, ‘test’, (1, 2))
(1, 2)

132 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 132 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

A unique consideration arises when constructing tuples containing zero or Notes


one item, as the syntax incorporates some peculiarities to accommodate
these cases. Empty tuples are created by employing an empty pair of
parentheses, while a tuple with a single item is formed by appending a
comma after the value (merely enclosing a single value in parentheses is
insufficient). Although these practices may appear unconventional, they
are effective in constructing tuples with zero or one item.
For Example:
tup1 = () # tuple with zero elements
tup2 = (1,) #tuple with just one element
print(tup1)
print(tup2)
tup3 = (2) #since the comma is missing, tup3
is an integer not a tuple
————— OUTPUT —————
()
(1,)
2

6.5.1 Concatenation
Tuples can be concatenated in the same way as that of strings and lists.
For Example:
tup1 = (1, 2, 3)
tup2 = (4, 5)
tup3 = tup1 + tup2
tup4 = tup1 * 2
print(tup3)
print(tup4)
————— OUTPUT —————
(1, 2, 3, 4, 5)
(1, 2, 3, 1, 2, 3)

PAGE 133
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 133 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 6.5.2 Indexing and Slicing


Tuples can also be accessed using indexing and slicing operations like
strings and lists.
For Example:
tup1 = (1, ‘a’, 4.0)
tup2 = tup1, “test”, (1, 2) # tup2 has 3
elements – tup1 as first element, “test” is
second element and (1,2) is third element
print(tup1)
print(tup2)
print(tup2[0]) # access first element of tup2
print(tup2[:2]) # slice first two elements of
tup2
————— OUTPUT —————
(1, ‘a’, 4.0)
((1, ‘a’, 4.0), ‘test’, (1, 2))
(1, ‘a’, 4.0)
((1, ‘a’, 4.0), ‘test’)

6.5.3 Built-in Functions


Built-in functions len(), max(), min(), sum() are defined for tuples in a
similar way as that for above data structures.
For Example:
tup1 = (1, 2, 2)
print(len(tup1))
print(max(tup1))
print(min(tup1))
print(sum(tup1))

134 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 134 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

————— OUTPUT ————— Notes


3
2
1
5

6.5.4 Tuples are Immutable


Tuples are immutable which implies assigning values to individual items
within a tuple is not possible, although tuples can contain mutable objects
such as lists.
For Example:
tup1 = (1, ‘a’, 4.0, [“test”, “str”])
tup1[0] = 2 # causes error as tuples are
immutable
————— OUTPUT —————
TypeError Traceback (most recent call last)
<ipython-input-31-8dd568d64489> in <cell line:
2> ()
1 tup1 = (1, ‘a’, 4.0, [“test”, “str”])
——> 2 tup1[0] = 2
3
TypeError: ‘tuple’ object does not support item
assignment
However, a tuple may contain mutable elements like list and can be
accessed and manipulated as shown in the example.
For Example:
tup1 = (1, ‘a’, 4.0, [“test”, “str”])
list1 = tup1[3] # element at index 3 is the
last element ([“test”, “str”]) in tup1
list1[0] = “change” # first element of the
list is set to “change”

PAGE 135
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 135 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes print(list1)
print(tup1) # tup1 still has the same list
element at index 3 as tup1 is immutable.
# But since the list is mutable, its
first element can be modified
————— OUTPUT —————
[‘change’, ‘str’]
(1, ‘a’, 4.0, [‘change’, ‘str’])

6.5.5 Packing and Unpacking


Despite the apparent similarities between tuples and lists, they are common-
ly employed in distinct scenarios for different purposes. Tuples typically
consist of a heterogeneous sequence of elements, which can be accessed
through unpacking or indexing. On the other hand, lists are mutable and
generally comprise homogeneous elements accessed via iteration. Tuple
packing and unpacking are explained in the given example.
For Example:
tup1 = 1, ‘a’, [“test”, “str”] # tuple
packing: three elements added to one tuple
print(tup1)
x, y, z = tup1 #tuple unpacking: x, y, z
receives the values of first, second, and
third elements of tup1
print(x)
print(y)
print(z)
————— OUTPUT —————
(1, ‘a’, [‘test’, ‘str’])
1
a
[‘test’, ‘str’]

136 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 136 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

Notes
6.6 Sets
In Python programming, a Set is an unordered collection of unique
elements (i.e., no duplicate elements unlike lists and tuples). It is rep-
resented by curly braces ({}) or created using the set() function. The
given example shows how to create a set and how it is different from
lists and tuples.
For Example:
s1 = {1, 2, 3}
s2= set()
print(type(s1))
print(type(s2))
————— OUTPUT —————
<class ‘set’>
<class ‘set’>
For Example:
x = (1,2,1) # tuple can contain duplicate
elements
y = [1,2,1] # list can contain duplicate
elements
z = {1,2,1} # duplicate element 1 will be
allowed just once as shown in the output below
print(x, y, z)
————— OUTPUT —————
(1, 2, 1) [1, 3, 1] {1, 2}
A set may be created using a list or a tuple as shown in the given example.
For Example:
l1 = [1, 2, 3, 1] # create a list
t1= (4, 5, 4) # create a tuple
str1 = ‘abcda’ # create a string
print(type(l1))
print(type(t1))

PAGE 137
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 137 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes s1 = set(l1) # create set from list


s2 = set(t1) # create set from tuple
s3 = set(str1) # create set from string
print(type(s1), s1)
print(type(s2), s2)
print(type(s3), s3)
————— OUTPUT —————
<class ‘list’>
<class ‘tuple’>
<class ‘set’> {1, 2, 3}
<class ‘set’> {4, 5}
<class ‘set’> {‘c’, ‘a’, ‘b’, ‘d’}
Also, it is important to note that when creating an empty set, the set() func-
tion should be used instead of using curly braces ({}), as the latter constructs
an empty dictionary (a data structure covered in the subsequent section).
For Example:
l1 = [1, 2, 3, 1] # Create a list
s1 = set() # creates an empty set
s2 = {} #creates a dictionary
print(type(s1), type(s2))
————— OUTPUT —————
<class ‘set’> <class ‘dict’>
Sets are particularly valuable when working with mathematical sets and
performing operations like unions, intersections, and differences. Sets
offer efficient membership testing and enable the removal of duplicate
elements with ease.

6.6.1 Membership Test


The ‘in’ operator is used to verify whether an element exists within a
set. When applied, the in operator yields True if the element is found
in the set. On the other hand, the ‘not in’ operator returns True if the
specified element is absent from the set.

138 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 138 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

For Example: Notes


s = {1, 2, 3}
if 1 in s:
print(“1 is an element of set s”)
if 4 not in s:
print(“4 is not an element of set s”)
————— OUTPUT —————
1 is an element of set s
4 is not an element of set s

6.6.2 Union of two sets


The union method or the | operator is used to find the union of two sets
S1 and S2. It forms a new set that contains elements present in either
S1, in S2, or in both S1 and S2.
For Example:
s1 = {1, 2, 3}
s2 = {1, 2, 3, 4, 5}
s3 = s1 | s2 # take union of two
sets using | operator
s4 = [Link](s2) #take the union
of two sets using the union function
print(s3, s4)
————— OUTPUT —————
{1, 2, 3, 4, 5} {1, 2, 3, 4, 5}

6.6.3 Intersection of two sets


The intersection method or the & (ampersand) operator is used to find the
intersection of two sets S1 and S2. It creates a new set having elements
common in S1 and S2.

PAGE 139
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 139 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes For Example:


s1 = {1, 2, 3}
s2 = {1, 2, 3, 4, 5}
s3 = s1 & s2 # take intersection of two
sets using & operator
s4 = [Link](s2) #take the intersection
of two sets using the intersection function
print(s3, s4)
————— OUTPUT ——-———
{1, 2, 3} {1, 2, 3}

6.6.4 Difference between two sets


The difference method or the - (minus) operator is used to find the differ-
ence of two sets S1 and S2. It creates a new set having elements present
in set S1 but not in set S2. In simpler terms, the difference represents
the elements unique to set A.
For Example:
s1 = {1, 2, 3}
s2 = {1, 2, 3, 4, 5}
s3 = s1 - s2 # returns a blank set as s1 does
not have any element that is not present in s2
s4 = [Link](s1) # returns s2 - s1
print(s3, s4)
————— OUTPUT —————
set() {4, 5}

6.6.5 Symmetric difference of two sets


The symmetric_difference method or the ^ (exclusive) operator is used
to find the symmetric difference of two sets S1 and S2. It creates a new
set having elements present in either set S1 or in set S2 but not in both.
In simpler terms, the symmetric_difference represents the elements that
are unique to either set.

140 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 140 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

For Example: Notes


s1 = {1, 2, 3, 6}
s2 = {1, 2, 3, 4, 5}
s3 = s1 ^ s2 # returns elements present in
either set s1 or in set s2 but not in both
s4 = s2.symmetric_difference(s1)
print(s3, s4)
————— OUTPUT —————
{4, 5, 6} {4, 5, 6}

6.7 Dictionaries
Dictionaries in Python are collections of key-value pairs that can be rep-
resented by curly braces ({}) or created using the ‘dict()’ method. The
key and value are separated by a colon (:). Dictionaries are different from
Lists as Lists organize elements based on their positions. However, there
are situations where the programmer is less concerned about the position
of an item in the data structure and more interested in the association of
that element (key) with another element (value) in the structure.

IN-TEXT QUESTIONS
1. List Case Changing Python String Methods.
2. Are Lists Mutable in Python?
3. Are Python Strings Immutable?
4. What are dictionary in python ?
5. Which method is used to add an element to the end of a list
in Python?

For Example:
d1 = {‘name’ : ‘Mita’, ‘RollNo’ : 21, ‘admsn_no’
: 112} # for key ‘name’, ‘Mita’ is the value.
#Similarly for key ‘RollNo’, 21 is the value
print(type(d1))
print(d1)
PAGE 141
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 141 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ————— OUTPUT —————


<class ‘dict’>
{‘name’: ‘Mita’, ‘RollNo’: 21, ‘admsn_no’: 112}
There are multiple ways to create a dictionary as shown in the given
example. One approach is to use the dict() constructor. It allows us to
create dictionaries from keyword arguments.
For Example:
d1 = dict(name = ‘Mita’, RollNo = 21,
admsn_no = 112) # dictionary created using
keyword arguments, where the argument names
are the keys and their values are provided.
print(type(d1))
print(d1)
————— OUTPUT —————
<class ‘dict’>
{‘name’: ‘Mita’, ‘RollNo’: 21, ‘admsn_no’: 112}
Another method is to create a dictionary from an iterable of key-value
pairs:
For Example:
pairs = [(‘name’, ‘Mita’), (‘RollNo’, 21),
(‘admsn_no’, 1)]
d1 = dict(pairs) # dict() constructor converts
the iterable of pairs into a dictionary
print(type(d1))
print(d1)
————— OUTPUT —————
<class ‘dict’>
{‘name’: ‘Mita’, ‘RollNo’: 21, ‘admsn_no’: 1}
Yet another method is to create an empty dictionary and add key: value
pairs to it.

142 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 142 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

For Example: Notes


d1 = {}
d1[‘name’] = ‘Mita’
d1[‘RollNo’] = 21
print(type(d1))
print(d1)
————— OUTPUT —————
<class ‘dict’>
{‘name’: ‘Mita’, ‘RollNo’: 21}
Dictionaries provide efficient lookup and retrieval of values based on keys,
making them suitable for mapping and storing data. Also, they offer the
ability to update or add new key-value pairs. Hence, they are mutable
and support operations such as adding, updating, and deleting elements.

6.7.1 Accessing Elements


To access the corresponding values in a dictionary, keys are used. The
syntax involves providing the desired key within square brackets ([]) as
shown in the given example.
For Example:
d1 = {}
d1[‘name’] = ‘Mita’
d1[‘RollNo’] = 21
print(d1 [‘name’])
————— OUTPUT —————
Mita

6.7.2 Updating and Adding Elements


Dictionaries are mutable, allowing users to modify or insert new key-value
pairs. To update a value, the existing key is referenced and assigned a
new value. To add a new key-value pair, a value is assigned to a previ-
ously non-existent key.

PAGE 143
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 143 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes For Example:


d1 = {‘name’ : ‘Mita’, ‘RollNo’ : 21,
‘admsn_no’ : 112}
print(d1)
d1[‘name’] = ‘Mitali’
d1[‘ContactNo’] = 9899989998
print(d1)
————— OUTPUT —————
{‘name’: ‘Mita’, ‘RollNo’: 21, ‘admsn_no’: 112}
{‘name’: ‘Mitali’, ‘RollNo’: 21, ‘admsn_no’:
112, ‘ContactNo’: 9899989998}

6.7.3 Removing Elements


Dictionaries provide methods to remove elements by specifying their keys.
The del keyword is used to delete a key-value pair from the dictionary
as shown in the given example. Another approach is to use the pop()
method, which not only removes the key-value pair but also returns the
value as shown in the given example.
For Example:
d1 = {‘name’ : ‘Mita’, ‘RollNo’ : 21,
‘admsn_no’ : 112}
print(d1)
del d1[‘admsn_no’]
print(d1)
val = [Link](‘RollNo’)
print(val)
print(d1)
————— OUTPUT —————
{‘name’: ‘Mita’, ‘RollNo’: 21, ‘admsn_no’: 112}
{‘name’: ‘Mita’, ‘RollNo’: 21}
21
{‘name’: ‘Mita’}

144 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 144 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

6.7.4 Nested Dictionaries Notes


A dictionary within a dictionary is called a nested dictionary. For instance,
in the given example, a student serves as a dictionary. The student’s name
will be the key and the associated value is a dictionary of the student’s
information.
For Example:
students = {‘Mita’: {‘RollNo’ : 21, ‘admsn_no’
: 112},
‘Smriti’: {‘RollNo’ : 22, ‘admsn_no’
: 115},
‘Chetna’:{‘RollNo’ : 23, ‘admsn_no’
: 117}
}
print(type(students))
print(type(students[‘Mita’]))
print(students)
print(students[‘Mita’])
————— OUTPUT —————
<class ‘dict’>
<class ‘dict’>
{‘Mita’: {‘RollNo’: 21, ‘admsn_no’: 112}, ‘Smriti’:
{‘RollNo’: 22, ‘admsn_no’: 115}, ‘Chetna’:
{‘RollNo’: 23, ‘admsn_no’: 117}}
{‘RollNo’: 21, ‘admsn_no’: 112}

6.7.5 Immutable Keys


In a dictionary, the keys must be immutable objects like strings, num-
bers, or tuples. Mutable objects such as lists cannot be used as keys
since they can change their values, which would disrupt the dictionary’s
internal structure.

PAGE 145
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 145 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 6.7.6 Missing Key value


Accessing a key that does not exist, raises a KeyError. get() method can
be used to handle the error. It returns a default value (None) if the key
is not found.
For Example:
d1 = {‘name’ : ‘Mita’, ‘RollNo’ : 21,
‘admsn_no’ : 112}
print([Link](‘section’))
print(d1[‘section’])
————— OUTPUT —————
None
KeyError Traceback (most recent call last)
<ipython-input-21-8f10b3fafc3d> in <cell line:
3>()
1 d1 = {‘name’ : ‘Mita’, ‘RollNo’ : 21,
‘admsn_no’ : 112}
2 print([Link](‘section’))
——> 3 print(d1[‘section’])
4
KeyError: ‘section’

6.8 Data Structures with Loop and Conditional Statements


Powerful real-world applications can be created using different built-in
data structures together along with loops and conditional statements.
For Example:
4ௐ:ULWHD3\WKRQSURJUDPWRUHPRYHDOOWKHYRZHOVIURPDJLYHQVWULQJ
Sol:
string = “TestString”
vowelCharts = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘A’,
‘E’, ‘I’, ‘O’, ‘U’]
NewString = “”

146 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 146 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

for i in range(len(string)): #iterate over Notes


each character of string
if string[i] not in vowelCharts: #if ith
character of string is not a vowel
NewString = NewString + string[i]
print(“\nString without vowels:”, NewString)
-————— OUTPUT —————
String without vowels: TstStrng
For Example:
4ௐ:ULWHD3\WKRQSURJUDPWRFRXQWWKHRFFXUUHQFHRIDJLYHQFKDU-
acter in an input string.
Sol:
str1 = “This is test string”
char_to_count = ‘t’ # Python is case-sensitive
language, ‘T’ is not same as ‘t’
count = 0
for i in range(len(str1)):
if(str1[i] == char_to_count):
count = count + 1

print(“Character”, char_to_count, “ occurs ” ,


count, “ times in the string:”, str1)
————— OUTPUT —————
Character t occurs 3 times in the string:
This is test string

6.9 Summary
This chapter discussed the characteristics and properties of various built-
in data structures in Python, including strings, lists, tuples, sets, and
dictionaries. Each data structure is described in detail, along with its
fundamental characteristics, how to manipulate and access its elements,
and the built-in functions, operators, and operations associated with it.

PAGE 147
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 147 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes Strings are collections of characters and can be enclosed in single or double
quotes. This chapter covered topics such as escaping quotes, special charac-
ters, string concatenation, indexing, slicing, and the immutability of strings.
Lists are introduced as ordered collections of elements enclosed in square
brackets. They are mutable and can store items of different data types.
This chapter covered concatenation, indexing, slicing, adding, and re-
moving elements, and finding the length of a list.
Tuples are collections of diverse data enclosed in parentheses. They can
be accessed using indexing and slicing operations like strings and lists.
Tuples are immutable, meaning their individual items cannot be modified,
although they can contain mutable objects like lists.
Sets are unordered collections of unique elements in Python, represented
by curly braces or the set() function. They have no duplicate values and
are primarily used for membership testing and eliminating duplicates
from other data structures. This chapter explained set operations such as
union, intersection, difference, and symmetric difference.
Dictionaries are unordered collections of key-value pairs, enclosed in
curly braces or created using the dict() method. They provide efficient
data retrieval based on keys rather than numerical indexing. This chapter
discussed different dictionary operations such as accessing values, add-
ing, and modifying key-value pairs, removing items, etc. Dictionaries are
mutable and can store elements of different data types.
Understanding these concepts will empower you to efficiently work with
data in Python, enabling you to build robust and scalable applications.
As you progress in your Python journey, remember to leverage these
powerful data structures to write clean and effective code.

6.10 Answers to In-Text Questions


1. ‹lower(): Converts all uppercase characters in a string into lowercase
‹ upper(): Converts all lowercase characters in a string into uppercase
‹ title(): Convert string to title case
‹ swapcase(): Swap the cases of all characters in a string
‹ capitalize(): Convert the first character of a string to uppercase

148 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 148 09-10-2025 [Link]


BUILT-IN DATA STRUCTURES IN PYTHON

Notes
2. Yes, Lists are mutable in Python. We can add or remove elements
from the list. In Python, mutability refers to the capability of an
object to be changed or modified after its creation.
3. Strings in Python are “immutable” which means they can not be
changed after they are created. Some other immutable data types
are integers, float, Boolean.
4. Python dictionary is a data structure that stores the value in
key:value pairs.
5. append()

6.11 Self-Assessment Questions


1. Write a Python program to remove all the vowels from a given string.
2. Write a Python program to check if a string contains only digits.
3. Write a Python program to find the most frequent character in a string.
4. Write a Python program to check if a given string is a palindrome
or not.
5. Write a Python program to find the largest element in a list.
6. Write a Python program to find the sum of all elements in a list.
7. Write a Python program to remove all even numbers from a list.
8. How do you find the length of a tuple in Python?
9. Write a Python program to access the third element of a tuple.
10. Write a Python program to create a set with the following elements:
1, 2, 3, 4, 5. Display the set.
11. Write a Python program to check if the element ‘2’ exists in the
set created in the above question. Display a message indicating
whether it exists or not.
12. Write a Python program to create a second set with the following
elements: 4, 5, 6, 7, 8. Perform a union operation between the first
and second sets and display the result.
13. Write a Python program to create a third set with the following
elements: 6, 7, 8, 9, 10. Perform an intersection operation between
the second and third sets and display the result.

PAGE 149
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 149 09-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 14. Write a Python program to create a dictionary with three key-value
pairs: “onion” with a value of 3, “tomato” with a value of 2, and
“potato” with a value of 5. Display the dictionary.
15. Write a Python program to access and print the value associated
with the key “onion” from the dictionary created in above question.
16. Write a Python program to add a new key-value pair “cucumber”
with a value of 4 to the dictionary created in the above question.
Display the updated dictionary.
17. Write a Python program to check if the key “garlic” exists in the
dictionary created in the above question. Display “Exists” if it does,
or “Does not exist” otherwise.

6.12 References
‹ Kamthane, A. N., & Kamthane, A. A. (2020). Programming and
Problem Solving with Python. McGraw-Hill Education.
‹ Saeed, A., Ayeva, A., Ayeva, K. (2020). Python In - Depth: Use
Python Programming Features, Techniques, and Modules to Solve
Everyday Problems. India: BPB PUBN.
‹ Balagurusamy E., (2018). Introduction to Computing and Problem
Solving using Python (2 ed.). McGraw Hill Education.

150 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 150 09-10-2025 [Link]


Glossary

Abnormal Termination: Situation when a program crashes and terminates due to an


unhandled exception.
Abstraction: It means hiding the internal details, allowing users to focus on high-level
functionality rather than implementation specifics.
Append: Concatenating at the end is known as append.
Arguments: These are the actual values that are provided when the function is invoked.
Associativity: It is used to determine the order of evaluation, when two operators have
same precedence.
Break: These are statements that are used to terminate a loop prematurely.
Compiler: It is a program that coverts whole source code into intermediate machine code.
Concatenation: Merging multiple strings into a single string is known as concatenation.
Conditional Statement: Statements that allow us to execute different blocks of code
based on specific conditions.
Continue: These are statements that are used to skip the current iteration of a loop and
move to the next iteration.
Control Statements: These are statements that are used to manage how loops are executed.
Data Structures: Specialized format for organizing, processing, retrieving and storing
data is known as data structures.
Def: It is a keyword that marks the beginning of a function definition.
Default Arguments: Arguments assigned a predetermined value in the function definition.
Dictionary: The collection of key-value pairs is known as dictionary.
Docstring: A string literal that serves as documentation to state the function’s purpose.
Error: In software development, these are syntax errors in the code that are also known
as parsing errors.
Eval Function: It evaluates the expression passed in the form of string as input and re-
turns the result.
Exception Chaining: Python mechanism to allow the code to retain the original exception
context when raising a new exception.

PAGE 151
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Glossary.indd 151 10-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes Exception: These are logical errors raised during program execution.
Expression: It is a combination of variables, literals, operators, and
function calls that produce a result.
Finally: These are blocks designed to define cleanup actions that must
be executed regardless of whether an exception occurred or not.
Formal Parameters: These are variables declared inside the parenthesis
of a function definition that serve as placeholders for the actual values
to be passed when the function is called.
Function: Independent module within a program is known as function.
Global Variable: Variables that are declared outside of any function, at
the top level of the program and have a global scope.
Handler: This is a piece of code written to handle exception(s).
High Level Programming Language: A programming language which
allows a programmer to write codes that are closer to human languages.
IDE: It is a software for building applications that combines common
developer tools into a single Graphical User Interface (GUI).
Identifier: It represents fixed value in a program which cannot be changed.
Immutable: Values that cannot be modified once created are known as
immutable.
Input Function: It is used to capture the user input from the console.
Interpreter: It refers to a software which converts the high-level instruc-
tions to machine-level language line by line.
Iteration: A single execution instance of a set of statements in a loop.
Keyword Arguments: Arguments to be specified by their corresponding
parameter names during a function call.
List: It is a collection of elements that are ordered (mutable).
Local Variable: These are variables that are declared within a function
and have a local scope.
Loop: Programming construct to repeatedly execute a block of code until
a certain condition is met.
Low Level Programming Language: Programming languages that pro-
vides little or no abstraction from the computer architecture.

152 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Glossary.indd 152 10-10-2025 [Link]


GLOSSARY

Modularity: It is the separation of different tasks into independent modules. Notes


Mutable: Values that can be modified are known as mutable.
Nested Loop: Loop inside the body of the outer loop allowing chaining
of loops.
Operators: These are used to perform operations on values or variables.
Output Function: It is used to display results on screen or any other
standard output device.
Pass: Null statement is referred to as pass.
Positional Arguments: Arguments passed based on their position in the
function call.
Precedence: It determines the priority of operators.
Punctuations: These are used to separate and mark different parts of code.
Python Shell: It provides a medium to use python interpreter in an in-
teractive manner.
Raise: Python statement used to trigger an exception.
Recursive Functions: Functions that call themselves are known as re-
cursive function.
Return: Python statement employed to explicitly specify the single or
multiple values to be returned from a user-defined function.
Scope: Accessibility/visibility within a program is known as scope.
Semantics: It refers to the interpretation of the code.
Sequence: It is a generic term for an ordered set in Python.
Set: In Python, set is an unordered collection of unique elements.
Special Characters: These are characters that have been assigned special
meanings like ‘\n’ for new line.
Statement: It is a line of code that performs some action but does not
produce any output.
String Indexing: It is a Mechanism that allows us to access specific
characters within a string by using subscripts.
String Slicing: It is the extraction of substrings from a string using
subscripts.
String: It is the collection of characters.

PAGE 153
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Glossary.indd 153 10-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes Syntax: Syntax refers to the structure, grammar, and rules of a program-
ming language.
Token: It is the smallest individual unit in a program.
Try-except: These are python statements for handling exceptions.
Tuple: It is a collection of diverse data enclosed in parentheses (immutable).
Variable: It is the name of a memory location where we store data.

154 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Glossary.indd 154 10-10-2025 [Link]


READING NOTES
FOR
EXTRA TOPICS

PAGE 155
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 155 15-10-2025 [Link]


PFUP_Unit_04_Lesson [Link] 156 15-10-2025 [Link]
L E S S O N

7
Object Oriented
Programming

STRUCTURE
7.1 Learning Objectives
7.2 Introduction
7.3 2EMHFWV DQG &ODVVHV  'H¿QLQJ &ODVVHV IRU 2EMHFWV
7.4 UML Class Diagrams
7.5 Immutable Objects vs. Mutable Objects
7.6 Hiding Data Fields
7.7 Class Abstraction and Encapsulation
7.8 Object-Oriented Thinking
7.9 Programming Examples
7.10 Exercises Related to Analytics
7.11 Summary
7.12 Answers to In-Text Questions
7.13 6HOI$VVHVVPHQW 4XHVWLRQV
7.14 Suggested Readings

7.1 Learning Objectives


‹ Gain a comprehensive understanding of fundamental Object-Oriented Programming
(OOP) concepts, encompassing classes, objects, and UML class diagrams.

PAGE 157
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 157 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ‹ Distinguish between immutable and mutable objects within Python,


discerning their unique characteristics and applications in programming.
‹ Explore the principles and practices of data hiding in Object-
Oriented Programming, covering various techniques to safeguard
data within classes.
‹ Enhance understanding of abstraction and encapsulation in Python,
recognizing their importance in software design and implementation.
‹ Cultivate problem-solving acumen and proficiency in addressing
analytical challenges in Data Science utilizing Python, through
practical problem-solving exercises.

7.2 Introduction
Python currently is the `dominant force` in programming and led to a
revolution of industries and to chose programming language for most
programmers, data scientists and educators. Its capability to be versatile,
simple and invincible has made it a necessary tool in virtually limitless
apps from web development to scientific computing.
Python’s simplicity and lucidity, mean that it is a perfect language for
both novice and experienced programmers to use. Its syntax resembles
English, but is still simple to learn and fairly easy to understand not
only for computer geeks, but also for those who do not have experience
programming. This availability slashes the entry barrier for people will-
ing to try themselves in the craft of programming as they can learn the
core principles in no time and move forward and construct the useful
applications.
To top it off, Python’s versatility cannot be matched. It offers many
programming models, such as procedural, object-oriented, and functional
programming, implying the freedom of developers to decide on the way
which is most appropriate to them. Python acquired the abilities and
libraries to be sufficient to resolve a wide range of issues comfortably
either creating a web application with the help of the frameworks like
Django or Flask, conducting data analysis with libraries like NumPy and
Pandas, or building a machine learning model with TensorFlow or PyTorch.
In addition, providing Python with a rich standard library and powerful
community of third-party apps, also play a role in increasing the popularity
158 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 158 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

and functionality of the language. The standard library includes modules Notes
that are intended to be used for certain tasks, including file I/O, net-
working, and data serialization. It helps to avoid the situation when we
need to re-invent the wheel applying same functions repeatedly. Also,
Python’s extensive library, the Python Package Index (PyPI), has more
than 300,000 available packages written by the community, which cover
almost every known practical case. The ecology of the system is one of
the main advantages for developers that give them a chance to save time
in setting up all the process due to the already existing solutions and do
not get lost in implementation details.
The role of Python in data science and scientific computing can be sum-
marized as of decisive significance. Its ease of use and the fact that it
can be molded to fit different tasks like data manipulation, visualization,
and statistical analysis make it very powerful. Numpy, SciPy, and Mat-
plotlib modules are in charge of some very crucial libraries while scikit-
learn has mechanisms that remove a lot of development work. More and
more companies are looking for the data-driven insights to develop their
business and so Python has become the most popular language for data
scientists and researchers to use it for analyzing large amounts of data.
Moreover, comparable to the technical abilities, Python is a platform that
promotes a strong sense of community and shared endeavors. The Py-
thon Software Foundation (PSF) supervises the maintenance and growth
of the language in a way that it may continuously progress and grow.
Besides, Python’s open-source characteristics push developers worldwide
to contribute and allow constantly rising updates, mending bugs, and
supplementing with new features. The community-based attitude behind
the Python has made it possible for a supportive and inclusive platform
where the collaborative knowledge transfer and mentorship happen, al-
lowing members from different backgrounds to be able to learn, grow
and participate towards the success of the language.
In conclusion, Python is one of the essentials in the contemporary
technological world due to its simplistic nature, its variability and how
vivid its supporting community is. To move forward and learn from this
interaction, we must take responsibility for our own choices and actions
both online and offline. The reason why it is the language of choice for
a lot of applications is just its practicality, depth libraries, and powerful

PAGE 159
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 159 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes community. This makes its popularity more likely to remain the same
as the years go by. Given the fact that technology keeps on pushing the
limits of what can be done, Python will likely remain cutting-edge and
alluring tool for the programmers and researchers in the years to come.

7.3 Objects and Classes - Defining Classes for Objects


Objects and classes are fundamental concepts in object-oriented pro-
gramming (OOP), a programming paradigm that focuses on modeling
real-world entities as objects that interact with each other. In Python,
everything is an object, and classes are used to define the blueprint for
creating objects.
1. Objects: An object is a self-contained unit that consists of data
(attributes) and behaviors (methods). It represents a particular instance
of a class. For example, if we consider a class Car, an object of
this class might represent a specific car with its own characteristics
(such as color, model, and mileage) and behaviors (such as starting
the engine, accelerating, and braking).
2. Classes: A class is a blueprint or template for creating objects. It defines
the attributes and methods that objects of the class will have. Think
of a class as a cookie cutter and objects as the cookies cut out from
that cutter. The class defines the shape, and each object created from
the class follows that shape. Classes encapsulate data and behavior,
promoting modularity, reusability, and maintainability in code.
Car (Class)

Audi (Object) Mercedes(Object)

160 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 160 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

Below is an example of how classes are defined in Python: Notes

Explanation:
‹ Class ClassName:: This line declares the start of a class definition.
ClassName is the name of the class, which follows the naming
conventions for identifiers in Python (typically using CamelCase).
‹ def __init__(self, parameter1, parameter2, ...):: This special method
is called the constructor or initializer. It is executed automatically
when an object of the class is created. The self parameter represents
the instance of the class (i.e., the object itself), and it is used to
access attributes and methods within the class. Other parameters
can be passed to the constructor to initialize the object’s attributes.
‹ self.attribute1 = parameter1: Inside the constructor, attributes of the
object are initialized using the parameters passed to the constructor.
self.attribute1 refers to an attribute of the object, and parameter1 is
the value passed when creating an instance of the class.
‹ def method_name(self, parameter1, parameter2, ...):: This is a method
definition within the class. Methods are functions associated with
objects of the class and can operate on the object’s data. The first
parameter of the method is always self, which represents the object
itself. Additional parameters can be defined as needed.
‹ Method body: This is where the functionality of the method is
implemented. Inside methods, you can access object attributes and
perform operations on them.
To create an object (instance) of a class, you simply call the class name as
if it were a function, passing any required parameters to the constructor:

PAGE 161
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 161 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes This creates a new instance of the class ClassName with the specified
attribute values. You can then access the object’s attributes and methods
using dot notation:

In summary, objects and classes provide a powerful way to structure


and organize code in Python, facilitating code reuse, modularity, and ab-
straction. By defining classes for objects, developers can model complex
systems more effectively, leading to cleaner, more maintainable code.
Example: Creating a Class for a Simple Bank Account
Suppose we want to create a Python class to represent a simple bank
account. Each account will have attributes like the account holder’s name
and balance, as well as methods to deposit money, withdraw money, and
display the account details.

Explanation of the code:


‹ class BankAccount:: This line declares the start of a class definition
named BankAccount.
‹ def __init__(self, account_holder, initial_balance=0):: This is the
constructor method (__init__) which is called automatically when
an object of the class is created. It initializes the attributes of the
object. account_holder and initial_balance are parameters passed to
initialize the object’s attributes.
162 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 162 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

‹ self.account_holder = account_holder: This line initializes the Notes


account_holder attribute of the object with the value passed to the
constructor.
‹ [Link] = initial_balance: This line initializes the balance
attribute of the object with the value passed to the constructor. If
no initial balance is provided, it defaults to 0.
‹ def deposit(self, amount):, def withdraw(self, amount):, def display_
details(self):: These are method definitions within the class. They
define behaviors associated with objects of the class.
‹ [Link] += amount: Inside the deposit method, this line adds
the amount to the object’s balance.
‹ if amount <= [Link]:: Inside the withdraw method, this line
checks if the amount to be withdrawn is less than or equal to the
current balance.
‹ print(f”Deposited {amount} into {self.account_holder}’s account. New
balance: {[Link]}”): This line prints a message indicating a
successful deposit, including the deposited amount and the new balance.
‹ print(f”Withdrew {amount} from {self.account_holder}’s account.
New balance: {[Link]}”): This line prints a message indicating
a successful withdrawal, including the withdrawn amount and the
new balance.
‹ print(f”Insufficient funds in {self.account_holder}’s account.”): This
line prints a message indicating insufficient funds if the withdrawal
amount exceeds the current balance.
‹ print(f”Account Holder: {self.account_holder}”), print(f”Balance:
{[Link]}”): These lines print the account holder’s name and
balance when the display_details method is called.
To create objects (instances) of the BankAccount class and interact with
them:

PAGE 163
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 163 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes

This code snippet demonstrates creating two bank accounts (account1


and account2), depositing and withdrawing money from each account,
and displaying the account details.
In summary, classes and objects provide a powerful way to organize and
structure code in Python, enabling developers to model real-world entities
and define their behaviors effectively. By encapsulating data and func-
tionality within classes, developers can create reusable and maintainable
code, promoting modularity and abstraction.

IN-TEXT QUESTIONS
1. Which of the following statements about objects in OOP is
true?
(a) Objects are blueprints for creating classes.
(b) Objects are instances of classes.
(c) Objects cannot have attributes.
(d) Objects are only used for inheritance.
2. What is the primary purpose of a constructor in a class?
(a) To destroy objects
(b) To create objects
(c) To access class attributes
(d) To define class methods
3. What is the purpose of the ‘self’ keyword in Python when
defining methods in a class?
(a) It refers to the current instance of the class
(b) It indicates a static method
(c) It refers to the superclass of the class
(d) It represents the class itself

164 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 164 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

4. What is the process of creating a new object based on a class Notes


called in OOP?
(a) Inheritance
(b) Polymorphism
(c) Instantiation
(d) Encapsulation

7.4 UML Class Diagrams


UML (Unified Modeling Language) Class Diagrams are a type of static
structure diagram that illustrates the structure and relationships of classes
and interfaces in a system. They provide a visual representation of the
system’s architecture, focusing on the classes and their attributes, meth-
ods, and associations.
Here’s an overview of the main components and concepts in UML Class
Diagrams:
‹ Class: Represents a blueprint for creating objects. It encapsulates
data for the object and operations that can be performed on the
data. Classes are depicted as rectangles with three compartments:
one for the class name, one for attributes, and one for methods.
‹ Attributes: Represent properties or data members of a class. They
describe the characteristics or state of objects belonging to the
class. Attributes are typically listed in the second compartment of
the class rectangle and are preceded by a hyphen (-).
‹ Methods: Represent operations or behaviors that objects belonging
to the class can perform. They define the functionality or actions
associated with the class. Methods are listed in the third compartment
of the class rectangle and are preceded by a plus sign (+).
‹ Associations: Represent relationships between classes. They
describe how objects of one class are connected to objects of
another class. Associations are depicted as lines connecting classes,
often with labels indicating the nature of the relationship (e.g.,
“owns”, “uses”).

PAGE 165
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 165 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ‹ Multiplicity: Indicates the number of instances of one class associated


with a single instance of another class. Multiplicity is represented
using numeric ranges or specific values on the association lines.
‹ Inheritance: Represents the “is-a” relationship between classes,
where one class (subclass or derived class) inherits attributes and
behaviors from another class (superclass or base class). Inheritance
is depicted using a solid line with a hollow arrowhead pointing to
the superclass.
‹ Interfaces: Define a contract for classes that implement them,
specifying a set of methods that implementing classes must
provide. Interfaces are represented similarly to classes but with the
interface name italicized and typically prefixed with a stereotype
(<<interface>>).
UML Class Diagrams are widely used in software development for model-
ing and designing object-oriented systems. They help developers visualize
the structure of their systems, understand relationships between classes,
and communicate system architecture to stakeholders.
Let’s consider a scenario of a library management system. In this system,
we might have classes for books, authors, library members, and library
staff. Here’s how we can represent this system in a UML class diagram:

௑௑௑௑
166 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 166 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

In this example: Notes


‹ We have classes like Library, Book, Author, LibraryMember, and
LibraryStaff.
‹ Each class has its attributes and methods.
‹ Relationships are depicted using lines between classes. For instance,
Book has an attribute author of type Author, indicating a composition
relationship between Book and Author.
‹ Methods are depicted with their respective access modifiers (+ for
public, - for private).
‹ Associations are shown between classes, such as Library having
a method addBook(book: Book) indicating that Library has a
relationship with Book.

Types of UML diagrams


UML offers several types of diagrams, each serving a different purpose
in modeling various aspects of a system. Here are some common types
of UML diagrams:
1. Class Diagram: Represents the static structure of a system by showing
classes, attributes, methods, and relationships between classes.
2. Use Case Diagram: Describes the interactions between users (actors)
and a system to achieve specific goals (use cases).
3. Sequence Diagram: Illustrates how objects interact with each other
in a particular scenario of a use case, showing the sequence of
messages exchanged over time.
4. Activity Diagram: Represents the flow of control and data in a
system, usually mapped out as a series of actions or activities.
5. Statechart Diagram (State Machine Diagram): Describes the various
states that an object can be in and how it transitions between those
states in response to events.
6. Component Diagram: Depicts the components of a system, their
interactions, and dependencies between them at a high level.
7. Deployment Diagram: Shows the physical deployment of artifacts
(software components) to nodes (hardware components) in a system.
8. Package Diagram: Organizes the elements of a system into packages
and shows the dependencies between these packages.
PAGE 167
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 167 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 9. Object Diagram: Represents a snapshot of the instances of classes


in a system at a particular point in time, showing their attributes
and relationships.
10. Composite Structure Diagram: Describes the internal structure of
a class or component, including its parts, their roles, and how they
interact.
11. Collaboration Diagram (Communication Diagram): Shows how
objects collaborate to achieve a specific behavior or functionality,
focusing on the structural organization of objects and their
interactions.
12. Timing Diagram: Illustrates the behavior of objects over a period
of time, showing the timing constraints and interactions between
objects.
13. Interaction Overview Diagram: Provides an overview of the flow
of control between various interactions or activities in a system.
These UML diagram types are widely used in software engineering and
systems design to visually represent different aspects of a system’s ar-
chitecture, behavior, and structure.

IN-TEXT QUESTIONS
5. Which of the following diagrams in UML is used to depict the
behavior of a system or a part of a system?
(a) Class diagram
(b) Sequence diagram
(c) Use case diagram
(d) State diagram
6. What does a dashed line with an arrow in a UML diagram
represent?
(a) Association
(b) Dependency
(c) Aggregation
(d) Generalization

168 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 168 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

7. What does a dashed line with a hollow arrowhead in a UML Notes


diagram represent?
(a) Inheritance
(b) Interface
(c) Dependency
(d) Association

7.5 Immutable Objects vs. Mutable Objects


In Python, objects are classified into two main categories based on their
mutability: immutable and mutable objects.
1. Immutable Objects: Immutable objects are those whose state cannot
be modified after they are created. This means that any operation
that appears to “modify” an immutable object actually creates a new
object with the modified value rather than changing the original
object itself. Examples of immutable objects in Python include
integers, floats, strings, tuples, and [Link]’s an example
illustrating immutability with integers:

In this example, even though x is incremented by 2, the original


integer object 5 remains unchanged. Instead, a new integer object
7 is created and assigned to x.
2. Mutable Objects: Mutable objects, on the other hand, are objects
whose state can be modified after they are created. This means that
operations can directly modify the contents of the object without
creating a new object. Examples of mutable objects in Python
include lists, dictionaries, sets, and custom [Link]’s an example
illustrating mutability with lists:

PAGE 169
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 169 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes

In this example, the original list [1, 2, 3] is modified by appending 4 to


it. The changes are reflected directly in the original list object.

IN-TEXT QUESTIONS
8. Which of the following data types in Python is immutable?
(a) List
(b) Dictionary
(c) Tuple
(d) Set
9. What happens when you try to modify an immutable object in
Python?
(a) Python raises a SyntaxError
(b) The modification is applied successfully
(c) Python raises a TypeError
(d) The object becomes mutable

7.6 Hiding Data Fields


In object-oriented programming (OOP), data hiding refers to the prac-
tice of encapsulating the internal state of an object and restricting
direct access to it from outside the object’s scope. This principle is
also known as “information hiding” or “encapsulation.” The idea is to
hide the internal details of how an object’s data is implemented and
provide controlled access to it through well-defined interfaces (methods
or functions).

170 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 170 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

There are several ways to achieve data hiding in OOP: Notes


‹ Private Data Members: Declaring data members of a class as
private ensures that they can only be accessed and modified by
member functions of the same class. This prevents external code
from directly manipulating the object’s internal state.
‹ Access Control: OOP languages like C++, Java, and Python provide
access modifiers (e.g., public, private, protected) to control the
visibility of class members. By marking data members as private,
you hide them from external access.
‹ Encapsulation: Encapsulation involves bundling data (attributes)
and methods (functions) that operate on the data within a single
unit, typically a class. This allows for the implementation details
to be hidden from the outside world while providing a well-defined
interface for interacting with the object.
‹ Getter and Setter Methods: Instead of allowing direct access to
data members, getter and setter methods can be used to retrieve
and modify the data, respectively. This allows for validation,
computation, or other actions to be performed when accessing or
modifying the data.
Data hiding promotes modularity, reduces complexity, and enhances secu-
rity by limiting the points of access to an object’s internal state. It also
facilitates better maintenance and evolution of codebases since changes
to the internal implementation can be made without affecting the external
interface as long as the interface remains consistent.

IN-TEXT QUESTIONS
10. What is the primary purpose of data hiding in object-oriented
programming?
(a) To make the code more difficult to understand
(b) To prevent access to certain data from outside the class
(c) To increase the performance of the program
(d) To reduce the number of data members in a class

PAGE 171
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 171 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 11. Which access modifier is typically used to hide data members
from outside access in many OOP languages?
(a) Public
(b) Private
(c) Protected
(d) Static
12. In OOP, data hiding is also known as:
(a) Information overload
(b) Encapsulation
(c) Inheritance
(d) Polymorphism

7.7 Class Abstraction and Encapsulation


Class abstraction and encapsulation are two fundamental concepts in
object-oriented programming (OOP) that contribute to building modular,
maintainable, and reusable code.
1. Abstraction: Abstraction is the process of hiding the complex
implementation details and showing only the necessary features of
an object. In OOP, abstraction allows you to create a simplified
model of a real-world object or system. This simplification helps in
managing complexity by focusing on relevant characteristics while
hiding irrelevant [Link] practice, abstraction is achieved through
the use of abstract classes and interfaces. Abstract classes are classes
that cannot be instantiated directly and may contain abstract methods
(methods without a body) that must be implemented by subclasses.
Interfaces define a contract for classes to implement, specifying
the methods that a class must provide without specifying their
[Link] example, consider a “Shape” class with abstract
methods like “area()” and “perimeter()”. Concrete subclasses like
“Circle” and “Rectangle” will implement these methods according
to their specific shapes.

172 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 172 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

Notes

PAGE 173
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 173 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes In this example:


‹ Shape is an abstract base class (ABC) that defines the interface
for all shapes.
‹ Shape contains two abstract methods area() and perimeter(). These
methods must be implemented by concrete subclasses.
‹ Rectangle and Circle are concrete subclasses of Shape that provide
implementations for area() and perimeter().
‹ Users can create instances of Rectangle and Circle classes and
call their methods (area() and perimeter()), but they don’t need
to know the details of how these methods are implemented
internally.
‹ This example demonstrates class abstraction by defining an abstract
base class Shape with abstract methods. Concrete subclasses (Rectangle
and Circle) inherit from Shape and provide implementations for
these abstract methods. Users interact with these subclasses without
needing to know the implementation details of the area() and
perimeter() methods.
2. Encapsulation: Encapsulation is the bundling of data and methods
that operate on the data into a single unit, typically referred to as a
class. It restricts direct access to some of the object’s components
and hides the internal state of an object from the outside world.
Encapsulation helps in achieving data hiding, abstraction, and
[Link] OOP, encapsulation is implemented using access
specifiers such as public, private, and protected. These specifiers
control the visibility of class members, allowing certain methods
and properties to be accessible from outside the class while keeping
others hidden and accessible only from within the [Link] example,
consider a “BankAccount” class where the balance should only be
modified through methods like “deposit()” and “withdraw()”. The
balance variable can be declared as private, ensuring that it can
only be accessed and modified through the defined methods, thus
encapsulating its implementation details.

174 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 174 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

Notes

In this example:
‹ The BankAccount class has a private variable __balance, indicated
by the double underscore prefix (__).
‹ The deposit() and withdraw() methods are provided to modify the
balance. These methods perform validation checks before modifying
the balance.
‹ The get_balance() method is provided to access the current balance.
This method allows controlled access to the private __balance variable.

PAGE 175
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 175 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ‹ Attempts to directly access or modify the __balance variable from


outside the class will result in an AttributeError because it is private.
‹ This way, encapsulation is achieved in Python by hiding the
implementation details of the BankAccount class’s balance variable
and providing controlled access to it through well-defined methods.
In summary, abstraction and encapsulation are key principles of OOP
that promote code organization, reusability, and maintainability by hid-
ing implementation details and providing a clear interface for interacting
with objects.

7.8 Object-Oriented Thinking


Object-oriented thinking (OOT) is not just a programming paradigm; it’s a
fundamental shift in how developers conceptualize and approach software
design and development. It represents a mindset that revolves around the
concept of objects, which are the basic building blocks of object-oriented
programming (OOP). In this essay, we’ll delve into the principles and
benefits of object-oriented thinking, exploring how it promotes modular,
reusable, and maintainable software development by modeling real-world
entities and their interactions.
At its core, OOT is about modeling software systems after real-world
entities and their relationships. Consider a simple example: a banking
application. In traditional, procedural programming, you might have
functions for withdrawing money, depositing money, and checking an
account balance. However, in OOP, you would conceptualize each of
these functionalities as objects: a BankAccount object, a Transaction
object, and perhaps a Customer object. These objects encapsulate both
data (such as account balances and transaction histories) and behavior
(such as depositing and withdrawing funds). By organizing code around
these objects, developers can create a more intuitive and flexible system
that mirrors the real-world domain.
One of the key advantages of object-oriented thinking is its emphasis on
modularity. By breaking down a complex system into smaller, more man-
ageable objects, developers can isolate different parts of the codebase and
work on them independently. Each object serves as a self-contained unit
with its own internal state and behavior, making it easier to understand

176 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 176 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

and maintain. This modular approach also promotes code reusability, as Notes
objects can be reused in different parts of the application or even in en-
tirely different projects. For example, the BankAccount object created for
a banking application could be reused in a budgeting app or a financial
management tool.
In addition to modularity and reusability, object-oriented thinking also
encourages a focus on maintainability. By modeling software systems
as interconnected objects with well-defined interfaces, developers can
more easily reason about the behavior of their code and make changes
without unintended side effects. For example, if you need to add a
new feature to your banking application, you can simply create a new
object that encapsulates the desired functionality and integrate it into
the existing system. Because each object adheres to a clear interface,
you can be confident that it will interact correctly with other objects
in the system.
Moreover, object-oriented thinking enhances code readability by promoting
a more natural and intuitive structure. When you model software systems
after real-world entities, the resulting code tends to be more expressive
and self-explanatory. For instance, if you’re working on a simulation of a
traffic management system, you might have objects representing vehicles,
traffic lights, and road intersections. By naming these objects and their
methods descriptively (e.g., [Link](), [Link]()),
you can create a codebase that is easy to understand and navigate, even
for developers who are unfamiliar with the project.
Furthermore, object-oriented thinking facilitates collaboration within
development teams by providing a common vocabulary and conceptual
framework. When everyone on the team is thinking in terms of objects
and their interactions, it becomes easier to communicate ideas, share
code, and divide tasks. For example, during a planning meeting for a
new feature, team members can discuss the objects involved, their re-
sponsibilities, and how they will interact with each other. This shared
understanding helps ensure that everyone is on the same page and working
towards the same goals.
In conclusion, object-oriented thinking represents a paradigm shift in
how developers approach software design and development. By modeling
software systems as interconnected objects with well-defined interfaces,

PAGE 177
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 177 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes OOT promotes modularity, reusability, maintainability, readability, and


collaboration. It encourages developers to think in terms of real-world
entities and their interactions, resulting in more intuitive, flexible, and
scalable codebases. In an industry where software complexity is ever-in-
creasing, object-oriented thinking provides a powerful framework for
managing that complexity and building software that meets the needs of
users and stakeholders alike.

IN-TEXT QUESTIONS
13. What is the primary focus of OOT?
(a) Algorithms
(b) Data structures
(c) Objects and their interactions
(d) Procedural programming
14. Which of the following is NOT a benefit of OOT?
(a) Modularity
(b) Code duplication
(c) Reusability
(d) Maintainability

7.9 Programming Examples


Example 1. Write a Python function to sort a list of numbers in ascend-
ing order.

Solution:

178 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 178 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

Explanation: Notes
‹ Define a function sort_numbers that takes a list of numbers as input.
‹ Use the sorted() function to sort the numbers in ascending order.
‹ Return the sorted list.
Example 2. Write a Python function to calculate the average of a list
of numbers.

Solution:

Explanation:
‹ Define a function calculate_average that takes a list of numbers
as input.
‹ Use the sum() function to calculate the total sum of the numbers
in the list.
‹ Use the len() function to count the number of elements in the list.
‹ Calculate the average by dividing the total sum by the count. Return
the result.
Example 3. Write a Python function to multiply two matrices.

PAGE 179
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 179 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes Solution:

180 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 180 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

Explanation: This function takes two matrices as input and returns the Notes
result of their multiplication. It first checks if the matrices can be multi-
plied by comparing their dimensions. If the matrices cannot be multiplied,
it returns None. Otherwise, it initializes a result matrix with zeros and
performs the matrix multiplication using nested loops. Finally, it returns
the resulting matrix.
Example 4. Write a Python function to generate all prime numbers up
to a specified number.

Solution:

Explanation:
‹ This function, generate_primes, takes an integer up_to as input
and generates all prime numbers up to that specified number. It
initializes an empty list primes to store the prime numbers found.

PAGE 181
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 181 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ‹ Within the function, there’s a helper function is_prime(num) that


checks whether a given number num is prime. It iterates from 2 to
the square root of num (inclusive) and checks if num is divisible
by any number in this range. If num is divisible by any number
other than 1 and itself, it returns False, indicating that num is not
prime. Otherwise, it returns True.
‹ The main loop iterates from 2 to up_to (inclusive). For each number
in this range, it calls the is_prime function to check if it’s prime.
If the number is prime, it’s added to the primes list.
‹ Finally, the function returns the list of prime numbers up to the
specified number.
Example 5. Write a Python function that takes a list of integers as input
and returns a new list where each element is doubled. Ensure that the
original list remains unchanged after calling the function.

Solution:

182 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 182 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

Explanation: Notes
‹ The ‘double_elements’ function takes a list of integers’ input_list’
as input.
‹ Inside the function, a new list ‘doubled_list’ is created to store the
doubled elements.
‹ Using a for loop, each element in the ‘input_list’ is doubled and
appended to the ‘doubled_list’.
‹ Finally, the ‘doubled_list’ is returned.
‹ When the function is called with an example list ‘original_list’,
it returns a new list with each element doubled, while leaving the
original list unchanged.

7.10 Exercises Related to Analytics


Exercise 1: Analyzing Student Scores
You have a list of dictionaries, each representing the scores of students
in different subjects. Write a Python function to calculate the average
score for each student and find the student with the highest average score.

Solution:

PAGE 183
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 183 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes

Exercise 2: Analyzing Sales Data


You have two lists, one representing sales amounts and the other repre-
senting expenses for each month. Write a Python function to calculate
the monthly profit (sales - expenses) and find the month with the highest
profit.

Solution:

Exercise 3: Analyzing Stock Prices


You have a list of tuples representing daily stock prices (date, price). Write
a Python function to calculate the average stock price for each month.

184 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 184 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

Solution: Notes

Exercise 4: Analysing Customer Data


You have a dictionary containing customer data. Write a Python function
to find the top N customers with the highest total purchase amount.

Solution:

PAGE 185
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 185 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes

Exercise 5: Analyzing Website Traffic


You have been given a CSV file containing website traffic data. Each
row represents a visit to the website, with columns for the timestamp of
the visit and the number of page views. Write a Python program to read
this CSV file and perform the following analytics:
‹ Calculate the total number of visits to the website.
‹ Determine the average number of page views per visit.
‹ Identify the date with the highest number of visits.
‹ Find the hour of the day with the highest traffic.
You can assume that the CSV file is named “traffic_data.csv” and has
the following structure:
Timestamp,PageViews
2024-05-01 [Link],120
2024-05-01 [Link],100
...

Solution:

186 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 186 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

Notes

7.11 Summary
This lesson provides a comprehensive exploration of fundamental Ob-
ject-Oriented Programming (OOP) concepts, tailored specifically for
Python. Through clear explanations and illustrative examples, learners
delve into the core concepts of OOP, including classes, objects, and UML
class diagrams. They gain a deep understanding of how classes serve
as blueprints for creating objects, encapsulating both data and behavior,

PAGE 187
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 187 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes with UML class diagrams aiding in visualizing class relationships and
hierarchies for better design decisions.
The distinction between immutable and mutable objects within Python is
elucidated, highlighting the advantages and considerations of each. Immutable
objects, maintaining an unchangeable state, are advantageous for scenar-
ios requiring data integrity and concurrency, while mutable objects offer
flexibility but demand careful handling to prevent unintended side effects.
Crucial to OOP, data hiding is thoroughly covered, presenting a range of
techniques to safeguard data within classes, ensuring security and integrity.
Abstraction and encapsulation, fundamental principles of OOP, are ex-
plored in depth within the Python context. Abstraction involves focusing
on essential attributes and behaviors while concealing implementation
details, while encapsulation entails bundling data and methods within a
class, promoting modular design and information hiding.
The lesson culminates in practical problem-solving exercises tailored for
data science applications in Python. Learners apply acquired OOP concepts
and problem-solving strategies to address real-world challenges effectively,
enhancing their proficiency and versatility in Python programming for
data science endeavors.

7.12 Answers to In-Text Questions


1. (b) Objects are instances of classes
2. (b) To create objects
3. (a) It refers to the current instance of the class
4. (c) Instantiation
5. (d) State diagram
6. (b) Dependency
7. (b) Interface
8. (c) Tuple
9. (c) Python raises a TypeError
10. (b) To prevent access to certain data from outside the class
11. (b) Private

188 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 188 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

Notes
12. (b) Encapsulation
13. (c) Objects and their interactions
14. (b) Code duplication

7.13 Self-Assessment Questions


1. You’re given a list of tuples, each representing sales data for a
particular product. Each tuple contains the product name, the quantity
sold, and the price per unit. Write a Python function to calculate
the total revenue generated from the sales data. (Total Revenue =
‫ گ‬TXDQWLW\BVROG  SULFHBSHUBXQLW
# Sample sales data
sales_data = [
(“Product A”, 10, 15.99),
(“Product B”, 5, 29.99),
(“Product C”, 8, 10.50)
]
2. Implement the PageRank algorithm in Python to rank web pages
based on their importance.
3. You have been provided with a CSV file containing customer purchase
data. Each row represents a purchase transaction, with columns for
customer ID, purchase amount, and purchase date. Write a Python
program to read this CSV file and perform the following analytics:
(a) Calculate the total number of unique customers.
(b) Determine the total revenue generated from all purchases.
(c) Find the average purchase amount per customer.
(d) Identify the date with the highest total revenue.
You can assume that the CSV file is named “purchase_data.csv”
and has the following structure:
CustomerID,Amount,Date
1,20.99,2024-05-01
2,15.49,2024-05-01
...
PAGE 189
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 189 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes 4. You have been given a CSV file containing sales data. Each row in
the CSV represents a sale, with columns for the date of sale, the
item sold, the quantity sold, and the price per item. Write a Python
program to read this CSV file and perform the following analytics:
(a) Calculate the total sales revenue.
(b) Find the item that generated the highest revenue.
(c) Calculate the average price per item.
(d) Determine the date with the highest sales revenue.
You can assume that the CSV file is named “sales_data.csv” and
has the following structure:
Date,Item,Quantity,Price
2024-05-01,Product A,10,15.99
2024-05-02,Product B,5,20.49
...
5. You have been provided with a CSV file containing social media
engagement data. Each row represents a post on a social media
platform, with columns for the post ID, number of likes, number
of comments, and number of shares. Write a Python program to
read this CSV file and perform the following analytics:
(a) Calculate the total number of posts.
(b) Determine the average engagement (likes + comments + shares)
per post.
(c) Identify the post with the highest engagement.
(d) Find the post with the highest number of likes per comment
ratio.
You can assume that the CSV file is named “social_media_data.
csv” and has the following structure:
PostID,Likes,Comments,Shares
1,100,20,5
2,200,25,8
...

190 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 190 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING

Notes
7.14 Suggested Readings
‹ Bader, D. (2017). Python Tricks: A Buffet of Awesome Python
Features. Dan Bader.
‹ Lutz, M. (2013). Learning python: Powerful object-oriented
programming. “O’Reilly Media, Inc.”
‹ Grus, J. (2019). Data science from scratch: first principles with
python. O’Reilly Media.
‹ McKinney, W. (2022). Python for data analysis. “O’Reilly Media,
Inc.”

PAGE 191
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 191 15-10-2025 [Link]


PFUP_Unit_04_Lesson [Link] 192 15-10-2025 [Link]
UNIT - V
File and Exception Handling

PAGE 193
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 193 15-10-2025 [Link]


PFUP_Unit_04_Lesson [Link] 194 15-10-2025 [Link]
L E S S O N

8
File and Exception
Handling

STRUCTURE
8.1 Learning Objectives
8.2 Introduction
8.3 Opening and Closing File
8.4 Interacting with File
8.5 Errors and Exceptions
8.6 Exception Handling
8.7 Object Oriented Programming
8.8 Summary
8.9 Glossary
8.10 Answers to In-Text Questions
8.11 6HOI$VVHVVPHQW 4XHVWLRQV
8.12 5HIHUHQFHV
8.13 Suggested Readings

8.1 Learning Objectives


After reading this lesson you will be able to:
‹ Recall and define some basic concepts and terminology related to file handling and
exceptions.
‹ Explain the purpose and use of some of the key functions dealing with file handling
and describe how they interact with file operations.

PAGE 195
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 195 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes ‹ Apply their knowledge in developing a working Python script for


handling files, along with suitable error handling.
‹ Analyse poorly written code given to understand the nature of
mistakes made regarding file and exception handling

8.2 Introduction
Till now we have taken data interactively from the user, such data is
stored in memory only till the program’s lifetime. But there are appli-
cations where we need to save the data to permanent memory which is
available even after the lifetime of the program. This can be done using
files, data stored in file remain on the disk and can be accessed when-
ever required. Therefore, we need to understand file handling and how
python interacts with files.
Python comes with a standard input file (you can type into the standard
input file using keyboard) as well as output file (which shows up on the
screen) that can be used to handle temporary data. Besides these common
input/output files, we can also make disk files that store data permanently
so that we can use it again later.
A file is a stream of bytes containing some data that you need to process.
Files can be utilized in any application that requires persistent data storage
like processing student data or maintaining patient history. You will learn
a lot about how to handle files in this lesson. Also, you will understand
how programs deal with exceptions that occur during file handling, like
when a file we want to read from is not available.

8.3 Opening and Closing File


To process (read or write) a file you will first need to open it using the
built-in function open (). You can open a file with the following syntax:
ILOH  RSHQ ILOHBQDPH PRGH
This function takes the file name as its first argument. The second option
“mode” specifies the access mode for the file. A file can be opened in
three modes: read (r), write (w), or append (a).
‹ Read mode is used to read an existing file. It will allow us to read
the data from the file and we can do processing of this data in your
196 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 196 15-10-2025 [Link]


FILE AND EXCEPTION HANDLING

python code. Opening a file in read mode will result in an error if Notes
the given file does not exist. The syntax is :
 2SHQ D ILOH LQ UHDG PRGH
ILOH  RSHQ µH[DPSOHW[W¶ µU¶
‹ Write mode is used to access a file and write data into it using
python code. Opening a file in write mode automatically creates a
new file if the requested file does not exist, but if a file already
exists then opening it in write mode will overwrite any data present
in the file.
ILOH  RSHQ µH[DPSOHW[W¶ µZ¶
‹ Append mode allows you to add content to a file by adding it at
the end. If the requested file does not exist, a new one is generated.
ILOH  RSHQ µH[DPSOHW[W¶ µU¶
Note that providing mode parameter while opening the file is optional.
So, without the mode option, the open function will open file in read
mode by default. After successfully executing the open function, a file
object is returned. Failure to open the file results in an error. Also, in
the code snippets written above we have assumed that file is present in
the current working directory but in case your file is stored in a different
location you need to provide the complete path. For example, if the file
is saved in the “Downloads” folder, you need to provide the full path to
the file when opening it.
ILOHBSDWK  U¶&?8VHUV?<RXU8VHUQDPH?'RZQORDGV?H[DPSOHW[W
ILOH  RSHQ ILOHBSDWK
This code opens a file named [Link] kept in downloads folder in
the default mode that is read mode. Thus, open function creates a file
object that can be used to interact with the file in python program.

Closing a file
Closing a file is also very important, it ensures resource management, data
integrity, and file safety. You can use [Link]() or use with statement
for file operations efficiently handles a file without causing potential
issues to it. Subsequent sections will show use of both these statements
to handle file.

PAGE 197
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 197 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes
8.4 Interacting with File
<RXFDQUHDGZULWHDQGDSSHQGGDWDLQ¿OH7KH¿OHKDQGOLQJIXQFWLRQVDUHH[-
plained in this section.

File Read
Python allows you to read a complete file in one go or line by line. The
program below shows reading in one go and line by line:

In the code above open(‘[Link]’, ‘r’) command opens the file ex-
[Link] in read mode. The file path may be relative or absolute. file.
read(), reads the complete file contents. [Link](), exits the file to free
up system resources. Let’s see another program to read file line by line:

Here, [Link](), reads a single line from the file. The while loop runs
until readline() returns an empty string, which occurs at the end of the
file. [Link](), removes all leading and trailing whitespace characters
(including newlines).
Reading bytes from a file: Sometimes we are not interested in reading
the whole content of the file instead we need only a chunk of data. This
can be achieved using byte read. Suppose there is file [Link] having

198 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 198 15-10-2025 [Link]


FILE AND EXCEPTION HANDLING

content “hi this is a long programming text for byte reading example”. Notes
The code below shows to read bytes.

You can also use seek() to find a particular position in the file and read
from there.

File Write
When you open a file in write mode (‘w’), you can enter data into it. If
the file already exists, it will be overwritten; otherwise, a new file will
be created. Note that write function returns number of characters written
into the file (in shell). Also, python doesn’t allow you to perform read
operation on the file that is opened in write mode. It returns unsupported
operations error in such case.

PAGE 199
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 199 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes Here, open(‘[Link]’, ‘w’), opens the file in write mode and creates it
if it does not already exist. [Link](), writes the provided text to the
file. We can also use ‘with’ statements. This allows you to efficiently
handle file resources. When working with files, using with is suggested
because it closes the file automatically, even if an error occurs during
file operations.

To read and write a file simultaneously you can use ‘r+’ mode to open file.

8.5 Errors and Exceptions


Programming errors are like potholes in the road—those things that don’t
go according to plan and that get in the way of our work. Errors in Py-
thon generally come in one of two ways: syntax errors and exceptions.
Syntax Errors: These occur when you violate one of the rules of python’s
grammar rules. If, for example, you omit the closing quotation mark in
a print() function, python will raise a syntax error. Another common er-
ror is to leave off the colon at the end of the for loop, which is also a
syntax error: indentation errors are another common sort of error. Python

200 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 200 15-10-2025 [Link]


FILE AND EXCEPTION HANDLING

is fussy about indentation, and incorrect indentation will raise a syntax Notes
error or sometimes a logical error. Indentation errors can result in logic
errors, which are probably the most subtle - these don’t pop up as overt
‘errors,’ but will frequently alter how your program is intended to func-
tion, in subtle manners that are not at all obvious to detect.
Exceptions: Unlike syntax errors, exceptions are conditions that take
place at the time of the execution of your code. These can’t be detected
by python until the time the code is in fact running. For example, at-
tempting to read from a file which doesn’t exist, dividing a number by
zero, or attempting to access a variable which hasn’t had a value assigned
will raise exceptions. These types of errors will stop the execution of the
program at the line on which the error occurs. If an exception occurs,
Python writes a traceback to the screen, which indicates the name of the
error and where in the code it happened.
Note that syntax errors are usually easy to locate, but the exceptions
often force you to carefully read the traceback and find the problem.
Some common exceptions are discussed below:
‹ NameError: This generally occurs when python cannot find the
name that you have mentioned in your code statement globally.
Mostly the name error occur due to typo while writing the code or
due to incorrect case (since python is case sensitive), like writing
int as Int , or accessing a variable before defining. An example is
shown below:

Here it should be print().


‹ TypeError: This occurs when we apply the wrong function to an
object, that is when data type and operation applied on that datatype
do not match or calling a method on an object that doesn’t support
that method.

PAGE 201
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 201 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes

‹ ValueError: This exception happens when an inappropriate parameter


value is used in a function call, regardless of its correctness. For
example:

‹ ZeroDivisionError: This exception occurs when the denominator


of a division is zero, such as in the following example:

‹ IndexError: This error is raised when you attempt to access an


element from a sequence-list, tuple, or string-using an index that
lies outside the valid range of indices for the sequence. In other
words, you are trying to reach an index that doesn’t exist. Refer
to example below for details:

202 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 202 15-10-2025 [Link]


FILE AND EXCEPTION HANDLING

Notes

‹ OSError: This is a generic set of exceptions that shows that there is


some problem with system-level operations, such as file operations.
For Example, in the code below, we trying to access a file that
doesn’t exist in the system generating a FileNotFoundError:

IN-TEXT QUESTIONS
1. To open a file in Python, the built-in function used is ‘__________’.
2. To close a file after performing operations, the ‘__________’
method is used.
3. The operation which reads all the contents of a file into memory
at once is ‘__________’.

8.6 Exception Handling


You have seen many exceptions and their examples in previous sections,
as you may have noticed that exceptions can cause abrupt program

PAGE 203
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 203 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes termination. These exceptions are referred to as unhandled, to avoid such


situations exception handling can be done in code. This allows the pro-
gram to catch errors gracefully and handle them, enabling your program
to handle situations that are not envisioned by the programmer without
breaking down. In Python, exceptions can be dealt with using try, except,
else, and finally. In this section you will learn, with an example, the main
concepts and syntax for exception handling.
Let’s understand the basic structure of exception handling as shown below:

Here, you can see that the order of writing is try, except, else and finally
(note that pass is to just to pass the code as a place holder).
A try block contains statements that may raise an exception. The try
block carries the codes you want to implement, and consequently, it’s the
place where exceptions could happen. If any error occurs in this block,
Python stops the rest of the code executions in the try block and jumps
to the except block.
An except block specifies what action should be taken when an exception
is raised in the try block. The except clause allows you to provide a set
of exceptions and the common action to take when they occur. Alterna-
tively, you give different actions for each exception.
Else block is invoked if there is no exception in the try block. It is
mainly used for codes that should be executed only if the try block is
successful.

204 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 204 15-10-2025 [Link]


FILE AND EXCEPTION HANDLING

Finally block is always executed (if it is present in the code) whether Notes
there was an exception or not. It is commonly used for cleaning up tasks
like closing files and releasing resources.
A few examples of exception handling are shown below:
Example 1: Try…except block

Example 2: Try…except...else block

Example 3: Try…except...finally block

PAGE 205
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 205 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes Example 4: Multiple exceptions

8.7 Object Oriented Programming


The concept of object-oriented programming is supported in python, we
have already seen a built-in class str in previous chapter. In this section
we will explore concept of class and objects. The class and objects are
one of the core concepts in object-oriented programming (OOP) languag-
es, and the language Python is no exception. With these two concepts,
you can model real-world entities, organize their code, create reusability,
and scalabilities.

Class
A class can be perceived as a template design for objects. The class de-
fines a set of attributes and methods which the instantiated objects will
contain. In Python, a class is declared using the class keyword preceded
by the class name.
Classes combine data (attributes) and functions (methods) into a single
‘unit’. The class is a blueprint; the actual data, however, lies within an
object which is formed from it. You can define class as shown.

206 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 206 15-10-2025 [Link]


FILE AND EXCEPTION HANDLING

Notes

In the above code ClassName is the name of the class( Conventionally,


class names are written in PascalCase). _init_ is a special constructor
method in classes of Python. It is automatically invoked whenever the
object has been created. It can be used to initialize attributes of an object.
Instance Variables vary in their value from one instance to another of
the class. The variables are declared using the keyword self, inside the
constructor or other methods. Functions defined inside a class are called
methods they operate on objects of the class.

Object
An object is an instance of a class. It is the concrete realization of the
blueprint provided by the class. Every object has its own data and can
use the methods defined in the class.A new object is constructed refer-
ring to the class name, and if necessary, passing appropriate arguments
to the constructor.

We can use objects to invoke methods of class and do the processing.


Remember we can have class attributes as well such attributes are shared
across all instances i.e. they are global to all objects, while instance
attributes are specific to each object i.e. each object has its own copy.

Example

PAGE 207
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 207 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes

Here, we define a `Car` class, with a class attribute `wheels` shared by


all instances of the class. The `__init__` constructor is used to initialize
three instance attributes: `make`, `model`, and `year`, which are unique
to each car object. The class has two methods: `display_info()` prints the
details in a formatted string as the car’s details, and `start()` outputs a
message stating the car is started. We create an object instantiating two
cars, `car1` and `car2`, and we pass certain values for the `make`, `model`
and `year` attributes. We refer to attributes and methods using dot nota-
tion : `object_name.method_name()`. We can refer to the class attribute
`wheels` directly with the class name, `[Link]`. This is important as
class attributes are shared among all instances while instance attributes
depend on the object. This definition affects the object behavior, where
each object keeps track of its own state and actions, based on class defi-
nition. The primary question is why Python uses the `__init__()` method.
And the explanation is that `__init__()` is the so-called constructor method
that gets automatically invoked every time an object is constructed. It is
used to initialize the object’s attributes.
208 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 208 15-10-2025 [Link]


FILE AND EXCEPTION HANDLING

Notes
8.8 Summary
In this chapter we discussed file handling and exception handling in
python. File handling is generally associated with the functions and li-
braries that are being used to carry out manipulative activities with files,
such as opening, reading, writing, or closing files. The `open()` function
provides access to files in various modes such as reading (`”r”`), writ-
ing (`”w”`), or appending (`”a”`). The `with` statement is very common
when working with files, to guarantee that a file is closed after it is
no longer needed-even when an exception occurs. Handling exceptions,
on the other hand enables you to gracefully deal with errors or other
unexpected events. You can use the `try`, `except`, `else`, and `finally`
blocks for catching exceptions and handling them; you can also perform
some actions in case of no exception occurrence and make some code
execute regardless of, if an error has occurred. This systematic handling
of errors helps to maintain the stability of the program and provides
more informative feedback upon encountering any errors. We have also
learned about the concept of classes and objects and how python supports
object-oriented programming.

8.9 Glossary
Exception: An exception is an error condition that happens while the
execution of an application or process, which upsets the usual flow of
instructions. Python raises exceptions when the program comes across
situations like invalid input or file operations errors.
File handling: Operations of files may include reading, writing, and
closing of the files using some in-built functions of Python, such as
open(), read(), and write().
Try-Except Block: A python construct employed to manage exceptions by
wrapping the code that may cause an error in a try block, and defining
how to handle specific exceptions in an except block.
FinallyThe block of code that gets executed after the try and except blocks,
regardless of whether an exception was raised or not. This is typically
used for cleanup actions, such as closing a file or releasing resources.

PAGE 209
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 209 15-10-2025 [Link]


OBJECT ORIENTED PROGRAMMING USING PYTHON

Notes
8.10 Answers to In-Text Questions
1. open()
2. close()
3. read()

8.11 Self-Assessment Questions


1. Describe how you would use the try and except blocks to handle an
exception that might occur if you were trying to write data into a
file.
2. Explain the difference between Python’s FileNotFoundError and
IOError. Provide a code example where each might be raised.
3. Create a Python function that reads a file and returns the contents.
4. Identify the error in the code sample below and explain how to solve
them using exception handling.

5. Create a Python script that prompts the user for a filename before
attempting to open and read the file. You should handle case in
which the file does not exist.
6. What is the difference between a class attribute and an instance
attribute in Python?
7. Extend the class `Car` so that the class provides a method to calculate
the car age relative to current year.

8.12 References
‹ Taneja, S., Kumar, N., Python Programming- A modular Approach,
Pearson Education India, 2018.
‹ Balagurusamy E., Introduction to Computing and Problem-Solving
using Python, 2nd edition, McGraw Hill Education, 2018.

210 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 210 15-10-2025 [Link]


FILE AND EXCEPTION HANDLING

Notes
8.13 Suggested Readings
‹ Brown, Martin C., Python: The Complete Reference, 2nd edition,
McGraw Hill Education, 2018.
‹ Guttag, J.V. Introduction to computation and programming using
Python, 2nd edition, MIT Press, 2016.

PAGE 211
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi

PFUP_Unit_04_Lesson [Link] 211 15-10-2025 [Link]


TP25

PFUP_Unit_04_Lesson [Link] 212 15-10-2025 [Link]

Common questions

Powered by AI

UML class diagrams are crucial for understanding and designing Object-Oriented systems as they provide a visual representation of classes, including their attributes, methods, and interrelationships. They help in visualizing the system architecture, identifying dependencies, and ensuring coherent structure. By depicting classes as blueprints, developers can better grasp complex class interactions and design robust, maintainable code that aligns with software requirements .

The key principles of OOP in Python include encapsulation, abstraction, inheritance, and polymorphism. Encapsulation restricts access to certain components, promoting modularity and code security. Abstraction hides complex implementation details, focusing instead on necessary functionalities. Inheritance allows new classes to inherit attributes and methods from existing ones, fostering code reusability. Polymorphism enables methods to process objects differently based on their class or data type, enhancing flexibility. These principles collectively help organize code, make it reusable, and manage complexity in software development .

The try-except block is fundamental because it allows programs to handle exceptions gracefully, avoiding program crashes. The try block contains code that might throw an error, and if an exception occurs, the execution moves to the except block where the error is handled, allowing for appropriate action and user feedback. This ensures robustness by isolating erroneous parts of code, making it possible to recover from runtime errors and maintain program stability .

Effective error and exception handling improve software reliability by preventing unexpected shutdowns and promoting continuous operation through graceful error recovery. It enhances user experience by providing meaningful feedback, allowing users to understand and correct inputs. Furthermore, by isolating error-prone code with constructs like try-except, developers can anticipate potential issues and implement recovery paths or fallbacks, ensuring application stability. Such practices build user trust and promote smoother interactions with software systems .

Input-output functions enhance interactivity by allowing user data to be dynamically inserted into programs and displaying results back to the user. For instance, the input() function in Python captures user input from the console, while print() displays data. These functions make applications more engaging and adaptable to user needs by providing real-time feedback and data processing. For example, using input() as in 'userName = input("Enter the name of user:")' waits for user input and incorporates it into program logic .

The finally block plays a crucial role in ensuring that cleanup actions occur in exception handling, as it executes regardless of whether an exception was raised. This characteristic makes it essential for releasing resources like closing files or network connections, maintaining program integrity, and preventing resource leaks. Typical use cases include finalizing transactions and ensuring necessary cleanup operations after handling exceptions, protecting against unexpected interruptions .

A statement in Python is a line of code that performs an action or a command without returning a value, such as variable assignments or control flow structures like loops. An expression, on the other hand, evaluates to a value and consists of variables, operators, and function calls. Understanding the distinction is crucial because it impacts how the code executes, enabling developers to predict the behavior of their programs more accurately and optimize for efficiency .

Built-in data structures such as lists, tuples, and dictionaries offer various benefits including ease of use, efficient data manipulation, and built-in methods that simplify common tasks. Lists are mutable, providing flexibility but requiring careful handling to avoid side effects. Tuples are immutable, offering stability and thread-safety. Dictionaries allow quick access and storage by key-value pairs, enhancing performance in situations where data lookups are frequent. These properties influence how developers manage and optimize code performance, balancing between speed and memory efficiency .

Raising exceptions explicitly with the raise statement is necessary when dealing with application-specific errors not covered by Python’s built-in exceptions. For instance, when certain conditions must be met, like input validation that ensures only positive numbers are allowed, a ValueError can be raised to handle invalid inputs. This mechanism provides clarity within code, communicates specific errors, and ensures logical consistency by allowing developers to transparently manage error handling according to application needs .

Python's strings are immutable, meaning once a string object is created, it cannot be modified. This immutability ensures data integrity and optimizes performance by allowing Python to reuse objects, leading to more efficient memory management. However, it also means that operations like concatenation or slicing create new strings rather than modifying existing ones, which could impact performance if not handled carefully .

You might also like