Python Programming
Python Programming
EDITOR
Dr. Kampa Lavanya
Assistant Professor
Department of CS&E
Acharya Nagarjuna University
ACADEMIC ADVISOR
Dr. Kampa Lavanya
Assistant Professor
Department of CS&E
Acharya Nagarjuna University
DIRECTOR, I/c.
Prof. V. Venkateswarlu
M.A., M.P.S., M.S.W., [Link]., Ph.D.
Centre for Distance Education
Acharya Nagarjuna University
Nagarjuna Nagar 522 510
Ph: 0863-2346222, 2346208
0863- 2346259 (Study Material)
Website [Link]
E-mail: anucdedirector@[Link]
MCA : Programming and Problem-Solving Using Python
No. of Copies :
This book is exclusively prepared for the use of students of MASTER OF COMPUTER
APPLICATIONS (MCA), Centre for Distance Education, Acharya Nagarjuna University
and this book is meant for limited circulation only.
Published by:
Prof. V. VENKATESWARLU
Director, I/c
Centre for Distance Education,
Acharya Nagarjuna University
Printed at:
FOREWORD
Since its establishment in 1976, Acharya Nagarjuna University has been
forging ahead in the path of progress and dynamism, offering a variety of courses
and research contributions. I am extremely happy that by gaining ‘A+’ grade from
the NAAC in the year 2024, Acharya Nagarjuna University is offering educational
opportunities at the UG, PG levels apart from research degrees to students from
over 221 affiliated colleges spread over the two districts of Guntur and Prakasam.
The University has also started the Centre for Distance Education in 2003-
04 with the aim of taking higher education to the door step of all the sectors of the
society. The centre will be a great help to those who cannot join in colleges, those
who cannot afford the exorbitant fees as regular students, and even to housewives
desirous of pursuing higher studies. Acharya Nagarjuna University has started
offering [Link]., B.A., B.B.A., and [Link] courses at the Degree level and M.A.,
[Link]., [Link]., M.B.A., and L.L.M., courses at the PG level from the academic
year 2003-2004 onwards.
It is my aim that students getting higher education through the Centre for
Distance Education should improve their qualification, have better employment
opportunities and in turn be part of country’s progress. It is my fond desire that in
the years to come, the Centre for Distance Education will go from strength to
strength in the form of new courses and by catering to larger number of people. My
congratulations to all the Directors, Academic Coordinators, Editors and Lesson-
writers of the Centre who have helped in these endeavors.
UNIT II
Text Files: Strings, Formatted Output, Files, Errors and Exception Handling
Execution and Control Structures: if Statement, for Loop, Two Dimensional Lists, while
Loop, More Loop Patterns, Additional lteration Control Statements
Containers and Randomness: Dictionaries, Other Built-in Container Types, Character
Encoding and Strings, Module random, Set Data Type.
UNIT III
Object Oriented Programming: Fundamental Concepts, Defining a New Python Class,
User- Defined Classes, Designing New Container Classes, Overloaded Operators,
lnheritance, User- Defined Exceptions
Namespaces: Encapsulation in Functions, Global versus Local Namespaces, Exception
Control Flow, Modules and Namespaces.
Objects and Their Use: Software Objects, Turtle Graphics, Modular Design: Modules, Top-
Down Design, Python Modules
Recursion: Introduction to Recursion, Examples of Recursion, Run Time Analysis,
Searching, Iteration Vs Recursion, Recursive Problem Solving, Functional Language
Approach.
UNIT IV
Graphical User Interfaces: Basics of tkinter GUI Development, Event-Based tkinter
Widgets, Designing GUls, OOP for GUI,
The Web and Search: The World Wide Web, Python WWW API, String Pattern Matching,
Database Programming in Python
Prescribed Book:
Ljubomir Perkovic, "Introduction to Computing Using Python: An Application Development
Focus", Wiley, 2012.
Reference Book:
Charles Dierbach, "Introduction to Computer Science Using Python: A Computational
Problem- Solving Focus”, Wiley, 2013.
(205MC24)
M.C.A. DEGREE EXAMINATION, MODEL QUESTION PAPER
Second Semester
205MC24: Programming and Problem-Solving Using Python
SECTION-A
Answer Question No.1 Compulsory 2 Marks × 7 = 14 Marks
1. a) What is a Python variable?
b) Define tuple?
c) What is formatted output?
d) Define a set in Python?
e) What is inheritance?
f) What is a module in Python?
g) What is the purpose of the sqlite3 library?
SECTION-B
Answer ONE Question from Each Unit 4 × 14 = 56 Marks
UNIT – I
2. a) Describe the features and advantages of Python as a programming language.
b) Explain expressions, variables, and assignments in Python with suitable examples.
OR
a) Explain objects and classes in Python with examples.
b) What is the Python Standard Library? Discuss any four useful modules.
UNIT – II
3. a) Explain string manipulation and file operations in Python with examples.
b) Describe error handling and exceptions in Python with appropriate code examples
OR
a) Explain control structures in Python (if, for, while, break, continue, and pass).
b) Describe the set data type and module random in Python with examples.
UNIT – III
4. a) Explain user-defined classes and method overriding with examples.
b) Discuss namespaces in Python — global, local, and built-in — with suitable examples.
OR
a) Explain recursion and write a Python function for binary search using recursion.
b) Describe modular programming and explain how modules improve software design.
UNIT – IV
5. a) Explain the design and development of GUIs using the tkinter library.
b) Describe event-driven programming using tkinter widgets with examples.
OR
a) Explain the use of Python for Web programming and string pattern matching using regular
expressions.
b) Write a short note on database programming in Python with an example of CRUD
operations.
CONTENTS
[Link] TITLES PAGE No
1 INTRODUCTION 1.1-1.14
4 STRING 4.1-4.19
5 FILES 5.1-5.13
10 TUPLE 10.1-10.20
11 SET 11.1-11.11
12 RANDOMNESS 12.1-12.13
14 14.1-14.15
OBJECTS AND THEIR USES
15 RECURSION 15.1-15.17
16 NAMESPACES 16.1-16.16
The primary goal of this chapter is to understand the concepts of Computational Problem
Solving & Python Programming. The chapter began with understanding of The Process of
Computational Problem Solving and Python Programming Language. After completing this
chapter, the student will understand the complete idea about of Computational Problem
Solving & Python Programming.
STRUCTURE
1.1 Introduction
1.2 Computational Problem Solving
1.2.1 What is Computational Problem Solving?
1.2.2 Example
1.3 Python Programming Language
1.3.1 Evolution of the Python Programming Language
1.3.2 Advantages and Disadvantages of Python
1.3.3 Companies used by Python.
1.3.4 Applications of Python
1.3.5 Features of Python
1.3.6 Key Features of Python
1.4 How to Write and Run A Python Script
1.4.1 The operating system command-line or Terminal
1.4.2 The Python Program Create and Run on Interactive Shell
1.4.3 How to Run Python Program on IDLE?
1.5 Summary
1.6 Technical Terms
1.7 Self-Assessment Questions
1.8 Suggested Readings
1.1. INTRODUCTION
Python is an ideal language for computational problem solving due to its simplicity,
readability, and powerful libraries. It allows programmers to focus on developing algorithms
and logic rather than dealing with complex syntax. Python's extensive standard library and
third-party modules, such as NumPy for numerical computations and SciPy for scientific
computing, provide robust tools for tackling a wide range of problems. The language
Programming and Problem-Solving … 1.2 Introduction
supports various programming paradigms, making it suitable for everything from small
scripts to large-scale applications. Python's dynamic typing and interactive environment
further enhance its ability to prototype and test solutions quickly, making it a preferred choice
for developers and researchers alike.
The chapter first covered the Process of Computational Problem Solving, Python
Programming Language.
1.2.2 Example
The basic structure and logic for an online shopping system is explained here. By following
this plan, you can implement a functional program that allows users to browse items, add
them to a cart, view and manage their cart, and checkout. This approach ensures that the
system is user-friendly and efficient.
Problem Definition
We want to create a simple online shopping system that allows users to:
1. Browse items available for purchase.
2. Add items to a shopping cart.
3. View the shopping cart.
4. Remove items from the shopping cart.
5. Checkout and see the total price.
Centre for Distance Education 1.3 Acharya Nagarjuna University
Algorithm Design:
We'll design a basic algorithm to manage our online shopping system:
Step 1: Start
Step 2: Initialize Data
ITEMS = [
(1, "Award-Winning Novel 1", 350),
(2, "Award-Winning Novel 2", 280),
(3, "Award-Winning Novel 3", 300),
(4, "Award-Winning Novel 4", 275),
(5, "Award-Winning Novel 5", 400),
(6, "Award-Winning Novel 6", 325),
(7, "Award-Winning Novel 7", 290),
(8, "Award-Winning Novel 8", 310),
(9, "Award-Winning Novel 9", 340),
(10, "Award-Winning Novel 10", 360),
(11, "Award-Winning Novel 11", 295),
(12, "Award-Winning Novel 12", 315)
]
REPEAT
DISPLAY "------ ONLINE BOOK STORE ------"
DISPLAY "1. View Items"
DISPLAY "2. Add Item to Cart"
DISPLAY "3. View Cart"
DISPLAY "4. Remove Item from Cart"
Programming and Problem-Solving … 1.4 Introduction
Step 5: Stop
Here’s a concise and clear table summarizing all the Python requirements for your Online
Shopping System:
Table 1: Python Requirements for online shopping application
Category Python Purpose / Use in Program
Concept /
Statement
Data Types int Store item numbers, prices, and quantities
float Represent prices with decimals (if needed)
str Store item names and messages
list Maintain collection of items and shopping cart
tuple Represent each item as (id, name, price)
Control Statements if, elif, else Make decisions (menu options, valid input checks)
while Repeat the menu until user exits
for Traverse item lists and calculate totals
break Exit loop when user chooses to quit
Input / Output input() Take user input for menu choices and item numbers
print() Display menus, items, and messages
f-string Format output neatly (e.g., f"₹{price}")
Operators +, * Add totals and compute price × quantity
==, !=, <, > Compare menu options and check item validity
and, or Combine multiple conditions
Data Structures List of Tuples Store available novels (id, name, price)
List (Cart) Keep track of items added by the user
Functions def Create reusable modules like view_items(),
(Optional) checkout()
Modules (Optional) os Clear screen using [Link]('cls' or 'clear')
time Pause execution briefly using [Link]()
Loop Control Boolean Flag Continue or stop the main loop (running =
True/False)
Programming and Problem-Solving … 1.6 Introduction
Python is a high-level, interpreted programming language known for its simplicity and
readability. Created by Guido van Rossum and first released in 1991, Python emphasizes
code readability with its notable use of significant whitespace. It supports multiple
programming paradigms, including procedural, object-oriented, and functional programming,
making it versatile for a wide range of applications. Python's extensive standard library,
dynamic typing, and ease of integration with other languages and tools have contributed to its
widespread adoption in various fields, including web development, data science, artificial
intelligence, scientific computing, and automation. The language's community-driven
development ensures continuous improvements and the availability of numerous third-party
libraries and frameworks, further enhancing its capabilities and appeal.
Python was created by Guido van Rossum in 1980s. While in the Netherlands' National
Research Institute for Mathematics and Computer Science, he created Python, an easy-to-
read and use programming language. This programming language was called after the
Pythons from Monty Python's Flying Circus, the founder's favorite comedians.
The first version, launched in 1991, contained few built-in data types and rudimentary
capabilities. Python 1.0 was introduced in 1994 with map, lambda, and filter functions after
scientists adopted it for numerical computations and data analysis. After that, adding features
and releasing updated Python versions became popular. Python 1.0 introduced map, filter,
and reduce methods in 1994 to process lists. Unicode support and a shorter list loop were
added to Python 2.0 on October 16, 2000. Python 3.0 debuted December 3, 2008. It added
print and number division support and error handling.
Python's new features benefit developers and boost performance. Python has grown in
popularity and is a challenging programming language. It's in demand in machine learning,
AI, data analysis, web development, and more, offering high-paying jobs. Python became the
major programming language for many programmers and developers worldwide.
Advantages Disadvantages
1. Easy to learn, read, and understand. 1. Restrictions in design
2. Versatile and open source 2. Memory inefficient
3. Improves productivity. 3. Weak mobile computing
4. Supports libraries. 4. Runtime errors
5. Huge library 5. Slow execution speed
6. Strong community
7. Interpreted language.
Centre for Distance Education 1.7 Acharya Nagarjuna University
➢ Facebook
➢ Instagram
➢ Spotify
➢ Reddit
➢ Uber
➢ Netflix
➢ Google
➢ Dropbox
• Web Development
Python's simplicity and features make it popular for web development. Python frameworks
allow them to build user-friendly dynamic websites. The frameworks include Django for
backend development and Flask for frontend. Because Python is easy to deploy, scalable,
and efficient, most online companies utilize it as their primary technology. Top Python
applications include web development, which is used across the business to build effective
websites.
Programming and Problem-Solving … 1.8 Introduction
• Data Science
Python snippets help data scientists develop effective AI models. Its simplicity lets
developers design complicated algorithms. Data science creates models and neural
networks that learn like human brains but are faster. It helps organizations make decisions
by extracting patterns from prior data. This field helps organizations invest in the future.
Data analysis and machine learning specialists can use Pandas and TensorFlow for
statistical analysis, data manipulation, etc. One of the most popular programming languages
is Python. The language of AI and ML is Python. Python has helped this field with its many
libraries and community support. Python use will rise as artificial intelligence and machine
learning evolve significantly.
• Game Development
Python developers can use Pygame to create 2D and 3D games. Pirates of the Caribbean,
Battlefield 2, and others are popular Python games. Pygame is a Python library for making
fun games. Since the gaming industry is growing, these types of development have become
more popular. This package makes game development easy, so you can try building some
simple games.
There are several characteristics that distinguish the Python programming language from
others the main reason is its features and described below and shown in Figure 1.4.
❖ Popularity
Python is the fourth most popular and fastest-growing programming language, according to
the Stack Overflow Developer Survey 2022. Businesses including Google, Instagram,
Netflix, and Spotify use it.
❖ Interpretation
Python is an interpreted language; unlike compilers, which need the creation of machine code
from the source code before it can be executed, Python passes directly to the interpreter,
simplifying and speeding up the execution process.
Centre for Distance Education 1.9 Acharya Nagarjuna University
❖ Open Source
The fact that Python is a free language created under an open-source license certified by OSI
is among its strongest features.
❖ Portability
Major trouble comes in transferring a code from one platform to another without making
blunders in the command. Python programming language, being a portable code can easily be
transferred without making any errors.
❖ Simplicity
The only programming language that is similar to English is Python. It's so simple to read and
comprehend. The Python programming language utilizes fewer keywords than C++ or Java.
As a result, developers everywhere now favor the Python language above all others.
❖ A high-level language
❖ An object-oriented language
Python is a programming language that supports a variety of programming styles, including
structured and functional programming, in addition to the standard object-oriented
programming paradigm.
Programming and Problem-Solving … 1.10 Introduction
Python programmers need to be familiar with all possible script and code execution
scenarios. There is no other way to confirm that the code is functioning as intended. The
Python programs are executed by the Python interpreter. A Python interpreter is a software
that functions as a bridge between computer hardware and Python programs.
Here, we'll go over the various methods for executing Python programs. The simple program
is created using notepad is shown in Figure 1.5.
The Python print statement is written and saved in the working directory as
[Link]. We are going to use the command line to execute this file now.
To run a Python script, open a command line. To run the file, we must input the file name and
then Python. Once you press the enter key, the result will look like this if there are no errors
in the file and is shown in Figure 1.6.
We can utilize the Python interactive session to write and execute the Python code. To launch
an interactive Python session, simply select a command-line or terminal from the Start menu,
type python, and hit the Enter key. It is a fantastic development tool because it enables us to
review every line of code. However, all of our written code will be lost when the session
ends. To exit the interactive shell, type quit(), exit(), or press the Ctrl+Z key.
This is an illustration of how to use an interactive shell to run Python code is shown in Figure
1.7.
Step 1: Launch the Python IDLE first. Since IDLE operates in the shell by default, this
window will appear on your screen.
Step 2: Using the IDLE, we can create and run Python scripts and see the results directly on
the screen, and is shown in Figure 1.8.
Step 3: Open a new file by selecting File → New File in order to run a whole Python
program on IDLE.
Step 4: Write your Python program in the "New File" that appears when the previous step is
completed shown in Figure 3.8.
Step5: Save your file in this step. It is saved here under the filename [Link].
Step 6: Click RUN → Run Module to start the process shown in Figure 3.9.
You can run Python applications with ease by following the instructions in the description
above, which include utilizing text editors, IDEs, or the command line. You can become
more adept at executing Python code and utilizing its features to take on a variety of tasks
and challenges with practice and experimentation.
Fig 1.9. Create and Save Python Scripts in new file of IDE.
One of the most important skills for anyone studying or using Python is the ability to run
programs. Knowing how to run Python code is essential, regardless of your level of
experience—whether you're a novice learning the fundamentals of the language or an expert
in creating complex apps.
1.5. SUMMARY
Computational problem solving is the process of using logical and systematic methods to
design algorithms that can be executed by a computer to achieve a desired outcome. It
involves understanding the problem, developing a step-by-step solution (algorithm), and
implementing it using a programming language. Python, a versatile and beginner-friendly
language, is widely used for this purpose because of its simple syntax, readability, and
powerful libraries. It enables programmers to focus more on problem logic rather than
complex syntax, making it ideal for tasks such as data analysis, automation, web
development, artificial intelligence, and scientific computing.
1.6 TECHNICAL TERMS
• Computational Problem
• Python
• Command Line
• IDE
• Programming
Essay questions:
Short Notes:
The primary goal of this chapter is to understand the Python data types. The chapter began
with an understanding of Expressions, Variables and Assignments, Strings, List, Objects and
Classes, Python Standard Library and so on. After completing this chapter, the student will
understand the python data types in detail with suitable examples.
STRUCTURE
2.1 Introduction
2.2 Python Data Types
2.2.1 Expressions, Variables, and Assignments in Python
2.3 String in Python
2.4 List in Python
2.5 Object and Class in Python
2.6 The Python Standard Library
2.7 Summary
2.8 Technical Terms
2.9 Self-Assessment Questions
2.10 Suggested Readings
2.1. INTRODUCTION
Python is a high-level computer language that is interpreted and object-oriented. Its semantics
change over time. Its high-level built-in data structures, along with dynamic typing and
dynamic binding, make it a great choice for Rapid Application Development. Python's
grammar is simple and easy to learn. It focuses on readability, which lowers the cost of
maintaining programs.
Python lets you use modules and packages, which makes it easier to break up programs into
smaller pieces and reuse code. For all major systems, you can get the Python interpreter and the
large standard library for free in source or binary form, and you can share them with anyone
else.
This chapter will cover the major basic concept of python programming including what is
python, history of python, advantages and disadvantages of python, applications of python etc.
Programming and Problem-Solving … 2.2 Python Data Types
In Python, data types define the kind of value a variable can hold and determine what
operations can be performed on that value. They form the foundation of any Python program,
allowing developers to store, manipulate, and process data efficiently. Python provides
several built-in data types such as numbers, strings, lists, tuples, sets, and dictionaries, each
designed for specific purposes. These data types make Python both flexible and powerful,
enabling programmers to handle a wide range of computational tasks — from simple
arithmetic to complex data processing — with ease and clarity.
Numbers: Based on their names, these are the types of data that store numbers: integer,
float, and complex. It can be either an int or a long int.
Example:
A = 20 # Assing 20 to A
Output:
20
4.65
Strings : These are in Python are groups of characters that are kept in memory together, like
an array of characters. Either a single quote or two double quotes are used to show these
characters.
Example:
Output:
Happy
H
Happy Morning
❖ Python List
In Python, a list is a sorted list of things separated by commas (,) and enclosed in square
brackets ([]). If you access a Python list using the slicing operator [], you can change the
value of any item in it. A list in Python is like a collection. The main difference is that an
array is a collection of items that are all of the same type, while a list is a collection of items
that can be of different kinds. The Python list can be changed.
Example:
Output:
The code above shows that Person_List has items that are numbers, floats, strings, and long
ints. The result shows that the whole Person_List was shown first.
❖ Python Tuple
Python tuples are the same as Python lists. The only difference is that Python tuples are
immutable, which means that you can access the things in them but not change their values.
Besides being able to change, another big difference between tuples and lists is that lists are
defined inside square braces [], while tuples are defined inside parentheses ().
Programming and Problem-Solving … 2.4 Python Data Types
Example:
Output:
The code above shows that the items in Person_Tuple are integers, floats, strings, long
integers, and strings. The result shows the full Person_Tuple as the first item. After that The
first and fourth items were printed.
But at the end of the last line, an error is made because the fourth member of the tuple is
being changed. Based on the finding, we can say that tuple items can't be changed, but List
data types can.
Python Dictionary
A sorted list of key-value pairs is called a dictionary in Python. The dictionary's entries are
key-value pairs separated by commas. The value can always be retrieved if we know the key,
but the opposite is not true. Python dictionaries are therefore designed for data retrieval.
Python dictionaries are defined inside curly braces ({}), and the slicing operator ([ ]) is used
to access and assign values.
Centre for Distance Education 2.5 Acharya Nagarjuna University
Example:
Output:
e have created a dictionary called week in the example above. In this case, the keys are
Monday, Tuesday, Wednesday, and Thursday, and the values are Monday, Tuesday,
Wednesday, and Thursday. To get the appropriate value, we employ keys. not the other way
around, though. Here, we've used the week dictionary's keys to obtain the data.
Capital_city['Thursday'] retrieves its corresponding value, Thu, since 'Thursday' is the key.
But since 'Thu' is the value assigned to the 'Thursday' key, capital_city['Thu'] raises an error.
A set is an arbitrary grouping of distinct objects. Values inside braces {} and separated by
commas define a set.
Programming and Problem-Solving … 2.6 Python Data Types
Example:
Output:
Here, four integer values have been added to a set called student_id. As sets are collections
that are not ordered, indexing is meaningless. The entire set is shown first. Afterwards, trying
to access the element of the set using the slicing operator [] does not work. Similar to the
output accessing the third item with the error message generated by the index.
Boolean: The datatype which returns only 2 values either TURE or FALSE.
Example:
A = 50 ;
Output:
>>> A = = 40
>>> FALSE
In Python, expressions are combinations of values and operators that evaluate to a value.
They form the basic building blocks of any Python program, allowing for operations such as
arithmetic calculations, string manipulations, and logical comparisons. Variables are used to
store these values, acting as named references to data that can be easily accessed and
manipulated throughout a program.
Centre for Distance Education 2.7 Acharya Nagarjuna University
• Expressions
In Python, expressions are combinations of values, variables, operators, and function calls
that are evaluated to produce a new value. They can perform a variety of operations,
including arithmetic calculations, string manipulations, and logical comparisons. Expressions
are fundamental components of a Python program.
# Examples of expressions
a = 5 + 3 # Arithmetic expression
b = "Hello" + " " + "World" # String concatenation expression
c = 10 > 5 # Comparison expression
• Variables
Variables in Python are symbolic names that reference or point to objects or values stored in
memory. They are used to store data that can be modified and accessed throughout a
program. Python uses dynamic typing, which means that you do not need to declare the type
of a variable explicitly; the type is inferred from the value assigned to it.
# Examples of variables
x = 10 # Integer variable
y = 3.14 # Float variable
name = "Alice" # String variable
• Assignments
Assignment statements are used to assign values to variables. The assignment operator = is
used to perform assignments. The variable on the left side of the = operator is assigned the
value on the right side.
# Examples of assignments
x = 5 # Assigning an integer value to variable x
y = x + 2 # Assigning the result of an expression to variable y
message = "Hello, World!" # Assigning a string value to variable message
• Python Operators
Operators are unique symbols or keywords in Python that perform operations on values and
variables. They form the foundation of expressions, which are used to work with data and
carry out calculations. Python has a number of operators, each having a distinct function. The
Python programming language supports the following types of operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
Example:
Output:
Once the two variables "x" and "y" are defined, this code does a number of mathematical
operations, including floor division, modulus, addition, subtraction, multiplication, and
division, and reports the results.
Python comparison operators are required in order to compare two [Link] produce a
Boolean value (True or False) based on the comparison. The comparison operators in python
is shown in Table 2.3.
Centre for Distance Education 2.9 Acharya Nagarjuna University
Example:
Output:
To assign values to Python, utilize the assignment operators. The simplest assignment
operator is the single equal symbol (=). The variable on the operator's left side is given the
value on the operator's right side. The different approaches to use assignment operator in
python is shown in Table 2.4.
Programming and Problem-Solving … 2.10 Python Data Types
x=x+5
x= 2 * x + 4 * 5 + 8
Example:
Output:
Above displays the assignment operators in Python. First, 'x' and 'y' have values of 20 and 10,
respectively. Afterwards, x=25 is the output of applying expression x+5 to x.
• Python Bitwise Operators : Bitwise operators in Python carry out actions on discrete
binary integer [Link] operate on each bit location logically while working with integer
binary [Link] bitwise operations, including AND (&), OR (|), NOT (),
XOR (), left shift (), and right shift (>>), are included in Python.
Centre for Distance Education 2.11 Acharya Nagarjuna University
In Python, you often use expressions, variables, and assignments together to perform
various operations and store results. This combination is essential for creating dynamic
and interactive programs.
a = 10
b = 20
print(sum_result) # Output: 30
greeting = "Hello"
name = "Bob"
Expressions, variables, and assignments are the core concepts of programming in Python.
Expressions allow you to perform operations and produce values. Variables provide a way to
store and reference these values. Assignments enable you to set and update the values of
variables. Understanding how to use these elements effectively is fundamental to writing
Python programs.
Programming and Problem-Solving … 2.12 Python Data Types
Python Keywords
Each language has words and rules that make sense when put together in a sentence. Also,
the computer language Python has a set of predefined words that are called Keywords. You
can't use these words anywhere else in Python because they have special meanings.
Keywords set the rules for how the code is written. That word can't be used as a variable,
function, or symbol name. The only words in Python that are written in capital letters are
True and False. Python 3.11 has 35 keywords and are’shown in Figure 2.2.
In Python, strings are sequences of characters enclosed in either single quotes (' ') or double
quotes (" "). They are immutable, meaning once a string is created, it cannot be changed.
Python provides a variety of built-in methods for string manipulation, such as len() to get the
length of a string, lower() and upper() to change the case, and split() to divide a string into a
list of substrings. Strings support indexing and slicing, allowing access to individual
Centre for Distance Education 2.13 Acharya Nagarjuna University
characters or segments of the string. Concatenation of strings can be done using the +
operator, and the in keyword is used to check for the presence of a substring within a
[Link] also supports triple quotes (''' ''' or """ """) for multi-line strings.
Key Points
1. Creation: Strings can be created using single quotes, double quotes, or triple quotes
for multi-line strings.
2. Concatenation: Strings can be concatenated using the + operator or various string
formatting methods such as f-strings, format(), and %-formatting.
3. Accessing Characters: Individual characters in a string can be accessed using
indexing, and substrings can be extracted using slicing.
4. Common Methods: Python provides a rich set of methods for string manipulation,
including:
o upper(), lower(): Convert to uppercase or lowercase.
o startswith(), endswith(): Check if a string starts or ends with a given substring.
o find(): Locate the position of a substring.
o replace(): Replace occurrences of a substring with another substring.
o split(): Split a string into a list of substrings.
o join(): Join a list of strings into a single string.
5. String Formatting: Formatting strings can be done using f-strings (for Python 3.6+),
the format() method, and %-formatting.
Example :
# String creation
greeting = "Hello"
name = "Alice"
# String methods
upper_greeting = full_greeting.upper()
# Slicing
first_word = full_greeting[:5]
lists in Python are dynamic, versatile, and powerful data structures that allow you to store and
manipulate an ordered collection of items. Understanding how to create, access, modify, and
manipulate lists is fundamental for effective programming in Python. Here's a summary of
the key points:
Key Points
Creation: Lists can be created using square brackets [] and can store elements of different
data types.
Accessing Elements: You can access elements using indexing and slicing.
first_element = my_list[0] # 1
Modifying Lists: Lists are mutable, so you can change their content.
my_list[0] = 10
my_list.append('cherry')
my_list.insert(2, 'orange')
my_list.remove('banana')
popped_element = my_list.pop()
del my_list[1]
List Operations: Lists support several operations such as concatenation, repetition, and
membership testing.
repeated_list = my_list * 2
Centre for Distance Education 2.15 Acharya Nagarjuna University
my_list.sort()
my_list.reverse()
index_of_apple = my_list.index('apple')
count_of_10 = my_list.count(10)
Iterating Over Lists: You can iterate over the elements of a list using loops.
print(item)
# List creation
# Accessing elements
# Modifying lists
fruits[1] = 'blueberry'
[Link]('date')
[Link](1, 'avocado')
# Removing elements
[Link]('cherry')
del fruits[0]
Programming and Problem-Solving … 2.16 Python Data Types
# List operations
doubled_fruits = fruits * 2
# List methods
all_fruits.sort()
all_fruits.reverse()
index_of_fig = all_fruits.index('fig')
count_of_avocado = all_fruits.count('avocado')
print(fruit)
# List comprehensions
By mastering these list operations and methods, you can efficiently manage collections of
data in Python, enhancing your programming capabilities. If you have any specific questions
or need further assistance, feel free to ask!
Classes
A class is a blueprint for creating objects. It defines a set of attributes and methods that the
created objects will have.
Defining a Class
class Dog:
# Class attribute
Centre for Distance Education 2.17 Acharya Nagarjuna University
[Link] = name
[Link] = age
# Instance method
def description(self):
Objects
An object is an instance of a class. It has the attributes and methods defined in the class.
Creating an Object
my_dog = Dog("Buddy", 3)
print(my_dog.age) # Output: 3
Example
Here's a summary example that includes class definition, object creation, and method
invocation:
class Dog:
[Link] = name
[Link] = age
def description(self):
my_dog = Dog("Buddy", 3)
Understanding these concepts will enable you to leverage the power of object-oriented
programming in Python, making your code more modular, reusable, and easier to maintain. If
you have any specific questions or need further details, feel free to ask!
The Python Standard Library is a collection of modules and packages that come with Python,
providing a wide range of functionality for various tasks such as file I/O, system operations,
data manipulation, and networking. Here is a brief overview of some key modules and their
uses:
Key Modules:
sys: Provides access to some variables used or maintained by the interpreter and to functions
that interact strongly with the interpreter.
import sys
print([Link]) # Output the Python version
[Link]() # Exit the program
os: Provides a way to use operating system-dependent functionality like reading or writing to
the file system.
import os
Centre for Distance Education 2.19 Acharya Nagarjuna University
import math
print([Link](16)) # Output: 4.0
print([Link]) # Output: 3.141592653589793
import random
print([Link](1, 10)) # Output a random integer between 1 and 10
The Python Standard Library provides tools and utilities for many common programming
tasks, enabling developers to write efficient and effective code without needing to install
external libraries. If you have any specific questions or need further details, feel free to ask!
2.7 SUMMARY
Python supports a wide range of data types and programming constructs that make it both
powerful and easy to use. Expressions in Python combine values, variables, and operators to
produce new results, while variables are used to store and reference data dynamically without
explicit type declarations. Strings represent sequences of characters and support numerous
operations such as concatenation, slicing, and formatting. Lists allow storage of ordered
collections of items that can be easily modified, whereas objects and classes provide the
foundation for object-oriented programming, enabling modular and reusable code through
encapsulation and inheritance. The Python Standard Library further enhances the language by
offering a vast collection of built-in modules and functions for tasks like file handling, math
operations, data manipulation, and system interaction — making Python a comprehensive
and efficient language for solving computational problems.
• Expressions
• Operators
• Operands
• Evaluation
• Variables
• Objects
• Classes
Programming and Problem-Solving … 2.20 Python Data Types
Essay Questions:
1. Explain the concept of expressions, variables, and assignments in Python with suitable
examples.
2. Illustrate the various data types in Python and describe their key characteristics.
3. Describe the string data type in Python and discuss common string operations and
methods.
4. Explain lists in Python, highlighting their features, indexing, and common list operations.
5. Discuss the concepts of objects and classes in Python and explain how object-oriented
principles are implemented.
6. Write a detailed note on the Python Standard Library and its importance in program
development.
Short Notes:
The primary goal of this chapter is to introduce the concept of imperative programming and
its implementation in Python. Students will learn about program structure, control flow,
variable assignments, functions, and parameter passing mechanisms.
After completing this chapter, students will be able to write, execute, and manage Python
programs effectively using imperative programming concepts.
STRUCTURE
3.1 Introduction
3.2 Imperative Programming Concepts
3.3 Python Programs
3.4 Execution Control Structures
3.5 User-Defined Functions
3.6 Python Variables and Assignments
3.7 Parameter Passing
3.8 Summary
3.9 Technical Terms
3.10 Self-Assessment Questions
3.11 Suggested Readings
3.1 INTRODUCTION
Imperative programming is one of the most common programming paradigms that focuses on
describing how a program operates.
It uses statements that change a program's state, executing instructions step by step.
Python, being a multi-paradigm language, supports imperative programming efficiently.
This approach helps programmers control the flow of execution using variables, functions, and
control structures such as conditionals and loops.
Imperative programming is based on commands that change the state of the program.
The program is a sequence of statements that tell the computer what to do, one after another.
Examples of imperative languages include C, Java, and Python.
Characteristics of Imperative Programming:
Example:
x = 10
y = 20
sum = x + y
print('Sum:', sum)
Output:
Sum: 30
if STATEMENT
The if statement tests a condition; if True, its indented block executes.
Syntax
if condition:
statement_block
Example
score = 90
Centre for Distance Education 3.3 Acharya Nagarjuna University
if–else STATEMENT
Used when two mutually exclusive paths exist.
Syntax
if condition:
block_true
else:
block_false
Example
num = int(input("Enter a number: "))
Programming and Problem-Solving … 3.4 Imprative Programming
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Flow Description:
If condition fails, the else block executes.
Practice
Write a program that accepts a temperature in
if–elif–else STATEMENT
When multiple conditions must be checked in order, Python uses elif.
if condition1:
...
elif condition2:
...
else:
...
Example -Grade Evaluation
marks = int(input("Enter marks: "))
if marks >= 75:
print("Distinction")
elif marks >= 60:
print("First Class")
elif marks >= 40:
print("Pass")
else:
print("Fail")
Output
Enter marks: 82
First Class
Practice Task
Modify the program to print “Outstanding” for marks ≥ 90.
For Loop Statement
It is possible to iterate over a series of elements in Python by using the for loop, which is one
of the looping instructions contained inside the language. There are a variety of objects that
can be iterated, including a list, a tuple, a text, and any other object.
Centre for Distance Education 3.5 Acharya Nagarjuna University
Syntax:
for variable in sequence:
# Code block to be executed
The preceding syntax,
• variable is a temporary variable that stores the value of each element in the sequence
during each iteration of the loop
• The code block that comes after the for statement is carried out many times for each
individual element that is included in the sequence.
Example:
for i in 10:
# Code block to be executed
Total 10 time block will be repeated
The flowchart to represent for loop statement in python is shown in Figure 5.2
Example :
Programming and Problem-Solving … 3.6 Imprative Programming
The code that you see above has a for loop that prints each element of the 'list' list on a new
line after iterating over each entry in the list. The output is shown on the next page.
Output:
Example 2:
Output:
Using the code that was just presented, the for loop will iterate over each element in the tuple
that is referred to as 'num' and then display it on a new line. In addition, the sum of each
Centre for Distance Education 3.7 Acharya Nagarjuna University
number was computed, the result was saved in the "sum_nums" variable, and the sum value
was eventually printed out. In the run tuple, a sequence of distinct integers (5,8,7,2) is used,
and the result is "the sum of the numbers is 22"
According to Python, a range object is a sequence of numbers that cannot be changed. When
using a for loop, it is helpful to keep track of the number of times a block is repeated.
Every one of the three arguments must be an integer. The value of the [start] parameter is
always set to zero, unless an alternative number is provided. The only parameter that is
required for the function described above is stop. It is one less than the stop parameter that
the last integer in the series is. In the intervals between, the [step] value, which is set to 1 by
default, is used to increment the numbers.
Example:
The range() method was used instead of a for loop statement in the Python code above. Three
for loop statements in all, each printing a distinct range of numbers according on the inputs
passed to the range () function.
When the first "10" value was entered into range (10) it produced numbers starting at 0 and
ending with 10-1, or 9. A for-loop statement is then given range(1,5), and values are printed
starting at 1 and ending at end 5-1, or 4. Lastly, range(10,50,5) is sent to the for-loop
expression, which outputs values starting at 10 and ending at 50-4, or 45, because step=5.
Programming and Problem-Solving … 3.8 Imprative Programming
Output:
Another Python looping expression used to repeat a block of code until a predetermined
condition is met is the while loop.
Syntax:
while condition:
The flowchart to represent while loop statement in python is shown in Figure 5.3
Centre for Distance Education 3.9 Acharya Nagarjuna University
Example:
Output:
Programming and Problem-Solving … 3.10 Imprative Programming
The code block is repeated here by the while loop until the sum variable is less than 5. As we
can see in the output, the sum variable is increased by 1 at each iteration, and the current
value of the sum is printed on a new line.
A loop inside another loop is known as a nested loop in Python. When we wish to loop over a
series of components with several degrees of nesting, we utilize it.
Syntax:
Variable, as used in this syntax, is a temporary variable that, for each iteration of the outer
loop, stores the value of each element in the sequence. Every time the inner loop iterates, the
value of every element in the i_sequence is stored in the i_variable, a temporary variable.
Every element in the inner sequence and every element in the outer sequence is subjected to
several executions of the code block that follows the inner for statement.
Example :
Output:
In this example, the nested loop performs an iteration over each item in the ‘matrix' list and
then prints the elements on a new line.
When one while loop is contained within another while loop, the resulting structure is
referred to as a nested while loop. We require nested loops in most of our apps.
Example:
Programming and Problem-Solving … 3.12 Imprative Programming
Output:
In this example, the nested loop performs an iteration over each item in the ‘matrix' list and
then prints the elements on a new line.
Break Statement
A premature termination of the loop in Python can be accomplished with the help of the
break statement. It is utilized in situations in which we wish to exit the loop prior to it having
finished all of its iterations.
Syntax:
The syntax of the break statement in Python is as follows:
for variable in sequence:
if condition:
break
• The value of each element in the sequence is stored in the variable, which is a
temporary variable, and it is used for each iteration of the loop to save the value.
• The condition is a statement that receives a boolean value and is evaluated at the
beginning of each iteration of the loop. If the condition is found to be true, the break
statement is carried out, therefore bringing an end to the loop.
Centre for Distance Education 3.13 Acharya Nagarjuna University
Example:
The code that you see above has a for loop that outputs each item in the "fruits" list on a new
line after iterating over each item in the list. On the other hand, the break statement is
executed, and the loop is halted when the value of the "fruit" variable is equal to "banana."
Output:
Continue Statement
Using the continue statement in Python, one can skip the iteration of the loop that is currently
being executed. It is utilized in situations in which we wish to skip a certain component of the
sequence and proceed with the subsequent iteration of the loop onward.
Syntax:
for variable in sequence:
if condition:
continue
# Code block to be executed
Programming and Problem-Solving … 3.14 Imprative Programming
• The value of each element in the sequence is stored in the variable, which is a
temporary variable, and it is used for each iteration of the loop to save the value.
• The condition is a statement that receives a boolean value and is evaluated at the
beginning of each iteration of the loop.
Example
Output:
The for loop iterates through each item in the "fruits" list in this example, printing each one
on a new line. Nevertheless, the loop's current iteration is skipped and the continue statement
is executed when the value of the "fruit" variable equals "banana."
Centre for Distance Education 3.15 Acharya Nagarjuna University
Pass Statement
The pass statement is used as a placeholder in Python. It is used when we want to write
empty code blocks and want to come back and fill them in later. The syntax of the pass
statement in Python is given below.
Syntax:
for variable in sequence:
pass
• Every time the loop iterates, the variable—which is a temporary variable—holds the
value of every element in the sequence.
• An empty code block is created using the pass statement and is subsequently filled in.
Example:
In this example, the pass statement is used to create an empty code block while the for loop
iterates over each element in the "fruits" list.
Programming and Problem-Solving … 3.16 Imprative Programming
Syntax:
def function_name(parameters):
# function body
return value
Example:
def greet(name):
print('Hello', name)
greet('Lavanya')
Output:
Hello Lavanya
Built-in Functions
Python's built-in functions are already defined. A user must remember the name and
parameters of a certain function. There is no need to redefine these functions because they
have already been [Link] of the widely used built-in functions are given below and
shown in Table 10.1:
Function Description
pow() Returns the power of two numbers
abs() Returns the absolute value of a number
max() Returns the largest item in a python iterable
min() Returns the largest item in a python iterable
sum() Sum() in Python returns the sum of all the items in an iterator
type() The type() in Python returns the type of a python object
Sqrt() Executes the python built-in to find sqrt of the given number
The following two example python codes shown in below demonstrate the usage of built-in
functions to fulfil the specific task. In the first example python code imported math module
Centre for Distance Education 3.17 Acharya Nagarjuna University
and later performed the two functions pow () and sqrt() operations. The result of each
function is produced on the output.
Example
Output
Similarly, the second example also imported math module and perform the abs (), max () and
min () operations respectively. The absolute function took the -25 is a negative number and
produced the output as 25. The maximum of 5 and 9 is determined by max () and minimum is
returned by min () function.
Example
Programming and Problem-Solving … 3.18 Imprative Programming
Output:
Variables are used to store data values. In Python, variables are created automatically when a
value is assigned. Python is dynamically typed, so there is no need to declare variable types
explicitly.
x=5
y = 2.5
name = 'Python'
print(x, y, name)
Python supports several ways to pass parameters to functions: positional, keyword, default,
and variable-length arguments.
Example:
def add(a, b=10):
return a + b
print(add(5))
print(add(5, 15))
Output:
15
20
3.8 SUMMARY
• Imperative Programming
• Control Structure
• Function
• Variable
• Parameter Passing
• Sequential Execution
Short Notes:
STRING
AIMS AND OBJECTIVES
The primary goal of this chapter is to grasp the concept of string in Python programming. The
chapter began with an understanding of basic definition of string, creating a string, and so on.
After completing this chapter, the student will understand how to work with string in python
in terms various methods, operations, and functions.
STRUCTURE
4.1 Introduction
4.2 Python String
4.2.1 Creating a Python String
4.2.2 Applications of Python String
4.3 Accessing the String
4.3.1 Indexing
4.3.2 Negative Indexing
4.3.3 Slicing
4.4 Python String Operations
4.4.1 Concatenation Operator
4.4.2 Repetition Operator
4.4.3 Membership Operator
4.4.4 Comparison Operator
4.5 Python String Methods
4.5.1 len()
4.5.2 upper()
4.5.3 replace()
4.5.4 find()
4.6. Formatted Output
4.7 Summary
4.8 Technical Terms
4.9 Self-Assessment Questions
4.10 Suggested Readings
Programming and Problem-Solving … 4.2 String
4.1. INTRODUCTION
Python strings, like those in many other well-known programming languages, are arrays of
bytes that represent unicode characters. Nevertheless, a single character in Python is just a
string with a length of 1. Python does not have a character data type. You can access the string's
constituents by using square brackets.
Since it is an immutable data type, you are unable to alter a string after you have created it.
Strings are extensively utilized in a wide range of applications, including the storing and
manipulation of text data as well as the representation of names, addresses, and other text-
representable data types. This chapter will cover Python strings, one of the core data types in
Python programming, and will cover Python string methods, operators and functions,
working with them, and more.
A string is a sequence of alphabets, words, or other characters. It is one of the most basic data
structures, serving as the foundation for data manipulation. Python includes a built-in string
class called str. Python strings are "immutable," which implies they cannot be modified once
formed.
Output:
The above example, where three strings are created namely S1,S2 and S3 in different styles
with same content. Finally displayed the three strings output is shown above.
• Strings can be utilized for encoding and decoding purposes, ensuring the secure
movement of data from source to destination.
• We are able to offer better filters for the approximate suffix-prefix overlap problem by
utilizing strings and the techniques associated with them.
• HTTP requests and responses, among other data exchanged over networks, are encoded
and decoded using strings.
• When working with files, you'll need to know that strings are the go-to for reading and
writing file names and locations.
• Applications like sentiment analysis and natural language processing make use of strings
to glean useful insights from massive text datasets.
• Indexing
• Negative Indexing
• Slicing
Programming and Problem-Solving … 4.4 String
4.3.1 Indexing
Using index values and treating strings like a list is one method. In Python, the Indexing
function can be used to retrieve specific characters from a String. The idea of indexing
technique is shown in Figure 4.1
Output:
Centre for Distance Education 4.5 Acharya Nagarjuna University
The above example illustrate the concept of indexing method, where one strings S1 is
created with the content of “GOOD MORNING” and then accessed character at index 1 and
5. Finally displayed the extracted characters output is shown above.
Python's string language permits negative indexing, just as that of a list. Negative address
references, such as -1 for the final character, -2 for the second last character, and so forth, can
access characters from the back of the String thanks to indexing. The idea of negative
indexing is shown in Figure 6.1.
Example:
Output:
Programming and Problem-Solving … 4.6 String
The above example illustrate the concept of negative indexing method, where one strings S1
is created with the content of “GOOD MORNING” and then accessed character at index-6
and -12. Finally displayed the extracted characters output is shown above.
4.3.3. Slicing
The String Slicing function in Python can be used to retrieve a range of characters from the
String. To slice something in a string, use a slicing operator, such as a colon (:). When
utilizing this method, bear in mind that the character at the start index is included in the
string that is returned, but the character at the last index is not.
Example:
Output:
The above example illustrate the concept of slicing method, where one strings S1 is created
with the content of “GOOD MORNING” and then accessed character with range of [3-7]
and [5-13] . Finally displayed the extracted sub string output is shown above.
Centre for Distance Education 4.7 Acharya Nagarjuna University
Python's basic string operations include doing simple arithmetic operations, verifying the
character of an existing substring, repeating a string, and much more are shown in Table 6.1.
Example:
Output:
Strings are sequences that cannot be changed, as we previously stated. Concatenating the two
strings in the previous example doesn't change either string. Rather, the process generates a
new string called "S3" from the two strings "S1" and "S2." This operator is frequently used
by beginners to add spaces between strings. This space is a string as well, but it's empty this
time.
Centre for Distance Education 4.9 Acharya Nagarjuna University
Example:
Output:
operator (*). Take for example that we have a string S and an integer N. Doing S times N or
N times S will result in S being repeated N times. The idea is shown in Figure 6.4.
Output:
Centre for Distance Education 4.11 Acharya Nagarjuna University
Notice the last two print functions in the preceding example. Both actually output empty
strings. The last but one step seems sense because it creates zero copies of the string, but the
last operation appears strange. However, multiplying a string by a negative number yields an
empty string.
Example:
Output:
Programming and Problem-Solving … 4.12 String
It is important to keep in mind that the membership operators are also capable of working
with substrings; that is, they can determine whether or not a substring is present in a string.
Example:
Output:
Example:
Their names also indicate that they are used for this purpose. However, because they return a
boolean, they are most utilized in conditional expressions to determine whether or not two
strings are identical. A True value is returned by the == operator when the two strings in
question are identical, whereas a False value is returned when the strings in question are not
identical.
Output
Programming and Problem-Solving … 4.14 String
Example:
Output:
As shown in the preceding examples, make a comparison between the first string, the second
string, and the third string. Along the same lines, second with fourth. != is the operator that
returns. True when the two strings are equal otherwise return false.
4.5.1 len()
It is possible to utilize the `len()` function in order to determine the length of a string. A count
of the characters contained in the string is returned by it.
Example:
length = len(String_new)
print(String_new)
Output
18
The total number of characters includes space returned by the len() function i.e. 13
4.5.2 upper()
The string that is returned by the upper() method is one in which all of the characters are
capitalized.
Example:
String_new = String_new.upper()
print(String_new)
Output :
WELCOME TO PYTHON!
The upper() is called along with string object String_new.upper and it returns a string where
all characters are in upper case.
4.5.3 replace()
Using the replace() method, a phrase that is supplied is replaced with another term that is also
specified.
Example:
print(String_new)
Programming and Problem-Solving … 4.16 String
Output:
Welcome to PYTHON!
The reverse r() is called along with old and new string and it replaces an old string
“Python” with new string “ PYHON”
4.5.4. find()
Using the find() method, one can locate the initial instance of the value that has been
supplied. However, if the value cannot be located, this procedure will return -1. This method
is essentially identical to the index() method; the only difference is that the index() method
throws an exception if the value is not found. In addition, this method is almost identical to
the index() method.
Example:
String_new = String_new.find(“Python”)
print(String_new)
Output:
11
4.6 FORMATTED OUTPUT
The output of a program often needs to be organized so that users can easily read and
interpret the results.
Python’s print() function provides several ways to produce formatted output. It can display
variables with separators, new lines, or in customized layouts.
n=5
r=5/3
name = 'Ida'
print(n, r, name)
print(n, r, name, sep=';')
Centre for Distance Education 4.17 Acharya Nagarjuna University
5 1.66666666667 Ida
5;1.66666666667;Ida
5
1.66666666667
Ida
Formatted Output with the format() Method
Python’s [Link]() function allows inserting variables into a string at specific placeholders
{}.
Example1:
weekday = 'Wednesday'
month = 'March'
day = 10
year = 2010
hour = 11
minute = 45
second = 33
print('{}, {} {}, {} at {}:{}:{}'.format(weekday, month, day, year, hour, minute, second))
Output
Wednesday, March 10, 2010 at 11:45:33
Explanation
In the statement above:
Each pair of curly braces {} is a placeholder for a variable supplied to the format()
[Link] replaces them in the same order they appear inside the parentheses.
Example2:
Programming and Problem-Solving … 4.18 String
Python code:
Output:
4.7 SUMMARY
Strings are an essential data type in Python, and they are utilized widely for activities that
involve working with textual data. In this chapter, we covered the fundamentals of creating
and manipulating strings, as well as accessing characters, string slicing, concatenation, string
length, and the different string methods that are available in Python. Your ability to work
effectively with strings in your Python programs and to handle text-based data in an efficient
manner will be directly correlated to your level of comprehension of these ideas.
Essay questions:
Short Notes:
FILES
AIMS AND OBJECTIVES
The goal of this chapter is to explain how Python programs interact with files stored in a
computer’s file system.
Students will learn how to open, read, write, and close files, as well as explore the most
common patterns used to process textual data.
STRUCTURE
5.1 Introduction
5.2 Understanding the File System
5.3 Opening and Closing a File
5.4 Patterns for Reading a Text File
5.4.1 Reading the Entire File
5.4.2 Reading Line by Line
5.4.3 Using readline() and readlines()
5.4.4 Using the with Statement
5.5 Writing to a Text File
5.5.1 Writing Strings and Data
5.5.2 Appending to a File
5.5.3 Writing Lists and Formatted Data
5.6 Practical Examples of File Handling
5.7 Common File Errors
5.8 Summary
5.9 Technical Terms
5.10 Self-Assessment Questions
5.11 Suggested Readings
Programming and Problem-Solving … 5.2 Files
5.1 INTRODUCTION
Programs often need to store information permanently, beyond the life of a single execution.
Variables and data structures reside in main memory (RAM), which is temporary; once the
program ends, that data disappears. To preserve data, we store it in files on a secondary
storage device (like a hard disk). A file is a named collection of data saved on a storage
medium. Python can read data from existing files and write new information to files. This
process is called file input and output (file I/O).
Every computer’s operating system manages a file system, which organizes data into files
and directories (folders).Each file has a name, location (path), and a type that determines how
the contents are interpreted.
The open() function creates a connection between the program and the file:
Reading data from a file can be done in several ways depending on the amount and structure
of data.
The following program counts the number of lines, words, and characters in a given text
file.
def fileStats(filename):
infile = open(filename, 'r')
lines = [Link]()
[Link]()
num_lines = len(lines)
num_words = sum(len([Link]()) for line in lines)
num_chars = sum(len(line) for line in lines)
The 3 lines in this file end with the new line character.
Output
Lines: 3
Words: 15
Characters: 96
Explanation:
This is a common file-reading pattern used in text processing and data analysis.
The 3 lines in this file end with the new line character.
Program Call
myGrep('[Link]', 'line')
Output
The 3 lines in this file end with the new line character.
There is a blank line above this line.
Explanation:
• The file is opened in read mode ('r').
• Each line is checked using the in operator to see if the target substring occurs in it.
• Lines containing the target word are printed after removing trailing newlines with
.strip().
• The file is then closed using .close().
This simple function demonstrates pattern searching in text files — a foundational concept
for text processing, data filtering, and log analysis in Python.
The function myReplace() reads a text file line by line, replaces all occurrences of a target
string with a replacement string, and writes the modified lines to a new output file.
[Link]()
[Link]()
Explanation:
• The program opens the input file ([Link]) in read mode and creates a new output
file (new_example.txt) in write mode.
• Each line is processed using the replace() method, which substitutes all occurrences of
the target string with the replacement.
• The modified lines are written to the new file.
• Finally, both files are closed to ensure proper resource handling.
value = 5
[Link]('3 Non string value like ' + str(value) + ' must be converted first.\n')
[Link]('4 Non string value like ' + str(value) + ' must be converted first. WRITING TO
A TEXT FILE\n')
[Link]()
Explanation:
• The file [Link] is opened in write mode ('w'), creating a new file in the current
working directory.
• Each write() call adds one line to the file.
• The \n character ensures each new line starts properly.
• The numeric value 5 is first converted to a string using str(value) before being written.
• Finally, close() is called to save and release the file.
[Link]()
Updated File – [Link]
1 This is the first line. Still the first line...
2 Now we are in the second line.
3 Non string value like 5 must be converted first.
4 Non string value like 5 must be converted first. WRITING TO A TEXT FILE
5 This line is added later using append mode.
6 File content is preserved and new data is added at the end.
Explanation:
• Opening a file with 'a' does not erase its existing contents.
• Every call to write() adds text to the end of the file.
• This mode is ideal for logging, adding new records, or progressively storing results.
• Only even numbers are printed after removing newline characters using .strip().
f = open('[Link]', 'r')
Output:
FileNotFoundError: [Errno 2] No such file or directory: '[Link]'
Reason:
• The file [Link] does not exist in the current working directory.
Solution:
Use a try–except block to catch the error gracefully:
try:
f = open('[Link]', 'r')
except FileNotFoundError:
print('Error: The specified file was not found.')
Output:
FileNotFoundError: [Errno 2] No such file or directory: 'C:/wrongfolder/[Link]'
Reason:
• The directory wrongfolder does not exist.
Solution:
• Verify the file path or use an absolute path:
f = open('C:/Users/YourName/Documents/[Link]', 'r')
5.8 SUMMARY
In this chapter, you learned how to:
• Work with the file system and understand file paths.
• Open, read, and write files using Python’s built-in functions.
• Use different reading patterns such as read(), readline(), and readlines().
• Employ the with statement for automatic file management.
• Write and append text efficiently.
• Handle file-related errors using exceptions.
The objective of this chapter is to explain the nature of program errors, differentiate between
syntax and runtime errors, and introduce Python’s exception-handling mechanism for
building reliable programs.
STRUCTURE
6.1 Introduction
6.2 Understanding Program Errors
6.3 Syntax Errors
6.4 Runtime Errors and Exceptions
6.5 Exception Hierarchy in Python
6.6 Handling Exceptions – try and except
6.7 else and finally Blocks
6.8 Raising Exceptions with raise and assert
6.9 Creating Custom Exceptions
6.10 Multiple and Nested Handlers
6.11 Using the with Statement for Resource Management
6.12 Debugging in Python
6.13 Logging Runtime Information
6.14 Case Study – Logging File Access
6.15 Summary
6.16 Technical Terms
6.17 Self-Assessment Questions
6.18 Suggested Readings
Programming and Problem-Solving … 6.2 Exception Handling
6.1 INTRODUCTION
Errors are an inevitable part of programming. Some errors prevent the program from running
at all, while others occur only when it executes.
Exception handling provides a structured way to detect and respond to runtime problems
without halting the entire program.
The commonly used root is Exception, from which most runtime errors inherit.
If no error occurs, the program skips all except blocks and continues normally.
If an error (exception) occurs, Python immediately stops the try block and looks for a
matching except
The except block is used to handle the exception that occurs in the try block.
It specifies what should happen when a particular error is detected.
try:
num = int(input("Enter an integer: "))
print(10 / num)
except ValueError:
print("Input must be an integer.")
except ZeroDivisionError:
print("Cannot divide by zero.")
Output Examples
Input: ten → Input must be an integer.
Input: 0 → Cannot divide by zero.
Multiple Except Blocks
You can use several except blocks to handle different error types separately.
try:
f = open("[Link]", "r")
n = int([Link]())
print(10 / n)
except FileNotFoundError:
print("File not found.")
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid data in file.")
Key Points
• The try block contains code that may cause an exception.
• The except block contains code that handles that exception.
• You can have multiple except blocks for different exception types.
• If no exception occurs, the except blocks are skipped.
• You can also use a generic exception handler to catch any unexpected error:
Centre for Distance Education 6.5 Acharya Nagarjuna University
except Exception as e:
print("An error occurred:", e)
They define what happens when no exception occurs (else) and what must always be
executed (finally).
• The else Block
The else block executes only if no exception occurs in the try block.
It is useful for placing code that should run only when the try block succeeds without
errors.
Syntax:
try:
# Code that might raise an exception
except ExceptionType:
# Handle the exception
else:
# Code to execute if no exception occurred
Example:
try:
f = open("[Link]", "r")
content = [Link]()
except FileNotFoundError:
print("Error: File not found.")
else:
print("File opened successfully.")
print(content)
[Link]()
Output (if file exists):
File opened successfully.
<file contents>
Output (if file does not exist):
Error: File not found.
Programming and Problem-Solving … 6.6 Exception Handling
Explanation:
• If open() raises a FileNotFoundError, the except block executes.
• If no error occurs, Python skips except and executes the else block.
2. The finally Block
The finally block executes no matter what happens — whether an exception occurs or not.
It is used for cleanup operations like closing files, releasing resources, or disconnecting
from databases.
Syntax:
try:
# Risky operation
except ExceptionType:
# Handle error
finally:
# Code that always runs
Example:
try:
f = open("[Link]", "r")
data = [Link]()
print("Reading file completed.")
except FileNotFoundError:
print("File not found.")
finally:
print("Closing file (if opened).")
try:
[Link]()
except:
pass
Possible Outputs:
Reading file completed.
Closing file (if opened).
or
File not found.
Closing file (if opened).
Centre for Distance Education 6.7 Acharya Nagarjuna University
Explanation:
• The finally block executes regardless of whether an exception occurs.
• Even if a return, break, or continue statement is used inside try or except, the finally
block will still run before the program exits that scope.
• It is commonly used to ensure resources (files, network connections, etc.) are released
properly.
Python allows programmers to define their own custom exceptions to handle specific error
situations that are not covered by built-in exceptions. Custom exceptions make programs
more readable, modular, and meaningful because they describe the exact problem in the
program’s domain.
A custom exception is a user-defined class that inherits from Python’s built-in Exception
class (or one of its subclasses). By creating subclasses of Exception, programmers can define
error types that are specific to their application.
Basic Syntax
class MyException(Exception):
"""Custom exception class."""
pass
The pass statement is used here because we do not need to add new behavior; the class
simply acts as a new type of exception.
def square_root(x):
if x < 0:
raise NegativeNumberError("Cannot compute square root of a negative number.")
else:
return x ** 0.5
try:
print(square_root(-9))
except NegativeNumberError as e:
Centre for Distance Education 6.9 Acharya Nagarjuna University
print("Error:", e)
Output
Error: Cannot compute square root of a negative number.
Explanation:
• The class NegativeNumberError extends Exception.
• When a negative value is passed, the raise statement triggers this exception.
• The except block catches and handles it gracefully.
try:
new_balance = withdraw(500, 800)
except InsufficientFundsError as e:
print("Transaction Failed!")
print(e)
print("Remaining balance:", [Link])
Output
Transaction Failed!
Insufficient funds: Balance=500, Withdrawal=800
Remaining balance: 500
Programming and Problem-Solving … 6.10 Exception Handling
Explanation:
• The __init__ method initializes the exception with custom attributes.
• The super() call passes a formatted error message to the base Exception class.
• The caught exception can access [Link] or [Link] for more details.
class AgeTooHighError(Exception):
pass
def check_age(age):
if age < 0:
raise InvalidAgeError("Age cannot be negative.")
elif age > 120:
raise AgeTooHighError("Age seems unrealistically high!")
else:
print("Valid age:", age)
try:
check_age(150)
except (InvalidAgeError, AgeTooHighError) as e:
print("Error:", e)
Output
Error: Age seems unrealistically high!
Advantages of Custom Exceptions
• Clarity: Communicate the exact type of problem in user-defined domains.
• Modularity: Separate error-handling logic from main program logic.
• Hierarchy: You can organize related exceptions under a parent custom exception.
• Maintainability: Easier debugging and understanding of specific failure conditions.
class InvalidIDError(StudentError):
pass
class MissingGradeError(StudentError):
pass
try:
raise MissingGradeError("Grade record not found for student ID 2025.")
except StudentError as e:
print("Student Database Error:", e)
Output
Student Database Error: Grade record not found for student ID 2025.
By creating a hierarchy, all student-related exceptions can be caught together using the base
class StudentError.
• Custom exceptions are classes derived from Exception.
• Use the raise statement to trigger them intentionally.
• Include descriptive messages and attributes for context.
• Organize related custom exceptions using inheritance.
• Handling them separately enhances readability and error diagnostics.
Programming and Problem-Solving … 6.12 Exception Handling
The with statement is used to wrap the execution of a block of code within methods
defined by a context manager. It ensures that resources are acquired and released
properly, even if an exception occurs inside the block.
Syntax:
with expression as variable:
# Code block using the resource
When the block under with finishes execution:
• The resource is automatically cleaned up (e.g., the file is closed).
• Any exceptions that occur inside the block are handled safely.
How It Works
When a file (or any object) is opened using with, Python calls two special methods of that
object:
Method Purpose
__enter__() Called when entering the with block; initializes the resource.
__exit__() Called automatically when leaving the with block, even if an exception occurs;
used for cleanup.
This automatic handling eliminates the need for a manual close() call.
Example 1: Using with to Handle Files
with open('[Link]', 'r') as f:
contents = [Link]()
print(contents)
Centre for Distance Education 6.13 Acharya Nagarjuna University
Explanation:
• The open() function returns a file object.
• The with statement calls f.__enter__() to open the file.
• The file is used inside the block.
• When the block ends, f.__exit__() is called automatically, closing the file — even if
an error occurs.
[Link]('Program started')
try:
result = 10 / 0
except ZeroDivisionError:
[Link]('Division by zero encountered')
[Link]('Program ended')
[Link]
INFO:root:Program started
ERROR:root:Division by zero encountered
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
INFO:root:Program ended
Logging is essential for diagnosing production errors without interrupting program execution.
Logging is a technique used to record events that occur while a program runs, such as file
openings, errors, or successful operations.
Centre for Distance Education 6.15 Acharya Nagarjuna University
Python’s logging module makes it easy to keep a record of such activities in a separate log
file.
[Link](
filename='file_access.log',
level=[Link],
format='%(asctime)s - %(levelname)s - %(message)s'
)
def open_file(filename):
try:
with open(filename, 'r') as f:
data = [Link]()
[Link](f"File opened successfully: {filename}")
except FileNotFoundError:
[Link](f"File not found: {filename}")
except PermissionError:
[Link](f"Permission denied: {filename}")
Sample Output on Screen
Error: File not found: [Link]
Contents of file_access.log
2025-10-28 17:10:03,502 - INFO - File opened successfully: [Link]
2025-10-28 17:10:04,210 - ERROR - File not found: [Link]
Explanation
• The logging module writes messages to a log file instead of printing them.
• Each log entry includes a timestamp, a severity level, and a message.
• Levels such as INFO, WARNING, and ERROR describe the importance of each
event.
• Logging helps trace errors, monitor program activity, and maintain system reliability.
Key Points
• [Link]() initializes log settings.
Programming and Problem-Solving … 6.16 Exception Handling
Logging file access helps developers track file operations and detect errors automatically,
improving debugging, transparency, and program maintenance.
6.15 SUMMARY
In this chapter, you learned how Python handles errors and exceptions, and how to write
programs that can detect and recover from unexpected situations gracefully.
Essay Questions
1. Explain the difference between syntax errors, runtime errors, and logical errors with
examples.
2. Discuss the working of the try–except–else–finally structure with suitable code.
3. Describe how custom exceptions are created and used in Python.
4. What is the purpose of the with statement? Illustrate its use in file operations.
Centre for Distance Education 6.17 Acharya Nagarjuna University
5. Explain the use of the logging module for debugging and tracking file access.
6. Write a short note on exception hierarchy and the importance of handling specific
exceptions.
7. Discuss how debugging tools like pdb can be used to find logical errors.
Short-Answer Questions
STRUCTURE
7.1 Introduction
7.2 Need for Decision Making in Programs
7.3 Boolean Expressions and Relational & Logical Operators
7.4 Simple if Statement
7.5 if–else Statement
7.6 if–elif–else Statement
7.7 Nested if Statements
7.8 Conditional Expressions (Ternary Operator)
7.9 Practical Examples
7.10 Summary
7.11 Technical Terms
7.12 Self-Assessment Questions
7.13 Suggested Readings
7.1 INTRODUCTION
Every non-trivial program must be able to make decisions. A decision statement allows a
program to choose a course of action depending on whether a condition evaluates to True or
False. Python’s main decision-making construct is the if statement. Together with relational
and logical operators, it forms the basis for control flow.
Example motivation:
temperature = 37.8
if temperature > 37:
print("Fever detected")
The program executes the print() statement only when the condition temperature > 37 is True.
Programming and Problem-Solving … 7.2 Conditional Structures
A Boolean expression evaluates to one of the two truth values: True or False.
Python treats True as 1 and False as 0 in numeric contexts.
Table 7.1 Relational Operators
Operator Meaning Example Result
== equal to 5 == 5 True
!= not equal to 7 != 2 True
< less than 3<9 True
> greater than 8 > 10 False
<= less than or equal to 5 <= 5 True
>= greater than or equal to 9 >= 5 True
Relational operators are often combined with logical operators to form compound conditions.
Example
age = 20
if age >= 18:
print("Adult")
Example
x=5
y = 10
print((x < 10) and not(y < 5 or x == 7))
Syntax:
if ( EXPRESSION = = TRUE ) :
if- Block of code
Next statement after Block of code is executed.
• Otherwise, the statement that comes after the conditional block of code will be
executed.
• If you look at the flowchart that was just presented, you will notice that the controller
will first arrive at an if condition and then evaluate the condition.
• if it is not true, then the code that is present outside the block will be executed.
Example: 1
Output:
The above code tests the condition "x<20." If the test is successful, a block of code will be
executed, as really seen in the output, and finally the last line, "This statement will always
be executed," will be executed. This statement is also clearly displayed in the output.
Centre for Distance Education 7.5 Acharya Nagarjuna University
Example 2:
Output:
The code condition (Obtained_Mark > = Pass_Mark) is tested in the previous example; if it
passes, the if-block will be executed. The code is executed twice. The first time, the
condition is not met (20 < 40), and the final message, "End of the Program," is shown.
Nevertheless, the second attempt met the success requirement (i.e., 60 > 40), printed
"Congratulations on Passing the Exam," and showed the final message, "End of the
Program."
if-else statements
The Boolean expression is evaluated by the if-else statement. The code in the "if" block will
be executed if the condition is TRUE; otherwise, the code in the "else" block will be
executed.
Programming and Problem-Solving … 7.6 Conditional Structures
Syntax:
If (EXPRESSION == TRUE):
If-Statement (Body of the block)
else:
else-Statement (Body of the block)
According to the flow chart above, the controller will first reach the if condition and
determine if the condition is true. If it is, the statements in the if block will then be run; if not,
the "else" block will be executed, and finally the remaining code that is included outside the
"if-else" block will be executed.
Centre for Distance Education 7.7 Acharya Nagarjuna University
Example: 1
The condition (x<20) is tested twice in the code above. The first time it is run, if it is
successful, a block of code will be executed, as we can see in the output. Finally, the final
statement, "This statement will always be executed," is executed, and this is also clearly
displayed in the output. Nevertheless, the second run condition failed by evaluating x=30,
executing the else-Block of code, and generating the output "X is greater than 20." The final
statement, "This statement will always be executed," is finally carried out and is likewise
displayed in the output.
Output:
Programming and Problem-Solving … 7.8 Conditional Structures
Example2:
Output:
The code condition (Obtained_Mark > = Pass_Mark) is tested in the previous example; if it
passes, the if-block will be executed. The code is executed twice. The first time, if the
condition is met (i.e., 50 > 40), the message "Congratulations You Passed Exam" is
displayed, and the final phrase, "End of the Program," is printed. Nevertheless, the second
time around, the condition failed (20 < 30), printing "Sorry, Better Luck Next Time" and
displaying the last sentence, "End of the Program."
"elif" statements are an additional type of conditional statement in Python. The "elif"
statement checks for multiple conditions only in the event that the supplied condition is false.
The sole distinction between it and a "if-else" expression is that the condition will be checked
in "elif" rather than "else."
Centre for Distance Education 7.9 Acharya Nagarjuna University
Syntax:
if (EXPRESSION-1 = = TRUE):
If-Statement (Body of the block)
elif(EXPRESSION-2 = = TRUE):
elif-Statement (Body of the block)
elif(EXPRESSION-3 = = TRUE):
elif-Statement (Body of the block)
else:
else-Statement (Body of the block)
Example:
In the code below, the condition (Obtained_Mark >= Dist_Mark) is tested; if it is successful,
the if-block of code is executed; otherwise, the following succeeding blocks are executed
based on the criteria; otherwise, the else statement and the end statement are executed. The
code is executed four times; the first time the condition is met (i.e., 50 > 40), the message
"Congratulations You Passed Exam" is displayed, and the last statement, "End of the
Program", is printed. However, the second time run condition (65 > 60) is successful and
prints "Congratulations You Passed Exam in First Class" before displaying the last line,
"End of the Program". Similarly, in the third run, the requirement (i.e., 80 > 70) is met, and
the message "Congratulations You Passed Exam in Distinction" is displayed, followed by
the final sentence "End of the Program". During the last run, if the condition (i.e., 30 < 40) is
not met, the else block is activated and the message "Sorry, Better Luck Next Time" is
written. The last statement displayed is "End of the Program".
Example:
Centre for Distance Education 7.11 Acharya Nagarjuna University
Output:
Nested "if-else" statements indicate that one "if" or "if-else" statement is contained within
another if or if-else block. Python has this feature as well, which allows us to verify several
conditions in a single application.
Syntax:
if (EXPRESSION-1 = = TRUE):
if (EXPRESSION-2 = = TRUE):
Inner-If-Statement (Body of the block)
Programming and Problem-Solving … 7.12 Conditional Structures
else:
Inner-else-Statement (Body of the block)
else:
Outer-else-Statement (Body of the block)
The syntax used above obviously shows that the if block will include another if block, and so
on. If block can have 'n' number of if blocks within it.
Example:
In the code below, the condition (Obtained_Mark > = Pass_Mask) is tested. If it is successful,
the inner if-statement (Obtained_Mark > = First_Mask and Obtained_Mark < Dist_Mask) is
tested. If it is successful, the block-related inner condition is executed. Otherwise, the block-
related inner condition is executed. Otherwise, the else block from the outer condition is
executed. The ensuing blocks are run based on the circumstances; otherwise, the else
statement is executed, followed by the end statement.
Centre for Distance Education 7.13 Acharya Nagarjuna University
The code is executed four times. The first time, the condition is successful (i.e., 80 > 40), and
the second time, the condition is likewise successful (i.e., 80 > 70), and the message
"Congratulations You Passed Exam in Distinction" is displayed, followed by the last
statement, "End of the Program". However, the condition is successful the second time
(65>40) and then tested (65>60) and printed "Congratulations You Passed Exam in First
Class" and displayed the last statement, "End of the Program". Similarly, in the third run, the
condition is successful (i.e., 50 > 40), and then tested (i.e., 50 > 40), which is successful and
prints "Congratulations You Passed Exam" and displays the last statement, "End of the
Program". If the condition is not met (i.e., 25 < 40), the else block is activated and the
message "Sorry, Better Luck Next Time" is written. The last statement displayed is "End of
the Program".
Programming and Problem-Solving … 7.14 Conditional Structures
Output:
In some situations, it is useful to make a simple decision in a single line rather than writing a
complete if–else [Link] provides the conditional expression, also known as the
ternary operator, for such cases.
It evaluates a condition and returns one of two values depending on whether the condition is
True or False.
Syntax
<value_if_true> if <condition> else <value_if_false>
This expression is evaluated from left to right.
• If the condition is True, Python returns <value_if_true>.
Centre for Distance Education 7.15 Acharya Nagarjuna University
Advantages
• Compact and expressive for simple decisions.
• Improves code readability when used judiciously.
• Can be nested for complex choices, though readability may suffer.
Each example shows both code and expected output to clarify control flow.
Where:
• weight → person’s weight in pounds
• height → person’s height in inches
• 703 → conversion factor for imperial units
Program
def myBMI(height, weight):
"""Compute and classify Body Mass Index (BMI)."""
bmi = (weight * 703) / (height ** 2)
print("BMI value:", round(bmi, 2))
print("Overweight")
# Example usage:
h = float(input("Enter height (in inches): "))
w = float(input("Enter weight (in pounds): "))
myBMI(h, w)
Explanation
1. The function myBMI() takes two inputs — height and weight.
2. The BMI is calculated using the formula.
3. Using an if–elif–else structure:
o If BMI < 18.5 → prints Underweight.
o If 18.5 ≤ BMI < 25 → prints Normal.
o If BMI ≥ 25 → prints Overweight.
4. The round() function is used to format the BMI to two decimal places.
Sample Runs
Example 1:
Enter height (in inches): 65
Enter weight (in pounds): 110
BMI value: 18.3
Underweight
Example 2:
Enter height (in inches): 68
Enter weight (in pounds): 150
BMI value: 22.8
Normal
Example 3:
Enter height (in inches): 63
Enter weight (in pounds): 165
BMI value: 29.2
Overweight
Programming and Problem-Solving … 7.18 Conditional Structures
7.10 SUMMARY
• Decision control statements make a program choose specific actions based on
conditions.
• The constructs if, if–else, if–elif–else, and nested if allow conditional branching.
• Boolean expressions use relational and logical operators and evaluate to True or
False.
• The conditional (ternary) expression provides a concise single-line decision.
• Correct indentation defines program structure in Python.
• These statements add flexibility and intelligence to programs.
7.11 TECHNICAL TERMS
Decision Control, Conditional Statement, Boolean Expression, Relational Operator, Logical
Operator, Indentation, if Statement, Elif, else, Nested if, Conditional Expression / Ternary
Operator, Branching, Truth Table, Compound Condition, Control Flow, Condition Testing.
7.12 SELF-ASSESSMENT QUESTIONS
Essay Questions
1. Explain the need for decision control in a program with examples.
2. Describe the working of if, if–else, and if–elif–else statements.
3. Write a program to determine whether a year is a leap year.
4. Discuss how logical operators help in forming compound conditions.
5. Explain the role of indentation in decision structures.
6. What is a conditional expression? Give suitable examples.
Short Notes
1. Boolean expressions and relational operators.
2. Range checking using if–else.
3. Flow of control in if–elif–else.
4. Difference between nested if and if–elif–else.
5. Syntax and use of the else block.
Programming Exercises
1. Accept three numbers and display the largest.
2. Write a menu-driven calculator using if–elif–else.
3. Determine whether a character is a vowel, consonant, or symbol.
4. Check if a given number is divisible by 5 and 11.
5. Print student grade based on marks using decision statements.
6. Use a conditional expression to find the smaller of two numbers.
STRUCTURE
8.1 Introduction
8.2 The for Loop and Iteration Patterns
8.2.1 Loop Pattern: Iteration Loop
8.2.2 Loop Pattern: Counter Loop
8.2.3 Loop Pattern: Accumulator Loop
8.2.4 Accumulating Different Data Types
8.2.5 Loop Pattern: Nested Loop
8.3 Two-Dimensional Lists
8.3.1 Concept of Two-Dimensional Lists
8.3.2 Nested Loop Pattern with 2-D Lists
8.4 The while Loop
8.5 More Loop Patterns
8.5.1 Sequence Loop
8.5.2 Infinite Loop
8.5.3 Loop-and-a-Half Pattern
8.6 Additional Iteration Control Statements
8.6.1 The break Statement
8.6.2 The continue Statement
8.6.3 The pass Statement
8.7 Summary
8.8 Technical Terms
8.9 Self-Assessment Questions
8.10 Suggested Readings
8.1 INTRODUCTION
For example:
• Counting from 1 to 10,
• Summing a list of numbers,
• Printing elements of a list, or
• Reading data until the user quits.
The for loop is used to execute a block of code a fixed number of times or once for each
element in a sequence such as a list, tuple, or string.
Syntax
for variable in sequence:
statement(s)
Each element in the sequence is assigned to the loop variable, and the indented block
executes once per element.
Output
fish
cat
dog
count += 1
Output
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
Example
for letter in "PYTHON":
print(letter)
Output
P
Y
T
H
O
N
8.5.2 Infinite Loop
An infinite loop runs forever unless stopped manually or by a break condition.
Example
while True:
name = input("Enter name (type 'stop' to exit): ")
if name == 'stop':
break
print("Hello,", name)
break
print(i)
Output
1
2
3
4
8.7 SUMMARY
• Loops repeat a block of code multiple times.
• The for loop handles definite iteration; the while loop handles indefinite iteration.
• Common loop patterns:
o Iteration Loop – processes each element.
o Counter Loop – runs for a set number of iterations.
o Accumulator Loop – builds up totals or collections.
o Nested Loop – processes multi-dimensional structures.
• Control statements (break, continue, pass) modify normal loop flow.
• Two-dimensional lists are handled using nested loops.
Iteration,
Loop,
Counter Variable,
Accumulator,
Nested Loop,
Two-Dimensional List,
Infinite Loop,
Loop-and-a-Half Pattern,
break, continue, pass,
Definite Iteration,
Indefinite Iteration.
Essay Questions
1. Explain the difference between for and while loops in Python.
2. Describe and illustrate accumulator and counter loop patterns.
3. Explain nested loops with an example.
4. How are two-dimensional lists processed using nested loops?
5. What is an infinite loop? How can it be avoided?
6. Discuss how break and continue statements affect loop execution.
Short Notes
1. Sequence loop.
2. Loop control statements.
3. Loop and a half pattern.
4. Role of the accumulator variable.
5. Use of range() in for loops.
Programming Exercises
STRUCTURE
9.1 Introduction
9.2 Python Dictionary
9.2.1 The Characteristic of Dictionary
9.2.2 Creating Python Dictionary
9.3 Accessing Dictionary Elements
9.3.1 Access Dictionary by Key
9.3.2 Access dictionary by get () method.
9.3.3 Access of Nested Dictionary
9.4 Dictionary Methods
9.4.1 Update Elements Methods
9.4.2 Remove Elements Methods
9.4.3 keys () and values() Methods
9.5 Dictionary Functions
9.5.1 len() method
9.5.2 sorted () method.
9.5.3 all () method
9.5.4 any () function
9.6 A Dictionary as a Substitute for Multiway Condition
9.7 Dictionary as a Collection of Counters .
9.8 Summary
9.9 Technical Terms
9.10 Self-Assessment Questions
9.1. INTRODUCTION
Python, a programming language, is equipped with a wide variety of tools and functions. The
dictionary is one example of such a feature. In the Python programming language, a dictionary
is a collection of key-value pairs. Uniqueness is required for the dictionary keys. A value of any
kind could be assigned to the dictionary. Python's dictionary is a data structure that makes it
possible for us to develop code that is both simple and very effective. The fact that the keys of
this data structure can be hashed is the reason why it is referred to as a hash table in many
different languages. In a moment, we will comprehend the significance of this.
Using Python dictionaries, we can easily obtain a value that has been associated with a specific
key and then immediately access that value. It is recommended that we make use of them if we
are looking for a certain Python object, also known as a lookup method.
A dictionary in Python is a set of objects that let's us store information in key-value pairs.
With Python dictionaries, we may rapidly obtain a value by associating it with a distinct key.
Using them whenever we need to locate (search for) a certain Python object is a good
concept. For this purpose, lists can also be used, but they operate far more slowly than
dictionaries.
• In the first place, the dictionary will have information in the form of key-value pairs.
• A colon ":" sign is used to visually define the key and the values.
• The representation of an item can consist of a single key-value pair.
• It is not permitted to have duplicate keys.
• It is possible to acknowledge duplicate values.
• It is quite OK to use heterogeneous objects for both keys and values.
• The order of the insertion is not maintained.
• a dictionary object that is capable of being altered.
• Dictionary entries behave in a dynamic manner.
• The notions of indexing and slicing are not applicable in this situation.
Centre for Distance Education 9.3 Acharya Nagarjuna University
Syntax:
my_dict = {
"key1":"value1",
"key2":"value2"
}
In the above syntax my_dict is a dictionary created with two pair of items differentiated with
different keys and values.
Example:
# creating a dictionary
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
In the above example country_capitals is a dictionary created with three pair of items which
includes {"Germany": "Berlin"}, {"Canada": "Ottawa"} and { “England": "London"}.
• Access by Key
• Access by get () function
• Access of nested dictionary
We can access the value of a dictionary item by placing the key inside square brackets. It
accesses and prints the values associated with the keys. The keys and values showcasing
can be of different data types (string and integer).
Syntax:
Value= dictionary_name[‘Key’]
Programming and Problem-Solving … 9.4 Python Dictionary
Example:
Example:
Output:
The code demonstrates accessing a dictionary element using the get() method. It retrieves
and prints the value associated with the key 3 in the dictionary ‘Dict’. This method provides
a safe way to access dictionary values, avoiding KeyError if the key doesn’t exist.
Centre for Distance Education 9.5 Acharya Nagarjuna University
Example:
Output:
To access the value of any key in the nested dictionary, use indexing [] syntax. It first
accesses main dictionary associated with the key and then, it accesses a specific value by
navigating through the nested dictionaries.
Example:
Programming and Problem-Solving … 9.6 Python Dictionary
Output:
Dictionary methods are used to perform specific functionality over dictionary that may be
updating, adding, extracting a, removing and etc operations on keys and items. Some of the
functions includes in given Table 9.1.
Function Description
pop() Removes the item with the specified key.
update() Adds or changes dictionary items.
clear() Remove all the items from the dictionary.
keys() Returns all the dictionary's keys.
values() Returns all the dictionary's values.
get() Returns the value of the specified key.
popitem() Returns the last inserted key and value as a tuple.
Dictionaries are subject to change. Using an assignment operator, we can add new things or
change the value of existing items.
Centre for Distance Education 9.7 Acharya Nagarjuna University
Example:
Output:
By declaring value together with the key, for example, Dict[Key] = ‘Value’, one value at a time
can be added to a Dictionary. Another approach is to use Python’s update () function. Python’s
update () method is a built-in dictionary function that updates the key-value pairs of a
dictionary using elements from another dictionary or an iterable of key-value pairs. With
this method, you can include new data or merge it with existing dictionary entries.
Programming and Problem-Solving … 9.8 Python Dictionary
Example:
Output:
A key can be removed from a dictionary in three ways: from an individual entry, from all
entries, or from the entire dictionary.
1. The pop () function can be used to remove a single element. The value of the key that has
been specified to be eliminated is returned by the pop () function.
2. To randomly remove any elements (key-value pairs) of the dictionary, we can use
the popitem() It returns the arbitrary key-value pair that has been removed from the
dictionary.
3. Using the clear () method, all elements can be eliminated at once. The del keyword is
used to completely delete the entire dictionary.
Centre for Distance Education 9.9 Acharya Nagarjuna University
Example:
Output:
In Python, the keys () function returns a view object that contains dictionary keys, which
enables quick access and iteration across the [Link] values() method in Python
returns a view object that contains all of the dictionary values. This view object can be
accessed and iterated through in an effective manner within Python.
Syntax:
d = {'key': 'value'}
[Link]()
Programming and Problem-Solving … 9.10 Python Dictionary
Syntax:
d = {'key': 'value'}
d. values ()
Example:
In the above example , created dictionary called dic_country with three elements with the
usage of keys() and values() fucntions displayed the information related every key and values
associated with elements stored in dic_county dictionary. The reslut shown in output.
Output:
The Python dictionary offers a wide range of methods that may be utilized to conduct operations
on key-value pairs in an easy and convenient manner. The following is a list of functions using
the Python dictionary shown in Table 9.1.
Centre for Distance Education 9.11 Acharya Nagarjuna University
Using the len() method, which returns the item count, one can determine the length of a
dictionary by its use. Printing the length of my dictionary is as follows:
Example:
Output:
Programming and Problem-Solving … 9.12 Python Dictionary
In the above example , dic_country elements count is determined by calling the len() function
and displayed lengh of the dictionary 3 it means dictinay holds the three elemtns and reslut
shown in output.
Sorting the dictionary can be accomplished with Python's built-in keys functions, which
include the keys () and values () functions. Any iterable can be used as an argument, and it
will return the sorted list of keys you provided. The dictionary can be arranged in ascending
order by using the keys to sort the entries. First, let's get familiar with the below example.
Example:
Output:
We have declared a dictionary of names in the code that was just presented. We made use of
the built-in function in conjunction with the sorted() method, which provided us with a list of
Centre for Distance Education 9.13 Acharya Nagarjuna University
the keys that had been sorted. We then proceeded to utilize the items() function in order to
obtain the dictionary in the order that it was sorted.
A dictionary's keys are the only elements that are examined when the all() method is applied to it;
the values are not examined. In the event that not all of the keys in the dictionary are true, the all()
method will return FALSE; but, if all of the keys are true, it will return false. In the event that the
dictionary does not consist of any entries, the all() function also returns a value of TRUE.
Example:
Output:
will return TRUE; otherwise, it will return FALSE. In the event that the dictionary does not
consist of any entries, the any () function also returns FALSE.
Example:
Output:
However, dictionaries can also replace long multiway if–elif–else chains where multiple
Centre for Distance Education 9.15 Acharya Nagarjuna University
conditions are used to perform simple lookups or mappings. Let us consider a motivating
example.
Example Problem
Suppose we want to write a function complete() that accepts the two-letter abbreviation of a
weekday (e.g., 'Tu') and returns the full name of the day (e.g., 'Tuesday').
Desired behavior:
>>> complete('Tu')
'Tuesday'
Explanation
• The dictionary days maps each two-letter abbreviation (the key) to the corresponding
full day name (the value).
• To find the full name, we simply index the dictionary using the abbreviation:
days[abbreviation].
• The dictionary performs this lookup instantly, without testing multiple conditions.
Sample Run
>>> complete('We')
'Wednesday'
>>> complete('Su')
'Sunday'
Benefits of the Dictionary Approach
Aspect Multiway if–elif–else Dictionary Mapping
Code length Long and repetitive Compact and readable
Efficiency Each condition is checked Direct key lookup (constant time)
sequentially
Maintainability Hard to update or extend Easy to modify or add key–value pairs
Concept Conditional branching Key–value mapping
One of the most important and practical applications of dictionaries is counting occurrences
— also known as frequency counting.
Many programs, from search engines to data analytics tools, rely on counting how many
times specific items occur within a dataset.
Example Problem
Suppose we want to count the number of occurrences of each name in a list of student names.
students = ['Cindy', 'John', 'Cindy', 'Adam', 'Adam',
'Jimmy', 'Joan', 'Cindy', 'Joan']
We need a function frequency() that will take such a list and compute how many times each
name appears.
Concept
For each distinct item in the list, we want to:
1. Create a counter initialized to zero.
2. Increment the counter each time the item occurs.
The challenge is that we don’t know in advance how many distinct items exist.
Solution: Use a Dictionary of Counters
A dictionary is ideal because it can dynamically:
• Create a new key (item) the first time it appears.
• Associate it with a counter value.
• Increment that value each subsequent time the item appears.
Implementation
def frequency(items):
'Counts occurrences of each distinct element in the list items'
counters = {}
for item in items:
if item in counters:
counters[item] += 1
else:
counters[item] = 1
return counters
Example Use
students = ['Cindy', 'John', 'Cindy', 'Adam', 'Adam',
'Jimmy', 'Joan', 'Cindy', 'Joan']
print(frequency(students))
Programming and Problem-Solving … 9.18 Python Dictionary
Output
{'Cindy': 3, 'John': 1, 'Adam': 2, 'Jimmy': 1, 'Joan': 2}
Explanation
1. The empty dictionary counters = {} starts with no keys.
2. The loop visits each item in the list:
o If the item already exists in the dictionary, increment its counter.
o If not, create a new key with initial value 1.
3. After processing all items, the dictionary contains each unique element with its count.
9.8 SUMMARY
Python is an excellent programming language that comes with a wide variety of feature sets.
The fact that it provides a structured code makes it much simpler to comprehend. Since
Python is currently one of the most widely used programming languages in the modern day, it
is essential to have a comprehensive understanding of this programming language. This
chapter will provide you with practical experience on how to work with dictionary along
methods and functions.
Short Notes:
1. Write about get () access method.
2. How dictionary is different form the List.
TUPLE
AIMS AND OBJECTIVES
The main aim of this chapter is understanding the concept of tuples in Python Programming.
The discussion related to understand what tuple and its characteristics is. After completion of
this chapter, student will be able to know what tuple is, how it is different from other data
types. Also able to know access tuples by various methods, operations, functions, and
methods in tuples.
STRUCTURE
10.1 Introduction
10.2 Python Tuple
10.2.1 Creating Python Tuple
10.2.2 Advantages of Tuple over List
10.3 Accessing Tuple
10.3.1 Indexing
10.3.2 Negative Indexing
10.3.3 Slicing
10.4 Python Tuple Operations
10.4.1 Concatenation of Tuples
10.4.2 Tuple Membership
10.5 Python Tuple Functions
10.5.1 len()
10.5.2 max()
10.5.3 min()
10.5.4 sum()
10.6 Tuple Methods
10.6.1 count() Method
10.6.2 index() Method
10.7 Class tuple
10.8 Tuple Objects Can Be Dictionary Keys
10.9 Dictionary Method items(), Revisited
10.10 Summary
10.11 Technical Terms
10.12 Self-Assessment Questions
10.13 Suggested Readings
10. 1 INTRODUCTION
development due to its dynamic type and binding features. In this chapter we'll learn about
tuples, an important data structure in Python programming.
Python tuples are a data structure that is quite like a list. The primary distinction between the
two is that tuples are immutable, which means they cannot be modified once generated. This
makes them excellent for storing non-modifiable data, such as database records. A tuple can
contain any number of objects of various types, including strings, integers, floats, lists, and so
on. Let's look at how to generate and use a tuple to make our programming work easier.
A sequence of any items that are separated by commas and wrapped in parenthesis is referred
to as a tuple. We use tuples to represent fixed collections of elements since they are
immutable objects, which means they cannot be modified. Tuples are used to carry out this
function. Tuple items are placed in a specific order, cannot be altered, and permit duplicate
values. When we say that tuples are ordered, we are referring to the fact that the items in the
tuple have a predetermined order on which they will remain indefinitely. Tuples and Python
lists share some similarities in terms of indexing, nested objects, and repetition; nevertheless,
the most significant distinction between the two is that a Python tuple is immutable, whereas
a Python list is mutable. Tuples are used in Python programming languages. Since tuples are
indexed, the first item has an index of [0], the second item uses an index of [1], and so on.
It is possible to create a tuple by associated with all of the items (elements) in parentheses ()
rather than square brackets [], and by separating each element with commas. It is possible for a
tuple to include any number of objects of different types, including integers, floats, lists, strings,
and so on. In addition, you have the option of specifying nested tuples, which can include one or
more items that are either dictionaries, lists, or tuples.
The given example shows how to create simple Tuple in python:
Example:
emp_tup = () # Empty Tuple
int_tup = (2, 8, 1, 6, 15, 3) # A Tuple with integers
mixed_tup = (12, "sai", 81.3) # A Tuple with mixed data items
nested_tup = ("Python", [8,5,17,6], (2, 6, 1, 20)) # Nested Tuple
Centre for Distance Education 10.3 Acharya Nagarjuna University
We produced four different sorts of tuples in the example that was just presented: empty, int-type,
mixed type, and nested type. It is after the initialization of data items that the size of the empty
tuple is calculated. Nevertheless, the elements that are part of the int type and the mixed type are
the numbers 6 and 3. An example of a nested tuple is a special sort of tuple in which each element
also contains additional elements. A string, a list, and a tuple were the three elements that were
present in the nested tuple that was defined before.
Since they are so comparable, tuples and lists are applied in scenarios that are comparable.
On the other hand, there are a few benefits that come along with utilizing a tuple rather than a
list.
• In contrast to lists, the Tuples cannot be modified in any way. The addition, removal,
or replacement of a tuple is not possible.
• Tuples are often utilized for heterogeneous data kinds, which are distinct from one
another, whereas lists are typically utilized for homogeneous data types, which are
comparable to one another.
• Dictionary keys can be derived from tuples that include elements that cannot be
changed. When it comes to lists, this is not possible.
• If you have data that does not change, implementing it as a tuple will ensure that it
continues to be protected from being written to.
• If you wish to make changes to the information contained in a tuple, we will first need
to transform it into a list.
• Indexing
• Negative Indexing
• Slicing
10.3.1 Indexing
Accessing an item within a tuple that has an index that begins at 0 can be accomplished using
the index operator []. A tuple that contains five items will have indices that range from 0 to 4,
inclusive. An index that is higher than four will be considered out of range.
Programming and Problem-Solving … 10.4 Tuple
Example:
The four types of tuples that have previously been constructed in the example above—empty, int-
type, mixed type, and nested type—are accessed using an index. This operator is quite helpful in
accessing particular elements from the tuple. Different elements are accessible from different
types of tuples in the code above. Three elements from the integer tuple and two from the mixed
tuple, for instance. Similar access is made using the indexing method in nested tuples.
Output:
Centre for Distance Education 10.5 Acharya Nagarjuna University
Tuple, a type of sequence object in Python, also allows negative indexing. -1 addresses the
final item in the selection, -2 addresses the second-to-last item, and so on.
Example:
Two sorts of tuples, empty and int-type, are already constructed in the example above and are
accessed using a negative index. For instance, the -3 and -1 indexes are used to retrieve the
elements 3 and 2 of the integer and mixed tuples, respectively. In a similar vein, nested tuples can
also use this type of access.
Output:
10.3.3. Slicing
In Python, tuple slicing is a widely used technique that programmers use to solve real-world
problems. Examine a Python tuple. To access a range of a tuple's elements, slice it. One
method is to use the colon as a simple slicing operator (:).We can use the slicing operator
colon (:) to access different tuple components.
Programming and Problem-Solving … 10.6 Tuple
Example:
Output:
Tuple is a sequence in Python. As a result, we can use the + operator to concatenate two
tuples and the "*" operator to concatenate many copies of a tuple. Tuple objects are used by
the membership operators "in" and "not in."
Example:
Two tuples of the types character and integer were constructed in the example above,
designated as tuple_1 and tuple_2. The outcome of later addition operations applied to two
tuples is reported. The result, which combines the contents of tuples 1 and 2 into a single
tuple, is displayed on screen.
Output:
Programming and Problem-Solving … 10.8 Tuple
The existence of an item in a tuple can be ascertained by using the in and not in keywords.
Example:
Output:
Applying membership procedures on the two produced tuples, tuple_1 and tuple_2, as
demonstrated in the preceding example. The results of these membership operations, such
as is and is not, are TRUE or FALSE. Verified whether the term "there" is available in the
case above. In a same manner, look up further words.
Python offers a variety of functions for carrying out tasks. Functions such as cmp(), max(),
min(), and so forth are used to carry out particular tasks. Each function's explanation can be
found in Table 8.1.
Centre for Distance Education 10.9 Acharya Nagarjuna University
Function Description
cmp(tuple1, tuple2) Compares elements of both the tuples
len(tuple) Returns the total length of the tuple
max(tuple) Returns the largest element from the tuple
min(tuple) Returns the smallest element from the tuple
tuple(seq) Converts a list into tuple
10.5.1 len()
The number of elements in a tuple can be obtained using the len() method. It accepts a tuple
as an input and outputs an integer number that is the tuple's length.
Example:
Output:
Programming and Problem-Solving … 10.10 Tuple
We have defined a tuple called my_tuple with five items in the example above. The length of
the tuple, which is 5, was then obtained using the len() method.
10.5.2 max ()
To get the maximum value in a tuple, use the max () function. It accepts a tuple as an input
and outputs the tuple's maximum value.
Example:
Output:
We have defined a tuple called my_tuple with five items in the example above. The
maximum value in the tuple, which is 9, was then obtained using the max() method.
Centre for Distance Education 10.11 Acharya Nagarjuna University
10.5.3 min ()
To get the lowest value in a tuple, use the min () function. It accepts a tuple as an input and
outputs the tuple's minimal value.
Example:
Output:
We have defined two tuples tuple_1 and tuple_2 with six and five items in the example
above. Next, we obtained the tuple's minimal values Two, and 2 by using the min() function.
10.5.4 sum ()
The sum of each element in a tuple can be obtained using the sum () function. It accepts a
tuple as an input and outputs the total of each tuple's elements.
Programming and Problem-Solving … 10.12 Tuple
Example:
Output:
We have defined a tuple called tuple_2 with five items in the example above. The total of all
the elements in the tuple, which is 36, was then obtained using the sum () method.
Python's tuple routines offer an extensive range of functionalities for working with tuples.
Programmers can find the length, maximum or minimum value, total of all items, and create
tuples from iterables using these functions. Easy finding and counting of particular elements
within tuples is also made possible by the index() and count() operations.
A built-in Python function called count () can be used to determine how many times a certain
element appears in a tuple. The value to be counted is the only input that the method accepts.
Centre for Distance Education 10.13 Acharya Nagarjuna University
Example:
Output:
In the above example, we first create a tuple tuple_2 with some elements. Then we use the
count () method to count the number of occurrences of the value 2 in the tuple. The method
returns the count of 2 which is 3. Finally, we print the count.
A built-in Python function called index () can be used to determine the index of a given
element's first instance in a tuple. The value to be searched in the tuple is the only input
required by the method.
Example:
Programming and Problem-Solving … 10.14 Tuple
Output:
In the preceding example, we first create a tuple, tuple_2, with certain elements. Then we use
the index () method to discover the index of the tuple's first occurrence of the value 2. The
method returns the index of the first occurrence of 2 (which is 1). Finally, we will print the
index.
Tuples are widely used in Python for a variety of purposes, including returning multiple
values from a function, representing fixed groupings of data, and serving as keys in
dictionaries.
The methods discussed above make it simple to interact with tuples in Python, allowing you
to extract and change their contents. The count () function in Python is useful for determining
the number of repetitions of a certain element in a tuple. The index () function in Python is
useful for determining the index of the first occurrence of a certain element in a tuple.
Tuples can hold heterogeneous data, can be nested, and support operations such as indexing,
iteration, slicing, comparison, and packing/unpacking.
Example
print("ID:", student[0])
print("Name:", student[1])
Centre for Distance Education 10.15 Acharya Nagarjuna University
print("Age:", student[2])
print("Course:", student[3])
Output
ID: A102
Name: Priya
Age: 21
Course: BCA
Here, the tuple represents a single structured record, similar to a row in a database.
A major advantage of tuples is that, unlike lists, they can be used as keys in a dictionary.
This is because tuples are immutable and hashable, while lists are mutable and
unhashable.
Suppose we want to create a phonebook where each key is a person’s name (first and last),
and the value is their phone number.
phonebook = {
}
Programming and Problem-Solving … 10.16 Tuple
Output
Explanation:
phonebook = {
print(phonebook)
Output
Each tuple key uniquely identifies a person by their first and last name.
Output
(321)908-76-54
print(phonebook)
Output
The items() method is an important dictionary function that returns a view object containing
all key–value pairs as tuples.
Syntax
[Link]()
Returns:
A view of all (key, value) pairs in the dictionary.
print(entry)
Output
Each dictionary entry is represented as a tuple containing the key and its corresponding
value.
Output
Yu Tsun: (901)234-56-78
Explanation
• Unpacking allows direct access to both the first and last name components.
print(list([Link]()))
Output
]
Centre for Distance Education 10.19 Acharya Nagarjuna University
This representation shows how the dictionary internally stores key–value mappings as tuples.
data = [
new_phonebook = dict(data)
print(new_phonebook)
Output
Key Points
Feature Description
items() Returns key–value pairs as tuples.
Unpacking Enables simultaneous access to keys and values.
Tuple as Key Tuples used as immutable dictionary keys.
Tuple in items() Each pair is represented as a tuple (key, value).
Output
10.10 SUMMARY
Tuples enable integer-based indexing and duplicate elements, which improves data
organization and retrieval. They can be defined with or without parentheses; however,
without parentheses, a following comma is required to represent a tuple. Tuples are best used
for their original purpose; misapplication can result in inefficiencies, such as substituting
lists, sets, or dictionaries.
To ensure efficient data processing and manipulation, choose the suitable data structure after
carefully considering the use cases.
Essay Questions
1. Explain the concept of tuples and how they differ from lists.
2. Discuss the advantages of using tuples in Python.
3. Why can tuples be dictionary keys, but lists cannot?
4. Explain the items() method of a dictionary with an example.
5. Write a program to create a phone directory using tuple keys and string values.
Short Notes
1. Write about Class tuple in Python.
2. Explain about Immutability and hashability.
3. How can Tuples as dictionary keys.
4. Describe about Tuple functions and methods.
5. Discuss about the role of items() in dictionary iteration.
1. Explain the concept and features of the Python set data type.
2. Create sets using curly braces {} and the set() constructor.
3. Apply set operators and methods to perform mathematical and logical operations.
4. Differentiate between mutable sets and immutable frozensets.
5. Use sets to remove duplicates, test membership, and compare data collections.
6. Implement real-world problem solutions using set operations and functions in Python.
STRUCTURE
11.1 Introduction
11.2 Characteristics of Sets
11.3 Creating Sets
11.3.1 Using Curly Braces { }
11.3.2 Using the set() Constructor
11.3.3 Creating an Empty Set
11.3.4 Creating a Set from a String
11.4 Accessing Elements in a Set
11.4.1 Iteration
11.4.2 Membership Testing
11.5 Set Operators
11.5.1 Membership and Length
11.5.2 Equality and Comparison
11.5.3 Union, Intersection, Difference, and Symmetric Difference
11.6 Set Methods
11.6.1 Adding Elements using add() and update()
11.6.2 Removing Elements using remove(), discard(), and pop()
11.6.3 Clearing Set Elements using clear()
11.7 Set Relationship Methods
11.7.1 issubset()
11.7.2 issuperset()
11.7.3 isdisjoint()
11.8 Built-in Functions with Sets
11.9 Frozen Sets (Immutable Sets)
11.10 Applications of Sets
11.11 Summary
11.12 Technical Terms
11.13 Self-Assessment Questions
11.14 Suggested Readings
Programming and Problem-Solving … 11.2 Set
11.1 INTRODUCTION
Python’s set data type is another powerful built-in collection class used to store unordered,
unique, and immutable items.
It represents the mathematical concept of a set — a group of elements with no repetitions.
Sets are very useful in programs that involve:
• Duplicate removal (e.g., cleaning data),
• Membership testing (checking if an element exists),
• Mathematical set operations (union, intersection, etc.),
• Fast lookups using hashing.
A set in Python is an unordered collection of unique, immutable objects enclosed in curly
braces {}.
Syntax:
set_name = {element1, element2, element3, ...}
Unlike lists or tuples, sets cannot contain duplicate elements or mutable items (like lists or
dictionaries).
Example – Creating a Simple Set
phonebook1 = {'123-45-67', '234-56-78', '345-67-89'}
print(phonebook1)
print(type(phonebook1))
Output
{'123-45-67', '234-56-78', '345-67-89'}
<class 'set'>
Explanation:
• The curly braces {} indicate a set.
• The order of items may differ since sets are unordered.
• The type() function confirms that it’s a set object.
Handling Duplicates
If a set is defined with duplicate items, Python automatically removes them.
Example
phonebook1 = {'123-45-67', '234-56-78', '345-67-89',
'123-45-67', '345-67-89'}
print(phonebook1)
Centre for Distance Education 11.3 Acharya Nagarjuna University
Output
{'123-45-67', '234-56-78', '345-67-89'}
Why Use Sets?
Purpose Advantage
Duplicate removal Automatically removes repeated entries
Mathematical operations Built-in support for union, intersection, etc.
Fast lookup Membership check is faster than lists
Hashable keys Can use immutable sets (frozensets) as dictionary keys
11.2 CHARACTERISTICS OF SETS
• Unordered: The elements have no fixed order; indexing and slicing are not supported.
• Immutable Elements:Each element inside the set must be an immutable object such as
integers, strings, or tuples.
empty = set()
print(empty)
print(type(empty))
Output
set()
<class 'set'>
{} creates an empty dictionary, not a set.
Output
True
True
11.5 SET OPERATORS
True
True
Example – Union, Intersection, Difference, Symmetric Difference
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B)
print(A & B)
print(A - B)
print(A ^ B)
Output
{1, 2, 3, 4, 5}
{3}
{1, 2}
{1, 2, 4, 5}
Method Description
add(x) Adds an element x.
update(iterable) Adds multiple elements.
remove(x) Removes x; error if not found.
discard(x) Removes x if present, no error otherwise.
pop() Removes and returns a random element.
clear() Removes all elements.
Example – add()
[Link]('123-45-67')
print(phonebook3)
Output
Centre for Distance Education 11.7 Acharya Nagarjuna University
[Link]('green')
print(colors)
Output
{'red', 'blue'}
[Link]()
print(phonebook3)
Output
set()
S = {10, 20}
print(S)
print([Link]())
print(S)
Output
40
Programming and Problem-Solving … 11.8 Set
Method Description
Example
A = {1, 2, 3}
B = {1, 2, 3, 4}
print([Link](B))
print([Link](A))
print([Link]({5, 6}))
Output
True
True
True
Function Purpose
len(s) Number of elements
max(s) Largest element
min(s) Smallest element
sum(s) Sum of numeric elements
sorted(s) Returns sorted list
Centre for Distance Education 11.9 Acharya Nagarjuna University
Example
S = {10, 2, 8, 4}
print(len(S))
print(max(S))
print(min(S))
print(sum(S))
print(sorted(S))
Output
10
24
[2, 4, 8, 10]
Example
A = frozenset([1, 2, 3])
B = frozenset([3, 4, 5])
print(A | B)
print(A & B)
Output
frozenset({1, 2, 3, 4, 5})
frozenset({3})
Programming and Problem-Solving … 11.10 Set
1. Removing Duplicates
numbers = [1, 2, 2, 3, 3, 4]
print(set(numbers))
2. Common Elements
A = {'apple', 'banana'}
B = {'banana', 'mango'}
print(A & B)
3. Filtering Data
text = "Python is powerful and Python is easy"
unique_words = set([Link]())
print(unique_words)
4. Fast Membership Checking
vowels = {'a', 'e', 'i', 'o', 'u'}
print('e' in vowels)
11.11 SUMMARY
Set, Unique Elements, Unordered, Mutable, Immutable Element, Membership Testing, Union,
Intersection, Difference, Symmetric Difference, frozenset, Hashing, Subset, Superset, Disjoint
Set.
6. Demonstrate the use of set relationships such as subset, superset, and disjoint sets with
code snippets.
7. Discuss the advantages and applications of sets in Python programming. Provide at
least three real-life examples.
8. Write a Python program to perform all set operations (union, intersection, difference,
and symmetric difference) on two given sets.
9. Compare the use of sets for duplicate removal versus using lists.
10. Explain how membership testing works in sets and why it is more efficient compared
to lists or tuples.
STRUCTURE
12.1 Introduction
12.2 Character Encodings and Strings
12.2.1 Character Encodings
12.2.2 ASCII
12.2.3 Unicode
12.2.4 UTF-8 Encoding for Unicode Characters
12.3 Working with Encoded Strings in Python
12.4 The random Module
12.4.1 Choosing a Random Integer
12.4.2 Choosing a Random “Real” (Floating Point Value)
12.4.3 Shuffling, Choosing, and Sampling at Random
12.5 Applications of Randomness
12.6 Summary
12.7 Technical Terms
12.8 Self-Assessment Questions
12.9 Suggested Readings
12.1 INTRODUCTION
Two fundamental areas are explored in this chapter:
1. Character Encoding, which defines how text characters are represented as numbers
inside a computer.
2. Randomness and the random Module, which allows programs to behave
unpredictably or simulate random events.
Programming and Problem-Solving … 12.2 Randomness
Every program that processes text must deal with encodings, and every simulation or game that
imitates chance must use randomness. Python provides robust support for both its built-in
Unicode string system and the standard random library.
For example:
Character Decimal Code Binary (8 bits)
A 65 01000001
B 66 01000010
C 67 01000011
Each character corresponds to a unique binary pattern stored in memory or transmitted between
systems.
Without a standard encoding, computers could not exchange text reliably.
12.2.2 ASCII (American Standard Code for Information Interchange)
ASCII was one of the earliest and most influential encoding standards, developed in the 1960s.
It uses 7 bits to represent 128 characters, covering:
• Upper- and lower-case English letters
• Digits 0–9
• Basic punctuation symbols
• Control characters (e.g., newline, tab)
Centre for Distance Education 12.3 Acharya Nagarjuna University
Python’s ord() function returns the code point of a character, and chr() converts a number back
to a character.
print(ord('A')) # 65
print(chr(65)) # 'A'
ASCII served well for English text but failed to handle accented letters or non-Latin scripts.
Program Execution
>>> encoding('dad')
Output
Char Decimal Hex Binary
d 100 64 1100100
a 97 61 1100001
d 100 64 1100100
Programming and Problem-Solving … 12.4 Randomness
Explanation
• ord() returns the Unicode code point (integer) for each character.
For example, ord('d') = 100 and ord('a') = 97.
• format(x, '02x') converts the integer x into a 2-digit hexadecimal string.
o The value 100 in decimal equals 64 in hexadecimal.
• format(x, '08b') converts the integer into an 8-bit binary string.
o For d, this is 1100100.
Each character in 'dad' is thus represented numerically in the computer’s memory, and these
numbers correspond to the ASCII/Unicode encoding values.
Python provides two complementary built-in functions for working with character codes:
Function Description
ord(char) Returns the numeric Unicode code point of the character char.
chr(number) Returns the character that corresponds to the Unicode code point number.
Explanation
• The integer 97 corresponds to the lowercase letter ‘a’ in the Unicode (and ASCII) table.
• 65 corresponds to ‘A’, the uppercase letter.
• 8364 represents the Euro symbol (€).
• 937 corresponds to the Greek capital letter Omega (Ω).
These code points are defined by the Unicode standard, which allows Python to support
characters from virtually every language.
Python 3 strings (str) are Unicode by default, meaning they can represent any text from any
language.
s = "Ωmega "
print(s)
print(len(s))
Output
Ωmega
7
12.2.4 UTF-8 Encoding for Unicode Characters
Unicode specifies code points, but the computer still needs a binary representation for storage
and transmission.
UTF-8 (Unicode Transformation Format – 8-bit) is the most common encoding form used
today.
Features of UTF-8:
1. Variable-length encoding using 1 to 4 bytes.
2. Backward compatible with ASCII (0–127).
3. Efficient for English text, flexible for global scripts.
Character Code Point UTF-8 Bytes (Hex)
A U+0041 41
ñ U+00F1 C3 B1
€ U+20AC E2 82 AC
U+1F60A F0 9F 98 8A
Example
msg = "Café"
b = [Link]('utf-8')
print(b)
print([Link]('utf-8'))
Output
b'Caf\xc3\xa9'
Café
If the wrong encoding is used while decoding, Python raises a UnicodeDecodeError.
Function Description
randrange(start, stop, step) Choose integer from a range.
getrandbits(k) Return integer with k random bits.
Example
print([Link](0, 10, 2)) # Even numbers 0–8
print([Link](8)) # Random 8-bit number
Example:
import random
print("Simulating 10 dice rolls:")
for i in range(10):
print([Link](1, 7))
Output
Simulating 10 dice rolls:
3
5
6
2
4
1
2
6
5
3
Example – Implementing a Number Guessing Game
The following program implements a simple interactive number guessing game using
Python’s random module.
The program randomly chooses a number between 0 and n - 1 and repeatedly asks the user to
guess it.
Each time the player guesses incorrectly, the program prints a hint:
• “Too low.” if the guess is smaller than the secret number.
• “Too high.” if the guess is larger.
When the player guesses correctly, the program prints “You got it.” and stops.
Centre for Distance Education 12.9 Acharya Nagarjuna University
while True:
# Step 2: Ask user for a guess
user_input = input("Enter your guess: ")
# Validate input
if not user_input.isdigit():
print("Please enter a valid integer.")
continue
guess_num = int(user_input)
winners = [Link](lottery, 6)
print("Winning numbers:", winners)
Output
Winning numbers: [7, 18, 25, 33, 42, 49]
Output
Estimated π: 3.1416
Programming and Problem-Solving … 12.12 Randomness
12.6 SUMMARY
• Character encoding maps characters to numeric code points.
• ASCII encodes 128 characters using 7 bits.
• Unicode extends this to global scripts; UTF-8 is the common binary encoding.
• Python 3 strings are Unicode by default.
• The random module generates pseudorandom integers, floats, and selections.
• Functions such as randint(), random(), choice(), and shuffle() provide flexible
randomization.
• Randomness supports games, simulations, and statistical modeling.
Short Notes
1. Code Points and Bytes
2. ord() and chr() functions
3. Unicode in Python 3
4. [Link]() vs [Link]()
5. [Link]() and [Link]()
Centre for Distance Education 12.13 Acharya Nagarjuna University
STRUCTURE
13.1 Introduction – Fundamental Concepts
13.2 Defining a New Python Class
13.2.1 Methods of Class Point
13.2.2 A Class and Its Namespace
13.2.3 Every Object Has an Associated Namespace
13.2.4 Implementation of Class Point
13.2.5 Instance Variables and Class Variables
13.2.6 Class Definition, More Generally
13.2.7 Documenting a Class (Docstrings)
13.3 Examples of User-Defined Classes
13.3.1 Overloaded Constructor Operator
13.3.2 Default Constructor
13.3.3 Playing Card Class
13.4 Designing New Container Classes
13.4.1 Class Deck of Cards
13.4.2 Queue Container Class
13.5 Overloaded Operators
13.5.1 Operators Are Class Methods
13.5.2 Making the Class Point User Friendly
13.5.3 Contract between Constructor and repr()
Programming and Problem-Solving … 13.2 Object Oriented Programming
Instead of writing functions that act on global data, OOP organizes related data and operations
within classes.
Core OOP Concepts
Concept Description
Class Blueprint defining the structure and behavior of objects.
Object (Instance) Individual entity created from a class.
Encapsulation Bundling of data and related methods into one unit.
Abstraction Hiding implementation details, showing only relevant features.
Inheritance Creating new classes that reuse attributes and methods of existing ones.
Polymorphism Ability to use the same operation on objects of different types.
13.2 DEFINING A NEW PYTHON CLASS
A Python class is defined using the keyword class, followed by the class name and a colon.
class Point:
"""Represents a point in 2D space."""
Centre for Distance Education 13.3 Acharya Nagarjuna University
def display(self):
print(f"({self.x}, {self.y})")
p = Point(2, 3)
[Link](1, 2)
[Link]()
Output
(3, 5)
13.2.2 A Class and Its Namespace
Each class defines a namespace, a mapping of names to objects—variables, constants, and
methods—local to the class.
Programming and Problem-Solving … 13.4 Object Oriented Programming
def __repr__(self):
return f"Point({self.x}, {self.y})"
p1 = Point(1, 1)
p2 = Point(3, 4)
print(p1, p2)
print("Number of points:", [Link])
Output
Point(1, 1) Point(3, 4)
Number of points: 2
Instance variables are attributes that are unique to each object created from a class.
They are defined using the prefix self. inside class methods (most commonly within the
constructor __init__()).
Example
class Student:
def __init__(self, name, rollno):
[Link] = name # instance variable
[Link] = rollno # instance variable
Centre for Distance Education 13.5 Acharya Nagarjuna University
s1 = Student("Asha", 101)
s2 = Student("Rahul", 102)
Explanation:
• [Link] and [Link] are instance variables.
• Each object (s1, s2) has its own copy of these variables.
• Changing [Link] does not affect [Link].
[Link] = "Anita"
print("Updated s1:", [Link])
print("Unchanged s2:", [Link])
Output
Updated s1: Anita
Unchanged s2: Rahul
Class variables are attributes that belong to the class itself, not to any individual instance.
They are declared outside all methods but inside the class definition.
Example
class Student:
school_name = "Greenwood High" # class variable
s1 = Student("Asha", 101)
s2 = Student("Rahul", 102)
Programming and Problem-Solving … 13.6 Object Oriented Programming
Output
Student 1 School: Greenwood High
Student 2 School: Greenwood High
Accessing through class: Greenwood High
Explanation:
• school_name is a class variable, shared by all objects.
• Any change made through the class name affects all objects.
Student.school_name = "Sunrise Academy"
print(s1.school_name)
print(s2.school_name)
Output
Sunrise Academy
Sunrise Academy
Table 13.1 Comparative Summary
Feature Instance Variable Class Variable
Defined in Inside methods using self. Inside class, outside methods
Belongs to Each object (instance) The class (shared by all instances)
Accessed object_name.variable [Link] or
using object_name.variable
Storage Separate copy for every object Single shared copy for all
Use case To store unique attributes for each To store common attributes across all
instance objects
Example
class Point:
count = 0 # class variable (shared)
p1 = Point(1, 2)
p2 = Point(3, 4)
def method1(self):
# perform operation
Purpose
The goal of an overloaded constructor is to:
• Allow flexible object creation, depending on the data available at runtime.
• Enable objects to be initialized with different numbers or types of parameters.
• Simplify class usage by adapting to various initialization contexts.
General Syntax
class ClassName:
def __init__(self, param1=None, param2=None, ...):
Centre for Distance Education 13.9 Acharya Nagarjuna University
# initialization code
Here:
• Default values (None) make parameters optional.
• The constructor adapts based on which arguments are provided
Example – Constructor with Default Parameters
class Circle:
def __init__(self, radius=1):
[Link] = radius
c1 = Circle()
c2 = Circle(5)
print([Link], [Link])
Output
15
Example – Constructor with Conditional Logic
In some situations, the constructor must behave differently based on argument type or
number.
class Student:
def __init__(self, name=None, marks=None):
if name is not None and marks is not None:
[Link] = name
[Link] = marks
elif name is not None:
[Link] = name
[Link] = 0
else:
[Link] = "Unknown"
[Link] = 0
def display(self):
print(f"Name: {[Link]}, Marks: {[Link]}")
Program Execution
s1 = Student("Asha", 85)
Programming and Problem-Solving … 13.10 Object Oriented Programming
s2 = Student("Rahul")
s3 = Student()
[Link]()
[Link]()
[Link]()
Output
Name: Asha, Marks: 85
Name: Rahul, Marks: 0
Name: Unknown, Marks: 0
Explanation:
• The same constructor handles three different initialization cases.
• The if-elif-else structure allows overloaded behavior within a single __init__() method
Example – Constructor Using Variable-Length Arguments
You can also simulate overloading using *args (for positional arguments) and **kwargs (for
keyword arguments).
class Rectangle:
def __init__(self, *args):
if len(args) == 0:
[Link] = 1
[Link] = 1
elif len(args) == 1:
[Link] = [Link] = args[0]
elif len(args) == 2:
[Link], [Link] = args
else:
raise TypeError("Too many arguments")
def area(self):
return [Link] * [Link]
Program Execution
r1 = Rectangle() # 1x1
Centre for Distance Education 13.11 Acharya Nagarjuna University
r2 = Rectangle(4) # 4x4
r3 = Rectangle(4, 6) # 4x6
[Link] = suit
def __repr__(self):
return f"{[Link]} of {[Link][[Link]]}"
c = Card('Ace', 0)
print(c)
Output
Ace of Hearts
Concept Illustration
Think of a container as a box that holds multiple items.
Each item can be:
• A number,
Programming and Problem-Solving … 13.14 Object Oriented Programming
• A string,
• Or even another object (instance of a class).
We don’t interact with individual items directly; instead, we interact with the container using
its methods.
[Link](num)
def display(self):
print("Numbers in container:", [Link])
Program Execution
c = NumberContainer()
[Link](10)
[Link](20)
[Link](30)
[Link]()
[Link](20)
[Link]()
Output
Numbers in container: [10, 20, 30]
Numbers in container: [10, 30]
Explanation
• The class NumberContainer maintains a list of numbers internally ([Link]).
• Methods such as add(), remove(), and display() allow controlled access to that list.
• Users of the class don’t directly manipulate the list — they call methods instead,
achieving encapsulation.
def draw(self):
return [Link]()
deck = Deck()
print([Link]())
Output
7 of Clubs
def dequeue(self):
if not [Link]:
print("Queue empty.")
return None
return [Link](0)
13.6 INHERITANCE
13.6.1 Inheriting Attributes of a Class
A subclass inherits attributes and methods from its superclass.
class Animal:
def speak(self):
print("Animal speaks")
Programming and Problem-Solving … 13.18 Object Oriented Programming
class Dog(Animal):
def bark(self):
print("Woof!")
d = Dog()
[Link]()
[Link]()
Output
Animal speaks
Woof!
class Dog(Animal):
Centre for Distance Education 13.19 Acharya Nagarjuna University
class Cat(Animal):
def speak(self): # overriding superclass method
print("The cat meows.")
Program Execution
a = Animal()
d = Dog()
c = Cat()
[Link]()
[Link]()
[Link]()
Output
The animal makes a sound.
The dog barks.
The cat meows.
13.6.3 Extending Superclass Methods
class Cat(Animal):
def speak(self):
super().speak()
print("Cat meows")
Output
Animal speaks
Cat meows
def dequeue(self):
if len(self)==0:
raise IndexError("Empty queue")
return [Link](0)
class Queue(list):
def dequeue(self):
if not self:
raise QueueEmpty("Cannot dequeue from empty queue")
return [Link](0)
Example
q = Queue()
try:
[Link]()
except QueueEmpty as e:
print("Error:", e)
Output
Error: Cannot dequeue from empty queue
13.8 SUMMARY
• OOP organizes code around objects that contain data and methods.
• Classes define the blueprint; objects are instances.
• Constructors (__init__) initialize object state.
• Operator overloading enables intuitive behavior (+, ==, etc.).
• Inheritance promotes code reuse and hierarchy.
• User-defined exceptions provide customized error handling.
Centre for Distance Education 13.21 Acharya Nagarjuna University
1. Explain the fundamental principles of OOP and their importance in software design.
2. Define a Python class with example code and explain its components.
3. What is the difference between class variables and instance variables?
4. How can we overload operators in Python? Illustrate with an example.
5. Discuss inheritance and method overriding with code examples.
6. Explain the design of a Queue or Deck container class.
7. Define and raise a user-defined exception.
8. What is the relationship between repr() and the constructor?
Short Answer Questions
1. What is encapsulation?
2. Give syntax of a Python class.
3. What are dunder (double-underscore) methods?
4. What is the purpose of __init__()?
5. Define polymorphism in your own words.
6. What is the output of repr() vs str()?
7. How is inheritance implemented in Python?
8. Difference between built-in and user-defined exceptions.
STRUCTURE
14.1 Introduction
14.2 Software Objects
14.2.1 What is an Object?
14.2.2 Object References
14.2.3 Garbage Collection
14.2.4 List Assignment and Copying
14.3 Turtle Graphics
14.3.1 Creating a Turtle Graphics Window
14.3.2 Turtle Position and Movement
14.3.3 Pen Attributes and Colors
14.3.4 Shapes, Sizes, and Speed
14.3.5 Multiple Turtles and Animation
14.4 Case Study – Horse Race Simulation
14.5 Modular Design
14.5.1 Modules and Top-Down Design
14.5.2 Python Modules and Importing
14.6 Summary
14.7 Technical Terms
14.8 Self-Assessment Questions
14.9 Suggested Readings
Programming and Problem-Solving … 14.2 Objects and Their Uses
14.1 INTRODUCTION
In imperative programming, functions are the basic building blocks of a program.
In object-oriented programming (OOP), however, objects become the fundamental units of
design, combining both data (attributes) and behavior (methods).
The concept of “objects” originated in computer simulation, where real-world entities such as
cars, students, or bank accounts were modeled in software.
In the early 1970s, Alan Kay at Xerox PARC developed the programming language Smalltalk,
introducing object-oriented programming as we know it. This idea later inspired the
development of graphical user interfaces (GUIs) and languages such as Python, Java, and C++.
505498136
Both have the same memory location, showing that n and k refer to the same object.
14.2.3 Memory Management and Garbage Collection
When no variable references an object anymore, Python automatically deallocates its memory
through a process called garbage collection.
Example:
n = 20
n = 40 # old value 20 no longer referenced
After this, the object 20 is marked for garbage collection and its memory becomes reusable.
list2 = list(list1)
To copy nested lists completely, use:
import copy
list3 = [Link](list1)
move forward, turn, change color, and even draw shapes, all by calling its methods. This
system allows beginners to visualize program execution and directly see how object-oriented
commands affect an object’s state.
Concept of the Turtle Object
In Python, the turtle module provides a built-in Turtle class.
When we create a new turtle using:
import turtle
t = [Link]()
we are instantiating an object from the Turtle class.
This t object has attributes (such as position, direction, color, and pen state) and methods (like
forward(), left(), and circle()).
Each turtle object operates independently, allowing you to create multiple turtles on the same
screen.
Advantages of Using Turtle Graphics
1. Provides an intuitive, visual approach to understanding programming logic.
2. Encourages experimentation and creativity.
3. Demonstrates object behavior (state, methods, and encapsulation).
4. Useful for teaching loops, conditionals, and functions through graphical tasks.
5. Allows multiple objects (turtles) to illustrate interactions and concurrency.
Turtle Graphics in Python:
• Uses objects and methods to represent motion and drawing.
• Makes abstract programming concepts visual and interactive.
• Provides a practical introduction to object-oriented design through creativity and play.
• It bridges the gap between logic and visualization, making it an ideal educational tool
for new programmers.
14.3.1 Creating a Turtle Graphics Window
Turtle graphics is a fun way to introduce programming and OOP through graphics.
It uses a “turtle” that moves around a screen, drawing lines as it goes.
import turtle
[Link](800, 600)
window = [Link]()
[Link]("My Turtle Window")
A turtle screen of 800×600 pixels is created, titled “My Turtle Window”.
Centre for Distance Education 14.7 Acharya Nagarjuna University
[Link](100, 100)
The turtle moves to position (100,100), drawing a line if its pen is down.
Relative movement is done using methods such as:
[Link](100)
[Link](90)
This allows shapes such as squares to be [Link] – Drawing a Square
for i in range(4):
[Link](100)
[Link](90)
the pen to draw thick green lines. The fill color used to shade shapes can be controlled with
fillcolor() and activated using begin_fill() and end_fill().
These attributes enable the creation of colorful and detailed designs, making programs both
interactive and visually engaging. Managing pen attributes reinforces the concept of object state
in object-oriented programming — the turtle object “remembers” its current pen color, width,
and state, and every drawing action reflects these properties.
• Pen up / down:
penup() and pendown() toggle drawing.
• Line width:
pensize(5) sets the line width in pixels.
• Color:
pencolor('blue') or pencolor(255, 0, 0) (if using RGB mode).
[Link]('green')
[Link](4)
[Link](120)
Example – Drawing a Colored Triangle with Pen Attributes
The following example demonstrates how pen color, fill color, and line width can be controlled
to create an attractive filled triangle using the turtle graphics module.
import turtle
t = [Link]()
[Link](4) # Set line thickness
[Link]("blue") # Set outline color
[Link]("yellow") # Set fill color
t.begin_fill() # Start filling the shape
for i in range(3): # Draw an equilateral triangle
[Link](150)
[Link](120)
t.end_fill() # Complete the fill
[Link]()
[Link]()
Output Description:
A blue-bordered triangle filled with yellow color is drawn at the center of the screen. The thick
border is a result of setting the pen size to 4 pixels.
Programming and Problem-Solving … 14.10 Objects and Their Uses
This simple example illustrates how pen attributes affect both the appearance and quality of
graphical output, while reinforcing the object-oriented nature of the turtle — every visual
change is a result of sending commands (messages) to the turtle object to modify its internal
drawing state.
def startRace(horses):
finish = 300
while True:
for h in horses:
[Link]([Link](1, 5))
if [Link]() >= finish:
print([Link](), "wins!")
return
screen = [Link]()
colors = ['red', 'blue', 'green', 'orange', 'purple']
horses = [createHorse(-300, i * 50, colors[i]) for i in range(5)]
startRace(horses)
[Link]()
Output:
Turtles race across the screen, and the color of the winning turtle is printed in the console.
Programming and Problem-Solving … 14.12 Objects and Their Uses
Pytbon Code:
# [Link]
from power import ElectricalSystem
from control import CommunicationSystem
def main():
print("Vehicle Control Simulation Starting...")
power = ElectricalSystem()
comms = CommunicationSystem()
[Link]()
[Link]()
print("System Operational.")
if __name__ == "__main__":
main()
# [Link]
class ElectricalSystem:
def activate(self):
print("Electrical System Activated.")
# [Link]
class CommunicationSystem:
def initialize(self):
print("Communication System Initialized.")
Output:
Vehicle Control Simulation Starting...
Electrical System Activated.
Communication System Initialized.
System Operational.
This modular approach is fundamental to object-oriented programming, where each class and
module models a real-world component with clearly defined attributes and behaviors.
Modular design allows large programs to be broken down into manageable size parts, in which
each part (module) provides a clearly specified capability. It aids the software development
process by providing an effective way of separating programming tasks among various
individuals or teams. It allows modules to be individually developed and tested, and eventually
integrated as a part of a complete system. Finally, modular design facilitates program
modification since the code responsible for a given aspect of the software is localized in a small
number of modules, and not distributed through various parts of the program.
Creating a Module
# file: math_utils.py
def square(x):
return x * x
Using the Module
import math_utils
print(math_utils.square(4))
Output
16
Selective Importing :
from math_utils import square
print(square(5))
14.6 SUMMARY
• Objects combine data and methods into a single entity.
• Variables store references to objects, not the objects themselves.
• Garbage collection reclaims unused memory automatically.
• The turtle module provides a visual introduction to object behavior.
• Modules and top-down design promote reusable, structured programming.
Essay Questions
1. Explain the concept of software objects in Python.
2. Describe how garbage collection works.
3. Write a program using turtle graphics to draw a star.
4. Explain the importance of modular programming in Python.
Short Notes
1. Turtle attributes and shapes
2. Object references and id() function
3. Difference between shallow and deep copy
4. Advantages of using modules
STRUCTURE
In a recursive process, each call solves a simpler subproblem, and the recursion continues until
a base case is reached — a condition where the problem can be solved directly without further
recursive calls.
Formally, recursion divides a problem into:
1. Base case – A stopping condition that prevents infinite recursion.
2. Recursive case – The part where the function calls itself to solve a smaller problem.
How does this code implement the function countdown() for input value n > 0? The
insight used in the code is this: Counting down from (positive number) n can be done by
printing n first and then counting down from n 1. This fragment of code is called the
recursive step. With the two cases resolved, we obtain the recursive function:
def countdown(n):
'counts down to 0'
if n <= 0: # base case
print('Blastoff!!!')
else: # n > 0: recursive step
print(n) # print n first and then
countdown(n-1) # count down from n-1
A recursive function that terminates will always have:
1. One or more base cases, which provide the stopping condition for the recursion. In
function countdown(), the base case is the condition n ≤ 0, where n is the input.
2. One or more recursive calls, which must be on arguments that are “closer” to the
base case than the function input. In function countdown(), the sole recursive call
is made on n 1, which is “closer” to the base case than input n.
def cheers(n):
"""Prints 'Hip ' n times followed by 'Hurray!!!' using recursion."""
if n <= 0: # base case
print("Hurray!!!")
else:
print("Hip ", end='') # print prefix without newline
cheers(n - 1) # recursive call
How it works
• Base case: when n <= 0 the function prints the final word Hurray!!! and stops.
• Recursive case: when n > 0 it prints the prefix Hip (note the trailing space) and
recursively calls cheers(n-1).
The printed prefixes accumulate (left-to-right) because each call prints one Hip before
delegating the remainder.
Programming and Problem-Solving … 15.4 Recursion
Examples (interactive)
>>> cheers(0)
Hurray!!!
>>> cheers(1)
Hip Hurray!!!
>>> cheers(4)
Hip Hip Hip Hip Hurray!!!
Complexity
• Time: O(n) — one recursive call per Hip printed.
• Space: O(n) call-stack depth (recursion frames).
• If you prefer to return the string instead of printing, you can implement a version that
builds and returns the string (useful for testing).
• If you expect negative inputs and want them handled differently, replace the if n <= 0:
guard with if n == 0: and raise an error for n < 0.
Recursive Function Calls and the Program Stack:
def vertical(n):
"""Prints the digits of n vertically."""
if n < 10: # base case: single-digit number
print(n)
else: # recursive case
vertical(n // 10) # print all but the last digit
print(n % 10) # print the last digit
Explanation
The function vertical(n) prints each digit of the integer n on a separate line, from most
significant digit to least significant digit.
It uses recursion to repeatedly reduce the number by removing its last digit until only one digit
remains — the base case.
• Base Case:
If n is a single-digit number (n < 10), simply print it.
• Recursive Case:
If n has two or more digits:
Centre for Distance Education 15.5 Acharya Nagarjuna University
1. Call vertical(n // 10) — this discards the last digit and recursively prints the
remaining digits.
2. After returning from recursion, print the last digit using print(n % 10).
Example Execution
>>> vertical(348)
Output:
3
4
8
Recursion is best understood through simple, familiar problems that can naturally be defined in
terms of smaller versions of themselves. Classic examples include the computation of a
factorial, the sum of natural numbers, the Fibonacci sequence, and countdown functions.
Programming and Problem-Solving … 15.6 Recursion
Each of these problems follows a common recursive structure: a base case that directly
provides an answer and a recursive case that reduces the problem toward that base case. For
example, the factorial function can be expressed as n! = n × (n−1)!, where the base case is 0! =
1. Similarly, the Fibonacci series is defined as F(n) = F(n−1) + F(n−2), where the sequence
builds upon previously computed results. Recursive functions like countdown(n) or sum_n(n)
repeatedly call themselves with a smaller input until the simplest instance of the problem is
reached.
These examples illustrate the self-referential nature of recursion—each function call handles
part of the work and delegates the rest to a smaller, identical subproblem. Through this process,
recursion converts complex problems into simpler ones, demonstrating how powerful and
elegant recursive thinking can be when applied to mathematical and algorithmic problem-
solving.
and by definition, 0! = 1.
Recursive Implementation
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
Example:
print(factorial(5))
Output:
120
Explanation:
Each recursive call computes n * factorial(n-1) until the base case n==0 is reached.
15.2.2 Sum of Natural Numbers
Recursive definition:
def sum_n(n):
if n == 0:
return 0
Centre for Distance Education 15.7 Acharya Nagarjuna University
else:
return n + sum_n(n - 1)
Example:
sum_n(5) = 5 + 4 + 3 + 2 + 1 = 15
15.2.3 Fibonacci Sequence
The Fibonacci sequence is defined recursively as:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
Output:
fibonacci(6) → 8
Example Execution
>>> pattern(4)
Output:
43211234
Programming and Problem-Solving … 15.8 Recursion
def drawKoch(n):
"""Draws the nth Koch curve using turtle graphics."""
s = Screen() # Create drawing window
t = Turtle() # Create turtle
[Link](0) # Set fastest drawing speed
[Link]()
[Link](-150, 0) # Position turtle for drawing
[Link]()
directions = koch(n) # Obtain recursive directions
for move in directions: # Interpret each command
if move == 'F':
[Link](300 / (3 ** n)) # Move forward, scaled to recursion level
elif move == 'L':
[Link](60) # Turn left 60 degrees
elif move == 'R':
[Link](120) # Turn right 120 degrees
[Link]() # Keep window open
# Example: draw Koch curve of level 3
drawKoch(3)
Recursive functions can be analyzed in terms of time complexity and space complexity.
• Factorial function: O(n) – One recursive call per level.
• Fibonacci function: O(2ⁿ) – Exponential growth due to repeated subproblems.
• Binary search: O(log n) – Divides problem size by 2 each step.
Each recursive call adds a new activation record to the call stack, consuming additional
memory.
Thus, recursion provides elegant solutions but can become inefficient without optimization
(e.g., memoization).
Koch curves Run Time Analysis
• Each level of recursion produces 4ⁿ segments.
Programming and Problem-Solving … 15.10 Recursion
Recursion is widely used in search algorithms such as linear and binary search.
In its recursive form, the function checks one element per recursive call, reducing the problem
size by one at each step — just like iterative looping but using the call stack instead of explicit
loop control.
The recursive linear search function works as follows:
1. Base Case:
If the list is empty or the search index has reached the end, the element is not found —
return -1.
2. Recursive Case:
Compare the target element with the current list element.
o If they match, return the current index.
o Otherwise, make a recursive call on the rest of the list (or increment the index).
Example:
binary_search([1,3,5,7,9,11], 7, 0, 5) → 3
Complexity: O(log n)
Recursive binary search demonstrates the power of recursion to simplify complex logic —
instead of using multiple loop conditions, it expresses the solution as repeated self-calls on
progressively smaller [Link] is a cornerstone example of how recursion can combine
mathematical elegance with computational efficiency.
Example:
gcd(48, 18) → 6
Complexity: O(log n)
Recursion forms the foundation of functional programming, where problems are solved by
defining functions in terms of themselves rather than changing state or using loops.
In Python, recursion aligns with a declarative approach — describing what to do, not how to
do it.
Key features:
• Functions are pure (no side effects).
• Emphasis on mathematical definition.
• No use of mutable variables.
• Enables higher-order functions such as map(), filter(), and reduce().
Example:
def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)
Here, recursion replaces iteration naturally, making the function concise and closer to its
mathematical definition.
Concept of Map–Reduce
The Map–Reduce model divides computation into two primary phases:
Centre for Distance Education 15.15 Acharya Nagarjuna University
1. Map Phase:
A function is applied independently to each element in a collection (list, tuple, etc.).
The result is a new list containing the function’s output for each input element.
This corresponds to mapping a function over data — similar to recursion over lists
where each recursive call processes one element.
2. Reduce Phase:
The results of the map phase are combined into a single cumulative value using a
reducer function.
This process recursively collapses multiple results into one — for example, summing a
list of numbers or concatenating strings.
Sequential Map–Reduce Example (Word Counting)
The Map–Reduce framework processes data in two main phases — map and reduce —
following the functional programming and recursive problem-solving approach.
In this example:
>>> words = ['two', 'three', 'one', 'three', 'three', 'five', 'one', 'five']
>>> smr = SeqMapReduce(occurrence, occurrenceCount)
>>> [Link](words)
[('one', 2), ('five', 2), ('two', 1), ('three', 3)]
1. Map Phase:
Each word is mapped into a key–value pair — (word, 1) — representing one
occurrence.
Example: ('three', 1)
2. Group Phase:
Intermediate pairs are grouped by key:
{'one': [1,1], 'three': [1,1,1], 'five': [1,1], 'two': [1]}
3. Reduce Phase:
The reducer function sums each list of values to count occurrences.
Final result:
[('one', 2), ('five', 2), ('two', 1), ('three', 3)]
This example demonstrates the recursive nature of Map–Reduce — the map phase applies a
function to each element independently (like recursive traversal), and the reduce phase
combines results cumulatively (like recursive aggregation).
Thus, Map–Reduce models functional recursion — dividing, processing, and recombining
data efficiently.
Programming and Problem-Solving … 15.16 Recursion
Short Notes
1. Base case and recursive case
2. Functional programming and recursion
3. Binary search using recursion
4. Tail recursion
The aim of this lesson is to explain how Python manages names, variables, and their visibility
through namespaces, and how encapsulation supports modular design, error handling, and
code reuse.
STRUCTURE
16.1 Introduction
16.2 Encapsulation in Functions
16.2.1 Code Reuse
16.2.2 Modularity (Procedural Decomposition)
16.2.3 Encapsulation (Information Hiding)
16.2.4 Local Variables
16.2.5 Namespaces Associated with Function Calls
16.2.6 Namespaces and the Program Stack
16.3 Global versus Local Namespaces
16.3.1 Global Variables
16.3.2 Local Scope
16.3.3 Global Scope
16.3.4 Changing Global Variables Inside a Function
16.4 Exceptional Control Flow
16.4.1 Exceptions and Exceptional Control Flow
16.4.2 Catching and Handling Exceptions
16.4.3 Catching Exceptions of a Given Type
16.4.4 Multiple Exception Handlers
Programming and Problem-Solving … 16.2 Namespaces
16.1 INTRODUCTION
Every Python program consists of a collection of names (variables, functions, lasses, etc.)
that refer to objects in [Link] association between a name and its corresponding object
is stored in a structure called a namespace.
print(area_circle(5))
Centre for Distance Education 16.3 Acharya Nagarjuna University
This function can be reused anywhere, without redefining its logic — an example of code
reuse through encapsulation.
In the example below, two functions are defined:
• jump() — performs a single well-defined action: move the turtle without drawing.
• emoticon() — uses jump() and other turtle commands to draw a complete smiley
face.
This structure illustrates how encapsulation enables clarity, reusability, and abstraction in
Python programs.
# Draw head
jump(t, x, y)
[Link](100)
# Draw smile
jump(t, x - 60.62, y + 65)
[Link](-60)
[Link](70, 120)
Explanation of Encapsulation
1. Encapsulated Helper Function (jump)
o Handles only one responsibility: repositioning the turtle without leaving a
trace.
o By defining it once, this logic can be reused anywhere, rather than repeating
pen-up and pen-down commands in multiple places.
Programming and Problem-Solving … 16.4 Namespaces
Program Output
When executed with:
import turtle
t = [Link]()
emoticon(t, 0, 0)
[Link]()
The output is a smiley face drawn on the screen, with circular head, two eyes, and a curved
smile.
Modularity means breaking a large problem into smaller, more manageable procedures.
Each function handles a single responsibility, which collectively contributes to solving the
overall problem.
For example:
def input_data():
return int(input("Enter value: "))
def process_data(x):
return x * 2
def display_result(result):
print("Result:", result)
Each function has a clear boundary and can be modified independently — an essential
property of modular design.
The function jump() is independent of the function emoticon() and can be tested and
debugged independently. Once function jump() has been developed, the function emoticon()
is easier to implement.
for i in range(5):
total += i
return total
print(compute_sum())
Here, the variable total exists only within the function and is not visible outside.
This is achieved through local namespaces.
The developer of the function emoticon() does not need to know how function jump() works,
just that it lifts turtle t and drops it at coordinates (x, y). This simplifies the process of
developing function emoticon(). Another benefit of encapsulation is that if the
implementation of function jump() changes (and is made more efficient, for example), the
function emoticon() would not have to change.
16.2.4 Local Variables and Namespaces
When a function executes, Python creates a local namespace to store its variables.
Each function call gets its own local namespace, which disappears after the function returns.
def example():
x = 10 # local variable
print(x)
example()
print(x) # NameError: x is not defined
This ensures that variables inside a function are encapsulated and do not affect other parts of
the program.
Here:
• z is local to inner().
• y is enclosing (outer function).
• x is global.
Fig 16.1 Python manages these namespaces automatically using the call stack.
The following code demonstrates how functions create their own namespaces and how
Python manages function calls using the program stack.
Program Code
def h(n):
print('Start h')
print(1 / n)
print(n)
def g(n):
print('Start g')
h(n - 1)
print(n)
def f(n):
print('Start f')
g(n - 1)
print(n)
f(3)
Program Output
Start f
Start g
Start h
0.5
2
2
3
Variables defined inside a function exist only while that function is executing.
def func():
local_var = "inside"
print(local_var)
func()
# print(local_var) → Error: not defined
Local variables improve safety by preventing unexpected interference.
Example:
total = 5
def add():
global total
total += 10
add()
print(total) # Output: 15
Without the global keyword, Python treats total as a local variable, leading to an
UnboundLocalError.
Example:
def f(b):
global a # all references to 'a' inside f() refer to the global variable 'a'
a=6 # modifies the global variable 'a'
return a * b # uses the global 'a'
In Python, when an error occurs during program execution, an exception object is created.
The term exception comes from the fact that an exceptional event has occurred — one that
causes the program’s normal flow of execution to be interrupted.
Normally, a program follows a predictable control flow, proceeding step by step according to
the logic defined in its functions and loops. However, when an error arises — such as
dividing by zero, accessing an invalid index, or opening a missing file — Python creates an
exception object to represent this error condition.
Programming and Problem-Solving … 16.10 Namespaces
Once the exception object is created, the regular (normal) control flow is suspended, and the
program enters a separate path known as the exceptional control flow.
This control flow is not part of the usual sequence of operations and typically isn’t
represented in the program’s flowchart because it occurs only when an unexpected event
happens.
If the exception is not handled by the programmer using a try–except statement, Python’s
default exceptional control flow takes over:
16.4.1 Introduction
Sometimes, unexpected events occur during program execution — such as dividing by zero,
opening a missing file, or invalid user input.
These events cause exceptions that alter the program’s normal control flow.
In Figure 16.4 , we illustrate what happens when we make the function call f(2) from the
[Link] execution runs normally all the way to function call h(0). During the execution of
h(0), the value of n is 0. Therefore, an error state occurs when the expression 1/n is evaluated.
The interpreter raises a ZeroDivisionError exception and creates a ZeroDivisionError
exception object that contains information about the error.
except:
# except block --- executed only if an exception
# is raised while executing the try block
print('Enter your age using digits 0-9!')
If no except block is defined, Python’s default exception handler terminates the program
and prints a traceback.
Enter your age: fifteen
Traceback (most recent call last):
Programming and Problem-Solving … 16.12 Namespaces
except ValueError:
# except block — executed only if a ValueError occurs
print('Enter your age using digits 0-9!')
Example 1 — Valid Input
Enter your age: 22
You are 22 years old.
No exception occurs; the except block is skipped.
except ValueError:
# raised if input cannot be converted to an integer
print('Enter both numbers using digits 0-9!')
except ZeroDivisionError:
# raised if denominator is zero
print('Cannot divide by zero! Please enter a nonzero denominator.')
except:
# handles any other unexpected exceptions
print('An unexpected error occurred.')
Example 1 — Valid Input
Enter the numerator: 10
Enter the denominator: 2
Result = 5.0
Normal execution; no exception occurs.
This enforces controlled error management and promotes robust software design.
16.5 MODULES AS NAMESPACES
module to describe a file containing Python code. When the module is executed (imported),
then the module is (also) a namespace. This namespace has a name, which is the name of the
module. In this namespace will live the names that are defined in the global scope of the
module: the names of functions, values, and classes defined in the module. These names are
all referred to as the module’s attributes.
The module where execution begins is treated as the top-level module (with name
'__main__').
Its global namespace becomes the program’s primary namespace.
A namespace is associated with every class. Python uses namespaces in a clever way to
implement classes and class methods.
Each class in Python defines its own namespace, storing attributes (variables) and methods
(functions).
class Student:
school = "ANU" # class variable
def __init__(self, name):
[Link] = name # instance variable
school belongs to the class namespace, while name belongs to the object’s namespace.
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__',
...,
'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
16.7 SUMMARY
• Namespaces organize names and prevent conflicts.
• Local and global scopes define variable visibility.
• Encapsulation hides details and promotes modular design.
• Exceptions control abnormal program flow.
• Modules and classes provide hierarchical namespaces for large programs.
1. Define namespace.
2. What is encapsulation and how does it improve modularity?
3. Explain the difference between local and global variables.
4. What is the LEGB rule for variable lookup?
5. Write an example demonstrating try and except.
6. What happens during the import process?
7. Explain how a class serves as a namespace.
8. Discuss the importance of exception handling in robust programming.
STRUCTURE
17.1 Introduction
17.2 Basics of tkinter GUI Development
17.2.1 tkinter Overview
17.2.2 Main Window and Event Loop
17.2.3 Common Widgets
17.2.4 Geometry Management
17.2.5 Example: Simple Login Window
17.3 Event-Based tkinter Widgets
17.3.1 Event Handling and Callbacks
17.3.2 Keyboard and Mouse Events
17.3.3 Example: Interactive Counter
17.4 Designing GUIs
17.4.1 GUI Design Principles
17.4.2 Steps in GUI Design
17.4.3 Example: Temperature Converter
17.5 OOP for GUIs
17.5.1 Class-Based GUI Design
17.5.2 Advantages of OOP in GUI Design
17.6 Case Study: Developing a Calculator
17.6.1 Program Design
17.6.2 Implementation
17.6.3 Output
17.7 Summary
17.8 Technical Terms
17.9 Self-Assessment Questions
17.10 Suggested Readings
Programming and Problem-Solving … 17.2 Graphical User Interfaces (Gui)
17.1 INTRODUCTION
Most programs so far have used text-based input and output, where users type commands and
read printed responses.
However, modern applications use graphical user interfaces (GUIs) — windows with buttons,
menus, labels, and other interactive components.
A GUI allows users to interact with programs visually, making software more intuitive and
user-friendly.
Python provides a standard GUI toolkit called tkinter, which supports event-driven
programming — the foundation of modern user interfaces.
A graphical user interface (GUI) consists of basic visual building blocks such as
buttons,labels, text entry forms, menus, check boxes, and scroll bars, among others, all
packed inside a standard window. Building blocks are commonly referred to as widgets. To
develop GUIs, a developer will require a module that makes such widgets available. We will
use the module tkinter that is included in the Standard Library. In this section, we explain the
basics of GUI development using tkinter:
tkinter is Python’s built-in module for GUI development. It acts as a bridge between Python
and the Tcl/Tk GUI framework.
Tkinter allows developers to:
• Create windows, buttons, labels, and text boxes.
• Handle user input through events.
• Build interactive desktop applications easily.
To start using tkinter:
from tkinter import Tk, Label
root = Tk() # Create main window
lbl = Label(root, text="Hello, GUI World!")
[Link]() # Place label in window
[Link]() # Run event loop
Output:
A simple window appears displaying “Hello, GUI World!”.
Figure 17.1 A text label. The Label widget created with the text argument will
display a text label.
Centre for Distance Education 17.3 Acharya Nagarjuna University
Explanation:
This simple interface uses the grid() geometry manager for organized alignment.
def clicked():
'prints day and time info'
time = strftime('Day: %d %b %Y\nTime: %H:%M:%S %p\n', localtime())
print(time)
root = Tk()
This example shows that in event-driven programming, control flow depends on user
actions (events) rather than a predefined sequence of commands.
Centre for Distance Education 17.5 Acharya Nagarjuna University
The command parameter acts as a callback function, executed only when the user interacts
with the GUI (in this case, clicks the button).
You can “bind” an event (e.g., mouse click) to a function using the command parameter or
the bind() method.
Example:
from tkinter import *
def greet():
print("Hello, User!")
root = Tk()
btn = Button(root, text="Greet", command=greet)
[Link]()
[Link]()
When the user clicks the button, the greet() function executes.
[Link]("<Key>", key_pressed)
Event patterns include:
• <Button-1> → Left mouse click
• <Button-3> → Right mouse click
• <Key> → Any key press
• <Return> → Enter key
• <Motion> → Mouse movement
In tkinter, these actions are handled by event binding, where a specific mouse action is
associated with an event-handling function.
def on_click(event):
"""Called when a mouse button is pressed."""
x, y = event.x, event.y
btn = [Link] # button number: 1=left, 2=middle, 3=right
Programming and Problem-Solving … 17.6 Graphical User Interfaces (Gui)
def on_double_click(event):
"""Called when the left button is double-clicked."""
[Link](text=f"Double-click at ({event.x}, {event.y})")
print(f"DOUBLE CLICK at ({event.x}, {event.y})")
def on_right_click(event):
"""Called when the right mouse button is pressed."""
[Link](text=f"Right-click at ({event.x}, {event.y})")
print(f"RIGHT CLICK at ({event.x}, {event.y})")
[Link]()
Explanation
1. Event Binding:
o The bind() function associates a mouse event with a handler (callback
function).
o Syntax:
o [Link]("<EventPattern>", callback_function)
o Example events:
▪ <Button-1> — Left mouse click
▪ <Double-Button-1> — Double left-click
▪ <Button-3> — Right mouse click
▪
2. Event Object:
Each callback receives an event object that contains details such as:
o event.x, event.y → Position of the cursor within the window.
o [Link] → Mouse button number.
Centre for Distance Education 17.7 Acharya Nagarjuna University
3. Label Update:
o The label lbl dynamically updates to show which mouse button was pressed
and the coordinates of the click.
o The same message is printed in the console for verification.
4. Window Setup:
o The Tk() function creates the main window.
o Label() displays messages to the user.
o geometry() defines the window size.
o mainloop() starts the event loop, keeping the window active.
Output
When the program runs, a window appears with the text:
Click anywhere inside the window
User Action Label Output (in GUI) Console Output
Left-click at (120, 45) Clicked: Button 1 at (120, CLICK: Button 1 at coordinates (120,
45) 45)
Double-click at (150, Double-click at (150, 60) DOUBLE CLICK at (150, 60)
60)
Right-click at (100, Right-click at (100, 30) RIGHT CLICK at (100, 30)
30)
This example demonstrates how tkinter enables event-driven programming for mouse
actions. By using bind() and handling the event object, programs can respond interactively to
user input — a fundamental concept in building responsive GUIs.
Widget Canvas:
The Canvas widget is a fun widget that can display drawings consisting of lines and
geometrical objects. You can think of it as a primitive version of turtle graphics. (In fact,
turtle graphics is essentially a tkinter GUI.) We illustrate the Canvas widget by building a
very simple pen drawing [Link] application consists of an initially empty canvas.
The user can draw curves inside the canvas using the mouse. Pressing the left mouse button
starts the drawing of the [Link] motion while pressing the button moves the pen and
draws the curve.
Example:
# event handlers
def begin(event):
Centre for Distance Education 17.9 Acharya Nagarjuna University
def draw(event):
global oldx, oldy
canvas.create_line(oldx, oldy, event.x, event.y) # draw a line segment
oldx, oldy = event.x, event.y # update coordinates
root = Tk()
oldx, oldy = 0, 0 # initialize mouse coordinates
# create a canvas
canvas = Canvas(root, height=100, width=150, bg='white')
[Link]()
[Link]()
When the user clicks and drags the mouse over the canvas:
• A continuous line is drawn following the mouse movement.
• Releasing the mouse button stops drawing.
This forms the basis for paint applications, signature capture tools, and interactive graphics
programs.
The Canvas widget in tkinter provides a powerful area for graphics, shapes, and
interactive [Link] supports several built-in methods for drawing and manipulating
shapes such as lines, rectangles, and [Link] shape drawn on the canvas is assigned a
unique item ID, which can later be used to move, modify, or delete that shape.
Some Canvas methods:
Method Description
create_line(x1, y1, x2, Creates one or more line segments connecting the specified
y2, …) coordinate points (x1, y1), (x2, y2), etc. Returns the ID of the
created line item.
create_rectangle(x1, y1, Draws a rectangle with opposite vertices at (x1, y1) and (x2, y2).
x2, y2) Returns the ID of the constructed rectangle.
create_oval(x1, y1, x2, Creates an oval (or circle) inscribed within a rectangle defined by
y2) the corner points (x1, y1) and (x2, y2). Returns the ID of the
constructed oval.
delete(ID) Deletes the item identified by its ID from the canvas. If called
without arguments (delete('all')), it clears the entire canvas.
move(item, dx, dy) Moves a canvas item horizontally by dx units and vertically by dy
units relative to its current position.
Programming and Problem-Solving … 17.10 Graphical User Interfaces (Gui)
the OOP approach to designing GUIs. This approach will make our GUI applications far
easier to reuse.
Program Code
from tkinter import Tk, Button
from [Link] import showinfo
from time import strftime, localtime
def clicked():
"""Displays the current day and time information."""
time = strftime('Day: %d %b %Y\nTime: %H:%M:%S %p\n', localtime())
showinfo(message=time) # display output in a popup message box
# Create button labeled 'Click it' and assign the event handler
button = Button(root,
text='Click it', # text on top of button
font=('Arial', 14),
command=clicked) # event handler function
[Link](pady=20)
[Link]()
Output
When the program runs, a window appears with a single button labeled “Click it”.
When the user clicks the button:
A message box pops up showing the current date and time, for example:
Day: 29 Oct 2025
Time: 03:24:45 PM
This example illustrates how tkinter integrates GUI widgets (like buttons) with event-driven
behavior. Using showinfo(), you can make the interface more interactive and user-friendly by
displaying information directly in a popup window rather than the console.
Output
When the program runs, a window appears with:
• A label showing the text:
Count: 0
Programming and Problem-Solving … 17.12 Graphical User Interfaces (Gui)
User Interaction:
• Clicking the Increase button repeatedly updates the label:
• Count: 1
• Count: 2
• Count: 3
• ...
This example shows how OOP concepts integrate seamlessly with tkinter GUI design.
By encapsulating interface elements and logic inside a class:
• The GUI becomes organized and scalable.
• Each object maintains its own state, allowing multiple independent GUIs if needed.
Such an approach is widely used in larger GUI projects where multiple windows, widgets, or
components interact cohesively.
17.6.2 Implementation
from tkinter import *
class Calculator:
def __init__(self, root):
[Link] = ""
self.input_text = StringVar()
input_frame = Frame(root)
input_frame.pack()
btns_frame = Frame(root)
btns_frame.pack()
buttons = [
['7', '8', '9', '/'],
['4', '5', '6', '*'],
['1', '2', '3', '-'],
['0', 'C', '=', '+']
]
root = Tk()
[Link]("Simple Calculator")
Calculator(root)
[Link]()
17.6.3 Output
A fully functional calculator GUI that performs basic arithmetic operations with real-time
display updates.
When the program runs, a window appears with:
Programming and Problem-Solving … 17.14 Graphical User Interfaces (Gui)
17.7 SUMMARY
• GUIs allow visual interaction with programs.
• tkinter provides an easy, cross-platform toolkit for GUI design.
• GUIs follow an event-driven model — responding to user inputs.
• Widgets are arranged using geometry managers like pack(), grid(), and place().
• OOP simplifies GUI design by encapsulating logic and interface.
• Practical GUI applications can be built using modular, reusable code.
• Term
• GUI
• Event
• Widget
• Callback
• Mainloop
• Geometry Manager
17.9 SELF-ASSESSMENT QUESTIONS
STRUCTURE
18.1 Introduction
18.2 The World Wide Web
18.2.1 Web Servers and Web Clients
18.2.2 “Plumbing” of the WWW
18.2.3 Naming Scheme: Uniform Resource Locator (URL)
18.2.4 Protocol: HyperText Transfer Protocol (HTTP)
18.2.5 HyperText Markup Language (HTML)
18.2.6 HTML Elements
18.2.7 Tree Structure of an HTML Document
18.2.8 Anchor HTML Element and Links
18.3 Python WWW API
18.3.1 Module [Link]
18.3.2 Module [Link]
18.3.3 Overriding the HTMLParser Handlers
18.3.4 Module [Link]
18.4 Case Study: Web Crawler
18.4.1 Recursive Crawler — Version 0.1
18.4.2 Recursive Crawler — Version 0.2
18.4.3 Web Page Content Analysis
18.5 Summary
18.6 Technical Terms
18.7 Self-Assessment Questions
18.8 Suggested Readings
Programming and Problem-Solving … 18.2 The World Wide Web (WWW)
18.1 INTRODUCTION
The World Wide Web (WWW) is a system of interlinked hypertext documents that can be
accessed via the Internet using web browsers. It enables users to navigate information using
hyperlinks, retrieve content from remote servers, and communicate using standardized
protocols.
Python provides modules and libraries that allow programs to interact with web resources —
downloading pages, parsing HTML, following links, and even automating browsing tasks.
This lesson covers the underlying structure of the Web and explores how Python can
interface with it programmatically.
The World Wide Web (WWW or, simply, the web) is a distributed system of documents
linked through hyperlinks and hosted on web servers across the Internet.
A URL (Uniform Resource Locator) identifies and locates a resource on the Web.
General Format:
scheme://host:port/path?query#fragment
Example:
[Link]
Component Meaning
https Protocol used (HTTP Secure).
[Link] Server name.
443 Port number (optional).
/articles/[Link] Path to the resource.
?topic=networking Query parameters.
#links Reference to a section within the page.
Tag Purpose
<h1>…</h1> Heading text
<p>…</p> Paragraph
<a href="…"> Hyperlink
<img src="…"> Image
<div>…</div> Section grouping
Each element can have attributes that provide additional information, e.g., href, src, or style.
<html>
└── <body>
├── <h1>
└── <p>
This hierarchical organization allows structured parsing and processing of web content.
Figure 18.2 shows all the elements in file [Link]. The figure makes explicit what element
is contained in another and the resulting tree structure of the document. This tree structure
and the HTML elements together determine the layout of the web page.
url = '[Link]
Programming and Problem-Solving … 18.6 The World Wide Web (WWW)
page = urlopen(url)
html = [Link]().decode('utf-8')
def __init__(self):
super().__init__()
[Link] = []
def handle_starttag(self, tag, attrs):
if tag == 'a':
for (attr, value) in attrs:
if attr == 'href':
[Link](value)
parser = LinkParser()
[Link]('<a href="[Link]
print([Link])
Output:
['[Link]
The figure 18.4 illustrates the interconnected structure of five HTML pages — [Link],
[Link], [Link], [Link], and [Link] — and the frequency of specific words
found within each page.
Each rectangle represents a single web page, and the labels inside indicate keywords (e.g.,
Beijing, Paris, Chicago) along with their frequency counts. The arrows represent
hyperlinks connecting one page to another, showing how a web crawler might traverse the
web structure.
For example:
• [Link] contains the words Beijing (×3), Paris (×5), and Chicago (×5), and links to
[Link] and [Link].
• [Link] mentions Chicago (×3) and Beijing (×6), linking onward to [Link].
• [Link] includes Nairobi (×7) and Bogota (×2), linking to [Link].
It uses a set named visited to track which web pages have already been processed, preventing
redundant crawling and infinite loops due to circular links.
Centre for Distance Education 18.9 Acharya Nagarjuna University
def crawl2(url):
'''A recursive web crawler that calls analyze()
on every visited web page'''
2. Recursive Design:
o Each time the function crawl2() is called with a new URL, that page is
analyzed (e.g., its HTML content is parsed to extract links).
o Then the crawler iterates over all hyperlinks found on that page.
o For each unvisited link, it calls itself recursively — continuing the crawl
process deeper into the link structure.
The visited set prevents this by ensuring that previously seen URLs are skipped.
5. Global Declaration:
o The global visited declaration is optional but serves as a clear reminder that
the variable belongs to the global scope, shared across recursive calls.
Output Behavior
When the crawler starts with an initial page, say:
crawl2("[Link]
class LinkCollector(HTMLParser):
def __init__(self):
super().__init__()
[Link] = []
def handle_starttag(self, tag, attrs):
if tag == 'a':
for (attr, val) in attrs:
if attr == 'href' and [Link]('.html'):
[Link](val)
def analyze(url):
Centre for Distance Education 18.11 Acharya Nagarjuna University
print(f"Analyzing: {url}")
try:
content = urlopen(url).read().decode('utf-8')
collector = LinkCollector()
[Link](content)
return [Link]
except:
return []
Summary
This recursive crawler version introduces three major improvements:
1. Recursion to automatically traverse linked pages.
2. A visited set to manage page tracking and prevent loops.
3. Exception handling to ensure robustness when facing inaccessible or malformed
pages.
Together, these enhancements make the crawler a practical, extensible foundation for real-
world web scraping, indexing, or search engine prototypes.
def crawl2(url):
'''A recursive web crawler that calls analyze()
on every visited web page'''
class LinkCollector(HTMLParser):
"""Collects all hyperlinks from an HTML page."""
def __init__(self):
super().__init__()
[Link] = []
def handle_starttag(self, tag, attrs):
if tag == 'a':
for (attr, value) in attrs:
if attr == 'href' and [Link]('.html'):
[Link](value)
def analyze(url):
"""Returns a list of hyperlinks extracted from a given URL."""
print("Analyzing:", url)
try:
content = urlopen(url).read().decode('utf-8')
collector = LinkCollector()
[Link](content)
return [Link]
except:
Centre for Distance Education 18.13 Acharya Nagarjuna University
return []
Execution Flow
Suppose the program begins with:
crawl2("[Link]
Step-by-Step Process:
1. [Link] is analyzed and added to visited.
2. analyze("[Link]") returns a list of links → ['[Link]', '[Link]'].
3. crawl2('[Link]') is called; [Link] is analyzed, producing ['[Link]'].
4. The recursion continues until all reachable pages ([Link], [Link], [Link],
[Link], etc.) have been processed.
5. Each page is visited only once, even if multiple pages link back to it.
Sample Output
Analyzing: [Link]
Analyzing: [Link]
Analyzing: [Link]
Analyzing: [Link]
Analyzing: [Link]
Advantages of Recursion in Crawling
• Simplifies the program structure by letting each call handle its own subset of links.
• Easily scalable for small to medium websites.
• Encourages modularity when combined with separate parsing and analysis functions.
Version 0.2 of the crawler demonstrates how recursion and state management can be used
to explore a network of web pages efficiently.
By integrating the analyze() function, a visited set, and exception handling, this program
forms a foundation for more advanced tools such as search-engine spiders and data-collection
bots.
collector = Collector(url)
[Link](content)
urls = [Link]() # get list of links
class Collector(HTMLParser):
'Collects text and links from a web page'
def getLinks(self):
return [Link]
def getData(self):
return ' '.join([Link])
[Link](url)
links = analyze(url)
for link in links:
if link not in visited:
try:
crawl2(link)
except:
pass
Each time crawl2(url) visits a page, it calls analyze(url) to print the word frequencies and list
of discovered links. Then it recursively crawls those links that have not yet been visited.
Sample Output (Textbook Example)
Visiting [Link]
URL link
[Link] [Link]
[Link] [Link]
[Link] [Link]
18.5 SUMMARY
• The World Wide Web operates through client-server communication using the HTTP
protocol.
• URLs identify resources, while HTML structures content.
• Python provides modules like [Link], [Link], and [Link] for web
automation and content retrieval.
• Regular expressions enable text pattern matching for data extraction.
• A web crawler automates navigation and analysis of web pages.
• HTTP
• URL
• HTML
• Parser
• Crawler
• Understand the concept of pattern matching and its importance in text mining and
data extraction.
• Explain the syntax and structure of regular expressions (regex).
• Identify and apply common regex operators and metacharacters.
• Use the Python re module for pattern-based searching, matching, replacing, and
extracting data.
• Develop programs that extract information such as emails, URLs, dates, and numbers
from text files and web content.
• Understand how regex enables data cleaning, validation, and web data mining.
STRUCTURE
To mine the text content of a web page or other text document, we need tools that help us
define text patterns and then search for strings in the text that match these text [Link]
analyzing or mining text data (such as web pages, logs, or emails), it is often necessary to
search for patterns instead of fixed words.
Programming and Problem-Solving … 19.2 String Pattern Matching
Regular expressions provide a compact and flexible way to match text patterns. They use
special symbols (called metacharacters) to describe text structures. Regular expressions
(regex) are patterns that describe sets of strings and are widely used for searching and text
manipulation.
The simplest regular expression is one that doesn’t use any regular expression operators. For
example, the regular expression best matches only one string, the string 'best':
'be.t' matches best, but also 'belt', 'beet', 'be3t', and 'be!t', among others:
Pattern: b e . t
↓ ↓ ↓ ↓
String: b e s t → Match
Centre for Distance Education 19.3 Acharya Nagarjuna University
b e l t → Match
b e e t → Match
b e ! t → Match
b e t → Match
Explanation:
• The dot (.) acts as a wildcard, matching any single character.
• Only strings that start with b and e, and end with t of length 4, will match.
For example, the operator * in regular expression be*t matches 0 or more repetitions of the
previous character (e). It therefore matches bt and also bet, beet, and so on:
Example: be*t
Pattern: b e* t
↓ ↓ ↓
String: b t → (zero 'e')
b e t →
b eet →
b eeet→
Flow of Matching:
Start → 'b' → zero or more 'e's → 't' → Match
Explanation:
• The * operator repeats the previous character zero or more times.
• This pattern is greedy, meaning it will match as many 'e's as possible before moving
to 't'.
Example: be+t
The pattern be+t requires at least one 'e' before 't'.
Pattern: b e+ t
↓ ↓ ↓
String: b t → (no 'e')
b e t →
b eet →
b eeet→
Programming and Problem-Solving … 19.4 String Pattern Matching
Flow of Matching:
Start → 'b' → one or more 'e's → 't' → Match
Example: bee?t
The pattern bee?t matches strings where 'b' is followed by one 'e' and an optional 'e' before
't'.
Pattern: b e e? t
String: b e t → (0 extra 'e')
b e e t → (1 extra 'e')
b e e e t→ (too many 'e')
Explanation:
• The ? operator means the previous character may occur zero or one time.
For example, regular expression hello|Hello matches strings 'hello' and 'Hello':
Example Text:
Contact: user1@[Link], info@[Link]
Matches:
user1@[Link]
info@[Link]
Flow Diagram:
Start
→ [word/dot/hyphen]+
→ '@'
→ [word/dot/hyphen]+
→ Match
Example:
import re
pattern = r'\d+'
text = "My age is 25 and my pin code is 530003."
numbers = [Link](pattern, text)
print(numbers)
Output:
['25', '530003']
Function Description
[Link](pattern, string) Checks if the pattern matches from the beginning of the string.
[Link](pattern, string) Searches the entire string for the first occurrence of the pattern.
[Link](pattern, string) Returns a list of all non-overlapping matches.
[Link](pattern, repl, string) Substitutes all occurrences of a pattern with another string.
[Link](pattern, string) Splits a string based on the pattern.
Function Description
[Link]() Matches from the beginning of a string.
[Link]() Finds the first occurrence of a pattern.
[Link]() Returns all non-overlapping matches.
[Link]() Substitutes one string for another.
Output:
+91-9876543210 is valid.
The following program combines regular expressions with file processing and text extraction.
import re
html_content = '''
<html><body>
<p>Contact: user1@[Link]</p>
<a href="[Link]
<a href="[Link]
</body></html>
'''
1. Web Scraping
Application: Extracting hyperlinks, image URLs, and metadata
Explanation:
Web scraping involves collecting data from websites. Since web pages are mostly in HTML,
Regex can be used to extract specific patterns of text such as URLs, links, or metadata.
For example:
• Extracting hyperlinks:
Programming and Problem-Solving … 19.10 String Pattern Matching
• href="(https?://[^"]+)"
→ This pattern matches all hyperlinks beginning with http or https.
• Extracting image URLs:
• <img[^>]+src="([^">]+)"
→ Captures all image source (src) attributes from <img> tags.
• Extracting metadata (e.g., title, description):
• <meta\s+name="description"\s+content="([^"]+)"
→ Extracts content of meta description tags.
Use case example:
In web scraping scripts using Python (e.g., with requests and re), Regex helps filter out only
the needed text from raw HTML before further processing or storing it in databases.
2. Data Cleaning
Application: Removing unwanted symbols, HTML tags, or whitespace
Explanation:
Data collected from the web or files often contains extra characters, symbols, or HTML code
that must be cleaned before analysis. Regex helps identify and remove such unwanted
patterns quickly.
Examples:
• Removing HTML tags:
• <[^>]+>
→ Removes everything between < and > (i.e., HTML tags).
• Removing special characters:
• [^a-zA-Z0-9\s]
→ Keeps only alphabets, digits, and spaces.
• Trimming extra whitespace:
• \s+
→ Matches multiple spaces or tabs; can be replaced with a single space.
Use case example:
Cleaning text data before feeding it to an NLP model or database ensures consistency and
accuracy.
3. Validation
Application: Checking emails, phone numbers, IP addresses
Centre for Distance Education 19.11 Acharya Nagarjuna University
Explanation:
Regex is widely used for input validation—to ensure data entered by users follows the correct
format.
Examples:
• Email validation:
• ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
→ Matches most standard email formats.
• Phone number validation (India):
• ^(\+91[\-\s]?)?[6-9]\d{9}$
→ Matches Indian mobile numbers with or without country code.
• IP address validation:
• ^((25[0-5]|2[0-4]\d|[0-1]?\d{1,2})\.){3}(25[0-5]|2[0-4]\d|[0-1]?\d{1,2})$
→ Ensures valid IPv4 format.
Use case example:
Used in web forms or backend systems to reject invalid entries before saving them to
databases.
5. Log Analysis
Application: Detecting error messages or IP addresses
Explanation:
System and application logs contain large volumes of text data. Regex enables automatic
pattern matching to detect key information.
Examples:
• Extracting IP addresses:
• \b\d{1,3}(\.\d{1,3}){3}\b
→ Finds all IPv4 addresses.
• Finding error messages:
• ERROR|FATAL|EXCEPTION
→ Detects critical log entries.
• Extracting timestamps:
• \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}
→ Captures datetime formats (e.g., 2025-10-29 20:15:30).
Use case example:
Used in server monitoring or debugging tools to locate issues from log files quickly.
6. Security
Application: Finding SQL injection or suspicious input patterns
Explanation:
Regex can detect potentially harmful user inputs or code injection attempts in web
applications.
Examples:
• Detecting SQL injection attempts:
• (?:')|(?:--)|(/\*(?:.|[\n\r])*?\*/)|(\b(select|update|delete|insert|drop|exec)\b)
→ Identifies suspicious SQL keywords or comment patterns.
• Identifying cross-site scripting (XSS) attempts:
• <script.*?>.*?</script>
→ Matches embedded JavaScript code in inputs.
Centre for Distance Education 19.13 Acharya Nagarjuna University
19.7 SUMMARY
• String pattern matching enables flexible search and extraction from text.
• Regular expressions (regex) are symbolic patterns that describe sets of strings.
• The re module provides Python tools for searching, matching, and replacing patterns.
• Common operators like ., *, +, ?, and | allow powerful pattern combinations.
• Regex is vital for web mining, data validation, and text processing.
Essay Questions
1. Define regular expressions. Explain their importance in text mining.
2. Discuss various regex operators with suitable examples.
3. Describe how the re module supports pattern matching and substitution.
4. Explain the difference between [Link](), [Link](), and [Link]().
Short Notes
1. Write a note on character classes.
2. How are grouping and alternation used in regex?
3. Explain the use of [Link]() with an example.
STRUCTURE
The Structured Query Language (SQL) is the standard language for interacting with
RDBMSs. SQL allows users to:
• Create and modify database structures.
• Insert, update, delete, and retrieve data.
• Control access and manage transactions.
Centre for Distance Education 20.3 Acharya Nagarjuna University
Key Concepts:
• Primary Key: uniquely identifies each row (e.g., RollNo)
• Foreign Key: links one table to another (e.g., RollNo in COURSE table)
• Constraints: ensure data integrity (e.g., NOT NULL, UNIQUE)
20.1.3 Structured Query Language (SQL) Overview
SQL consists of multiple categories of commands:
Category Description Examples
DDL (Data Definition Language) Defines and modifies CREATE, ALTER,
database schema DROP
DML (Data Manipulation Language) Manages data in tables INSERT, UPDATE,
DELETE
DQL (Data Query Language) Retrieves data SELECT
DCL (Data Control Language) Grants/revokes permissions GRANT, REVOKE
TCL (Transaction Control Manages transactions COMMIT,
Language) ROLLBACK
Result:
Name Marks
Kavya 92
Anjali 87
Output:
Branch AvgMarks
CSE 89.5
Centre for Distance Education 20.5 Acharya Nagarjuna University
[Link]()
[Link]()
[Link]()
def create_table():
with [Link]('[Link]') as conn:
[Link]('''CREATE TABLE IF NOT EXISTS Student
(RollNo INTEGER PRIMARY KEY, Name TEXT, Branch TEXT, Marks
INTEGER)''')
def view_students():
with [Link]('[Link]') as conn:
for row in [Link]("SELECT * FROM Student"):
print(row)
Programming and Problem-Solving … 20.8 Database Programming in Python
create_table()
insert_student(1, 'Anjali', 'CSE', 89)
insert_student(2, 'Ramesh', 'ECE', 78)
view_students()
List Comprehensions
A list comprehension provides a concise way to create lists.
Syntax:
[expression for item in iterable if condition]
Example 1:
squares = [x*x for x in range(1, 6)]
print(squares)
Output:
[1, 4, 9, 16, 25]
Example 2: Filtering
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)
Output:
[0, 2, 4, 6, 8]
List comprehensions are faster and more readable than traditional loops.
2. map() Function:
Applies a function to all items in an iterable.
numbers = [1, 2, 3, 4]
result = list(map(lambda x: x**2, numbers))
print(result)
Output: [1, 4, 9, 16]
Centre for Distance Education 20.9 Acharya Nagarjuna University
3. filter() Function:
Selects elements that satisfy a condition.
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
Output: [2, 4]
Conceptual Example:
data = [("A", 3), ("B", 5), ("A", 2), ("B", 7)]
# Map phase - already done
# Shuffle phase
shuffled = {}
for k, v in data:
[Link](k, []).append(v)
# Reduce phase
reduced = {k: sum(vs) for k, vs in [Link]()}
print(reduced)
Output:
{'A': 5, 'B': 12}
# Map Phase
mapped = []
for doc, text in [Link]():
for word in [Link]():
[Link](([Link](), doc))
Centre for Distance Education 20.11 Acharya Nagarjuna University
# Shuffle Phase
index = {}
for word, doc in mapped:
[Link](word, set()).add(doc)
Advantages:
• Faster computation for large datasets
• Better utilization of CPU resources
• Useful in AI, image processing, and simulations
def square(n):
return n * n
if __name__ == "__main__":
with Pool(4) as p:
result = [Link](square, [1, 2, 3, 4, 5])
Programming and Problem-Solving … 20.12 Database Programming in Python
print(result)
Output:
[1, 4, 9, 16, 25]
Each process handles one element in parallel.
Efficiency (E):
def map_func(line):
return [(w, 1) for w in [Link]()]
if __name__ == "__main__":
with Pool(3) as p:
mapped = [Link](map_func, text)
Output:
{'python': 2, 'supports': 1, 'mapreduce': 3,
'enables': 1, 'parallel': 2, 'computing': 1, 'in': 1}
20.5 SUMMARY
• Functional programming emphasizes expressions and immutability.
• List comprehensions and lambda functions make Python concise and powerful.
• MapReduce divides computation into mapping and reducing phases for large data
processing.
• Parallel computing executes tasks concurrently using multiple processors.
• The multiprocessing module enables scalable, high-performance Python programs.
Short Questions
1. Define functional programming.
2. Write any two examples of list comprehensions in Python.
3. Differentiate between the map() and filter() functions.
4. What is the purpose of the reduce() function?
5. Explain the two main phases of the MapReduce framework.
6. State any two advantages of parallel computing.
7. Write the formula for Speedup and Efficiency in parallel computing.
8. What is the role of the [Link] class in Python?
9. Mention any two real-world applications of parallel computing.
10. List any two differences between sequential and parallel MapReduce execution.
Essay Questions
1. Explain the concept of functional programming and describe how it is supported in
Python with examples.
2. Discuss list comprehensions in Python and illustrate their use with appropriate
examples.
3. Compare and contrast the working of map(), filter(), and reduce() functions with
code illustrations.
4. Describe the MapReduce problem-solving framework. How does it simplify data
processing in distributed environments?
5. Develop a Python program that counts the frequency of words in a given text using
the MapReduce approach.
6. What is parallel computing? Explain its importance in high-performance and data-
intensive applications.
7. Write a Python program using [Link] to compute the cube of
numbers in parallel.
8. Define Speedup and Efficiency in parallel systems. Illustrate how they are used to
measure performance improvement.
9. Compare sequential and parallel MapReduce executions in terms of processing,
resource usage, and efficiency.
10. Discuss the applications of parallel computing in real-world domains such as
machine learning, data mining, and simulations.