Object-Oriented Python Programming Guide
Object-Oriented Python Programming Guide
Editor
Deekshant Awasthi
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
Printed at: Taxmann Publications Pvt. Ltd., 21/35, West Punjabi Bagh,
New Delhi - 110026 (250 Copies, 2025)
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
UNIT-III
User Defined Functions
Lesson 5: User Defined Functions in Python 93–115
UNIT-IV
Built-in Data Structures
Glossary 151–154
UNIT-V
File and Exception Handling
PAGE i
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 1
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
PAGE 3
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
4 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
PAGE 5
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
6 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 7
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
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
PAGE 11
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
14 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
PAGE 15
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Notes
PAGE 17
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
18 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
3. Click on Save As option and save the file with a .py extension,
say [Link].
Notes
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
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.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
PAGE 23
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
PAGE 25
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
PAGE 27
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
28 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 29
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Notes
2.4.3 Boolean Literals
Boolean literals represent the truth values: True or False.
For Example:
# Boolean literals
flag = True
x = False
30 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
PAGE 31
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
a = “Hello World!!”
print(a)
32 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
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
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
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
print(b != c) Notes
print(c > b)
————— OUTPUT —————
True
False
True
True
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
PAGE 37
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
For Example:
a = 10 # binary representation of the value 10 : 0000 1010
38 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 39
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
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
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
42 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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.
44 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
PAGE 45
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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.
PAGE 47
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
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.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
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
52 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 53
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
54 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 55
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
56 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 57
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Notes
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”]
58 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 59
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
60 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
PAGE 61
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
PAGE 63
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
PAGE 65
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
66 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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)
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
10. Write a program to print the following patterns on output screen: Notes
D E F
G H I
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
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
70 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
PAGE 71
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
74 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
76 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 77
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
78 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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])
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.
PAGE 81
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
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
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
86 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
88 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
PAGE 91
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
PAGE 93
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
94 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
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
PAGE 97
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Display(“Hello there!”)
————— OUTPUT —————
Hello there!
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)
PAGE 99
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
100 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
102 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 103
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
104 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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)
PAGE 105
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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)
PAGE 107
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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.
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
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
PAGE 111
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
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.
114 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
PAGE 117
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
PAGE 121
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
PAGE 123
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
124 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 125
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
126 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
print(list3) Notes
print(list4)
————— OUTPUT —————
[1, 2, 3, 4, 5]
[1, 2, 3, 1, 2, 3]
PAGE 129
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
130 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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]
PAGE 131
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
134 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 135
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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’])
136 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
138 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 139
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
140 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
142 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 143
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
144 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
PAGE 145
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
146 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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.
148 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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()
PAGE 149
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
PAGE 151
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
PAGE 153
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
PAGE 155
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
PAGE 157
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
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.
160 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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:
PAGE 163
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Notes
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
PAGE 165
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
166 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
PAGE 169
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Notes
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
170 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
172 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Notes
PAGE 173
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
174 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
176 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
Solution:
178 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
Notes Solution:
180 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
Solution:
182 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
Solution:
PAGE 183
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Notes
Solution:
184 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Solution: Notes
Solution:
PAGE 185
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Notes
Solution:
186 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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.
188 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Notes
12. (b) Encapsulation
13. (c) Objects and their interactions
14. (b) Code duplication
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
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
PAGE 193
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
PAGE 195
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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.
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
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
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
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.
200 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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:
PAGE 201
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Notes
202 PAGE
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Notes
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 ‘__________’.
PAGE 203
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
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
PAGE 205
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
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
Notes
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.
Example
PAGE 207
© Department of Distance & Continuing Education, Campus of Open Learning,
School of Open Learning, University of Delhi
Notes
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
Notes
8.10 Answers to In-Text Questions
1. open()
2. close()
3. read()
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
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
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 .