Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
219 views

Programming Fundamentals Using Python (Unit 1-4)

This document provides an introduction to programming fundamentals using the Python programming language. It outlines a syllabus for a course on Python programming that covers 4 units: 1) Introduction to Python Programming, 2) Fundamentals of Python Programming, 3) Control Structures, and 4) User Defined Functions and Built-in Data Structures in Python. The syllabus maps lessons and topics to the outlined units, providing an overview of the concepts and techniques that will be taught in the course.

Uploaded by

Tanjiro Kamado
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
219 views

Programming Fundamentals Using Python (Unit 1-4)

This document provides an introduction to programming fundamentals using the Python programming language. It outlines a syllabus for a course on Python programming that covers 4 units: 1) Introduction to Python Programming, 2) Fundamentals of Python Programming, 3) Control Structures, and 4) User Defined Functions and Built-in Data Structures in Python. The syllabus maps lessons and topics to the outlined units, providing an overview of the concepts and techniques that will be taught in the course.

Uploaded by

Tanjiro Kamado
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 168

PROGRAMMING

FUNDAMENTALS
USING PYTHON
B.A. (PROGRAMME) IN COMPUTER SCIENCE DISCIPLINE
SEMESTER-I
DSC-1 (A/B)
(MAJOR PAPER - I)

DEPARTMENT OF DISTANCE AND CONTINUING EDUCATION


UNIVERSITY OF DELHI
Programming Fundamentals Using Python

Editors
Prof. Ajay Jaiswal

Content Writers
Pratibha Yadav, Mansi Sood

Content Reviewer from the DDCE/COL/SOL


Ms. Bhavya Ahuja Grover

Academic Coordinator
Mr. Deekshant Awasthi

© Department of Distance and Continuing Education


ISBN: 978-81-19169-95-5
1st edition: 2023
E-mail: ddceprinting@col.du.ac.in
computer@col.du.ac.in

Published by:
Department of Distance and Continuing Education,
Campus of Open Learning/School of Open Learning,
University of Delhi, Delhi-110 007
Printed by:
School of Open Learning, University of Delhi

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

This Study Material is duly recommended and approved in Academic Council


meeting held on 11/08/2023 Vide item no. 1015 and subsequently Executive
Council Meeting held on 25/08/2023 vide item no. 1267.

Corrections/Modifications/Suggestions proposed by Statutory Body,


DU/Stakeholder/s in the Self Learning Material (SLM) will be incorporated in the
next edition. However, these corrections/modifications/suggestions will be
uploaded on the website https://sol.du.ac.in. Any feedback or suggestions may be
sent at the email- feedbackslm@col.du.ac.in

Printed at: Vikas Publishing House Pvt. Ltd. Plot 20/4, Site-IV, Industrial Area Sahibabad, Ghaziabad - 201 010 ( Copies)

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

SYLLABUS
Programming Fundamentals Using Python
Syllabus Mapping

Unit 1: Introduction to Python Programming


Problem solving strategies; Structure of a Python program; Syntax and Lesson 1: Introduction to
semantics; Python interpreter/shell, indentation; Executing simple programs Python Programming
in Python. (Pages 3-24)

Unit 2: Creating Python Programs


Identifiers and keywords; literals, numbers, and strings; Operators and Lesson 2: Fundamentals of
expressions; Input and output statements; control structures (conditional Python Programming
statements, loop control statements, break, continue and pass), Errors and (Pages 27-54)
exception handling. Lesson 3: Control Structures
(Pages 55-74)
Lesson 4: Error and Exception
Handling in Python
(Pages 75-94)

Unit 3: User Defined Functions


Defining functions, passing arguments and returning values, default Lesson 5: User Defined
arguments Functions in Python
(Pages 97-120)

Unit 4: Built-in Data Structures


Strings, Lists, Tuples, Sets, Dictionaries; their built-in functions, operators Lesson 6: Built-in Data
and operations Structures in Python
(Pages 123-156)

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

CONTENTS
UNIT I
LESSON 1 INTRODUCTION TO PYTHON PROGRAMMING 3-24

1.1 Learning Objectives


1.2 Introduction to Computers
1.3 Understanding Programming
1.3.1 Low Level Language
1.3.2 High Level Language
1.4 What Is Python
1.5 Why Use Python?
1.6 Problem Solving Strategies
1.7 Structure of a Python Program
1.7.1 Components of a Python Program
1.7.2 Documentation
1.7.3 Indentation and Code Blocks
1.8 Syntax and Semantics of Python
1.8.1 Syntax
1.8.2 Semantics
1.9 Python Interpreter and Shell
1.9.1 Interpreted vs. Compiled Languages
1.9.2 Installing Python and Setting up the Interpreter on Windows
1.10 Executing Simple Python Programs
1.10.1 Writing your First Python Program
1.11 Summary
1.12 Glossary
1.13 Self-Assessment Questions
1.14 References

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

UNIT II
LESSON 2 FUNDAMENTALS OF PYTHON PROGRAMMING 27-54

2.1 Learning Objectives


2.2 Introduction
2.3 Tokens
2.4 Literals
2.4.1 Numeric Literals
2.4.2 String Literals
2.4.3 Boolean Literals
2.4.4 Literal Collections
2.4.5 Special Literals
2.5 Data Types
2.6 Variables
2.6.1 Variable Assignment
2.6.2 Variable Types
2.7 Keywords & Identifier
2.7.1 Keywords
2.7.2 Identifier
2.8 Expressions & Operators
2.8.1 Arithmetic Operators
2.8.2 Relational Operators
2.8.3 Logical Operators
2.8.4 Bitwise Operators
2.8.5 Assignment Operators
2.8.6 Identity Operators
2.8.7 Membership Operators
2.8.8 Operators Precedence
2.9 Statements Vs Expressions
2.10 Strings

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

2.11 Input Output Statements


2.11.1 Input
2.11.2 Eval Function
2.11.3 Output
2.12 Summary
2.13 Glossary
2.14 Self-Assessment Questions
2.15 References
LESSON 3 CONTROL STRUCTURES 55-74

3.1 Learning Objectives


3.2 Introduction
3.3 Conditional Statements
3.3.1 if Statement
3.3.2 If - Else Statement
3.3.3 If – ELIF - Else LADDER
3.4 Loops in Python
3.4.1 For Loop
3.4.2 while Loop
3.4.3 Nested Loop
3.5 Loop Control Statements
3.5.1 Break Statement
3.5.2 Continue Statement
3.5.3 Pass Statement
3.6 Summary
3.7 Glossary
3.8 Self-Assessment Questions
3.9 References
LESSON 4 ERROR AND EXCEPTION HANDLING IN PYTHON 75-94

4.1 Learning Objectives


4.2 Introduction
4.3 What is Error?

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

4.4 What Is Exception?


4.5 Handling Exceptions
4.5.1 The try-except Block
4.5.2 Multiple Except blocks
4.5.3 Else Block
4.5.4 Finally Block
4.6 Raising Exceptions
4.7 Nested Try Block
4.8 Exception Chaining
4.9 Common Built-in Exceptions
4.9.1 TypeError
4.9.2 ValueError
4.9.3 NameError
4.9.4 Most used Built-in Exceptions
4.10 Best Practices for Exception Handling
4.11 Summary
4.12 Glossary
4.13 Self-Assessment Questions
4.14 References

UNIT III
LESSON 5 USER DEFINED FUNCTIONS IN PYTHON 97-120

5.1 Learning Objectives


5.2 Introduction
5.3 Defining Functions
5.4 Passing Arguments to Functions
5.4.1 Positional and Keyword Arguments
5.4.2 Default Arguments
5.5 Scope of Variables

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

5.6 Purpose of Functions


5.7 Recursive Functions
5.8 Summary
5.9 Glossary
5.10 Self-Assessment Questions
5.11 References

UNIT IV
LESSON 6 BUILT-IN DATA STRUCTURES IN PYTHON 123-156

6.1 Learning Objectives


6.2 Introduction
6.3 Strings
6.3.1 Concatenation
6.3.2 In and Not In Operator
6.3.3 String comparison
6.3.4 Indexing and Slicing
6.3.5 Built-in Function – Len, Min, Max
6.3.6 Strings are Immutable
6.4 Lists
6.4.1 Concatenation
6.4.2 In and Not in operator
6.4.3 del Operator - Remove Element
6.4.4 Indexing and Slicing
6.4.5 Lists are Mutable
6.4.6 Adding and Removing Elements
6.4.7 Built-in Functions – len, max, min, sum
6.5 Tuples
6.5.1 Concatenation
6.5.2 Indexing and Slicing
6.5.3 Built-in functions
6.5.4 Tuples are Immutable

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

6.5.5 Packing and Unpacking


6.6 Sets
6.6.1 Membership Test
6.6.2 Union of two sets
6.6.3 Intersection of two sets
6.6.4 Difference between two sets
6.6.5 Symmetric difference of two sets
6.7 Dictionaries
6.7.1 Accessing Elements
6.7.2 Updating and Adding Elements
6.7.3 Removing Elements
6.7.4 Nested Dictionaries
6.7.5 Immutable Keys
6.7.6 Missing Key value
6.8 Data Structures with Loop and Conditional Statements
6.9 Summary
6.10 Glossary
6.11 Self-Assessment Questions
6.12 References

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


School of Open Learning, University of Delhi
UNIT I: INTRODUCTION TO PYTHON
PROGRAMMING

LESSON 1 INTRODUCTION TO PYTHON


PROGRAMMING
Introduction to Python Programming

LESSON 1 NOTES

INTRODUCTION TO PYTHON PROGRAMMING

Pratibha Yadav
Assistant Professor
Shyama Prasad Mukherji College
Email-Id: pratibha.123@spm.du.ac.in

Structure
1.1 Learning Objectives
1.2 Introduction to Computers
1.3 Understanding Programming
1.3.1 Low Level Language
1.3.2 High Level Language
1.4 What Is Python
1.5 Why Use Python?
1.6 Problem Solving Strategies
1.7 Structure of a Python Program
1.7.1 Components of a Python Program
1.7.2 Documentation
1.7.3 Indentation and Code Blocks
1.8 Syntax and Semantics of Python
1.8.1 Syntax
1.8.2 Semantics
1.9 Python Interpreter and Shell
1.9.1 Interpreted vs. Compiled Languages
1.9.2 Installing Python and Setting up the Interpreter on Windows
1.10 Executing Simple Python Programs
1.10.1 Writing your First Python Program
1.11 Summary
1.12 Glossary
1.13 Self-Assessment Questions
1.14 References
Self-Instructional
Material 3

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES
1.1 LEARNING OBJECTIVES

After completion of this lesson, you will be able to learn about:


 Basics of Computer and Programming
 Features of Python
 Problem Solving strategies for any programming language
 Structure of a Python Program
 Complied vs Interpreted languages
 Installation of Python
 Using Python Interpreter
 Executing First Python Program

1.2 INTRODUCTION TO COMPUTERS

A computer is an electronic device that can receive, process, store, and output data. It
consists of hardware (physical components) and software (programs that run on the
hardware). Computers use a fetch-decode-execute cycle to execute instructions. The
CPU fetches instructions from memory, decodes them, and executes the corresponding
operations.
The basic components of a computer are:
 Central Processing Unit (CPU): It is the core of any computer device
which executes instructions and performs calculations. It is also called the
Brain of the Computer.
 Memory Unit: It is used to store data, instructions and information. Primary
and secondary are the two categories of memory. Secondary memory is
used to store data permanently and is involatile in nature. Primary memory is
also known as principal or internal memory which is volatile in nature. There
are two types of primary memory:
Self-Instructional
4 Material

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


School of Open Learning, University of Delhi
Introduction to Python Programming

o Read-only memory (ROM): ROM is a component of the memory unit. NOTES


This memory is read-only and cannot be used for writing.
o Random-access memory (RAM): RAM is a component of the memory
unit which is used to store program data in temporary manner.
 Input Devices: These allow people to send data to the computer so that it
can carry out specific commands. Examples include keyboards, mouse,
and scanners.
 Output Devices: After the computer has done processing the instructions,
these devices display the processed data. For instance: speakers, plotters,
projectors, printers, or monitors

1.3 UNDERSTANDING PROGRAMMING

Programming is the process of instructing a computer to perform specific tasks by


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

1.3.1 Low Level Language

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

1.3.2 High Level Language

High level languages are programming languages designed to be human-readable and


easier to understand and write. They offer abstractions that make programming easier Self-Instructional
Material 5

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES and are independent of the underlying hardware. Examples of high level languages
include Python, Java, C++, C#, PHP, JavaScript and many more.

In-Text Questions
1. What are the different components of a computer?
2. What is the difference between high level and low level programming languages?

1.4 WHAT IS PYTHON

Python is a widely used high level programming language that is well-known for being
easy to understand and simple to use. It is similar to a tool that enables you to instruct
a computer to carry out numerous tasks. Python is flexible and may be used for a
variety of tasks, including designing games, websites, data analysis, and repetitive task
automation. Python allows you to develop understandable code because of its clear
and easily readable syntax. This makes it an excellent choice for entry level coders.
Overall, Python is a powerful and user-friendly language that helps people solve
problems and create all sorts of interesting things using a computer.

1.5 WHY USE PYTHON?

Python is a programming language that is widely used and loved by developers for a
variety of reasons. Here are some key advantages of using Python:
 Open Source: Since Python is open source, anyone can use and distribute it
without restriction, including for profit.
 Ease of use: Python’s syntax is simple and clear. It’s clear syntax and statements
that mimic English make it simpler to create, debug, and maintain.
 Versatility: Python is a very flexible language that can be used for a variety of
tasks, including machine learning and web development. Programming paradigms
Self-Instructional
6 Material

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


School of Open Learning, University of Delhi
Introduction to Python Programming

including procedural, object-oriented, and functional programming are all NOTES


supported.
 Robust Standard Library: Python has a vast collection of libraries and
frameworks that extend its capabilities. Developers can utilize existing solutions
and save time by using these libraries, which offer pre-written code for particular
tasks. Popular libraries include NumPy for scientific computing, pandas for
data analysis, Django for web development, TensorFlow for machine learning,
and Flask for building web applications.
 Easy Integration and Interoperability: Python easily integrates with other
programming languages and systems. It can interface with C/C++, Java, and
other languages, allowing developers to utilize existing codebases and extend
functionality. Python also offers modules for connecting to databases, accessing
web services, and working with different file formats.
 Strong Community and Support: Python has a large and active community of
developers who contribute to its growth. Through forums, online resources,
and documentation, this community offers considerable support. It’s likely that
you will receive assistance from the Python community if you run into any problems
or have any inquiries.
 Rapid Development and Prototyping: Python’s simplicity and readability
contribute to faster development cycles. Rapid prototyping is made possible by
it, enabling developers to design and test concepts quickly.
 Job Opportunities and Career Growth: Python is highly sought after in the
employment market and has been gaining popularity quickly. Python expertise
is valued across a wide range of industries, including technology, finance, data
science, and machine learning. Learning Python increases your opportunities
for employment and for career advancement.
Overall, Python is a great option for developers thanks to its readability,
adaptability, collection of library, rapid development, and strong community support.
Its wide range of applications and ease of use have contributed to its widespread
adoption and popularity.

Self-Instructional
Material 7

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES
1.6 PROBLEM SOLVING STRATEGIES

The problem-solving process in Python programming involves a systematic approach


to tackle programming challenges. Here are the key steps to follow:
1. Understanding the Problem: Problem understanding is essential to find solution
to any problem. Problem understanding means analyzing: what should be the
desired code output and how can that be produced?
2. Plan and Design: A proper action plan must be created to address a problem
after it has been identified. We refer to this as designing the plan. This stage
often entails computing the outcome from the inputs that have been provided.
3. Pseudocode: Without concentrating on the syntax of Python, write pseudocode
or list the steps of your approach in simple language. This aids in streamlining
the logic of the solution and organizing your thoughts.
4. Translate pseudocode into Python Code: Start implementing your solution
in Python by translating your pseudocode into actual code. Start with small
sections and test them as you find any problems or mistakes.
5. Test and Debug: Test your code using various inputs to ensure it produces the
desired results. Debug any errors or unexpected behaviour by identifying and
fixing issues in your code.
6. Optimize: Examine your code for any potential improvements or optimizations.
Look for areas where you can make the code more efficient or eliminate
redundancies.
7. Documentation: Document your code by adding useful comments to make
your code easier to understand and maintain.
8. Repeat and Iterate: If your solution does not meet the requirements or you
encounter new problems, go back to the previous steps and make necessary
adjustments. Problem-solving is an iterative process, and it’s common to refine
and improve your code based on feedback and new insights.
9. Finalize: Once you have a working solution, review and finalize your code.
Make sure it adheres to best practices for coding, is adequately documented,
Self-Instructional
8 Material and is organized correctly.

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


School of Open Learning, University of Delhi
Introduction to Python Programming

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

In-Text Questions
1. What do you understand by the term “open source”?
2. How does writing pseudocode helps with problem solving process?

1.7 STRUCTURE OF A PYTHON PROGRAM

Python program is structured in a way that allows it to be easily understood and


modified by other programmers. By following best practices for program structure
and organization, programmers can create code that is efficient, maintainable, and
easy to debug.

1.7.1 Components of a Python Program

1. Comments: Comments are lines of text that are used to make the code more
readable. These are not executed by the Python interpreter. Comments start
with the hash symbol (#) and can be placed anywhere in the code.
For example:
# This is a comment placed above the python statement
print(“Python is a programming language”)
print(“Hello World”) # This is another comment placed after
the python statement

2. Import statements: These are used to bring in external modules or libraries


that contain pre-written code for specific tasks. Import statements are usually
placed at the beginning of the code.
Self-Instructional
Material 9

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES For Example:


import sys

3. Variable declarations: Variables hold the values or data throughout the


program. Variables can be assigned values using the assignment operator ( = ).
For Example:
x = “Lily”
y = 123

Here, x and y are variables holding data


4. Function definitions: Functions are used for defining reusable code blocks to
carry out specific tasks. We can pass data to functions in form of input parameters.
Functions can return result as well.
For Example:
def firstFunction(): #defining the function
print(“My first code in python using functions”)
firstFunction() #calling the function

5. Output statements: Output statements are used to display data or results to


the user. In addition to reporting text or values to the console, output statements
can write data to files or other output devices. print() function is the most often
used function for printing the message on the screen or any other standard
output device.
For Example:
print(“This is an example of print statement”)
print(1, 2, 3, ‘Hello’, ‘World’)

1.7.2 Documentation

Python documentation is a way to explain the code to other programmers who may
read it in the future. Python code documentation can be done in various ways:
1. Documentation strings or docstrings: These multi-line strings are used at
the start of the definition of a module, class, or function. They give a thorough
explanation of the actions the code takes, the parameters it requires, and the
Self-Instructional
10 Material

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


School of Open Learning, University of Delhi
Introduction to Python Programming

results it produces. The docstrings are declared using "'triple single quotes"' or NOTES
"""triple double quotes"""
For Example:
‘‘‘This is an example of
Docstrings in Python’’’
“““This is another example
of Docstrings
in Python”””

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


about the code. However, they are usually used for brief explanations and are
less structured than docstrings.
3. Type hints: Python 3.5 introduced type hints, which are annotations that provide
a means of statically providing information about the type of values within the
Python code.
For Example:
def typeHintDemo(username: str) - > str:
return “Welcome User:” + username

The username:str indicates the name argument should be of type str. The ->
syntax indicates the greet() function will return a string. In the above example,
we have fixed the type of function parameters and return type.
4. External documentation: The code may have external documentation, such
as user guides, technical specifications, or design documents, if it is a component
of a bigger project. These can offer further context and details about how the
code fits into the bigger picture.
In addition to helping, you maintain and share your code, good documentation
can also make it simpler for other developers to understand and utilize your code.

1.7.3 Indentation and Code Blocks

Python relies heavily on indentation to define code blocks and specify the scope of
statements. It does not use {} for code blocks. Indentation is used to organize the
Self-Instructional
Material 11

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES code and group statements together. A number of spaces or tabs are used to indent
the blocks of code; the standard convention in Python is to use four spaces for indentation.
Loops and conditional statements are examples of control flow statements that are
frequently used in code blocks.
Here’s an example that demonstrates indentation and code blocks in Python:
For Example:
Consider the following if-else statement
x = 50
if x > 40:
print(“x is greater than 40”) # This line is indented,
part of the if block
else:
print(“x is not greater than 40”) # This line is indented,
part of the else block

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


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

1.8 SYNTAX AND SEMANTICS OF PYTHON

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

1.8.1 Syntax

Syntax refers to the structure, grammar, and rules of a programming language. It defines
how code should be written and the order in which statements should appear. A program
with incorrect syntax will result in a syntax error and won’t be executed.

Self-Instructional
12 Material

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


School of Open Learning, University of Delhi
Introduction to Python Programming

For Example: NOTES


x = 30
y = 15
if x < y:
print(“y is greater”)
else:
print(x is greater) #This statement will generate syntax
error since the print statement is expected to be in quotes

A syntax error typically results from missing reserved keywords, spaces,


incorrectly placed quotations, indentations and block usage, erroneous declarations,
inappropriate function calls, and improper function definitions.

1.8.2 Semantics

Semantics is concerned with the interpretation and meaning of code. It focuses on


determining whether the code follows logic and results in the desired result. Even
when a program’s syntax and semantics are accurate, it could still produce false results
even though it runs without errors.
For Example:
# user defined function to calculate division of two numbers
def divide(a, b):
result = a / b
return result
x = int(input(“enter the value of x”))
y = int(input(“enter the value of y”))
quotient = divide(x, y) # This statement might result in
Semantics Error when we pass y as 0
print(quotient)

Note: This above code is syntactically correct. However, it might raise a semantic
error whenever we pass denominator as zero. As division by zero is not possible
mathematically.
Self-Instructional
Material 13

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES Let’s consider an example for better understanding of importance of semantics


in code.
For Example:
num1 = int(input(“enter the first number”))
num2 = int(input(“enter the second number”))
# find the average of two numbers
average_of_numbers = num1+num2 /2 # This statement is
semantically incorrect
print(average_of_numbers)

Note: This above code is again syntactically correct. However, when we try to execute
the above code, python interpreter will read the expression for average computation
as:
num1 + (num2 / 2) instead of ( num1 + num2 ) / 2
Understanding both the syntax and semantics of Python is necessary to write
code that is accurate and meaningful. While syntax guarantees that your code is
appropriately constructed, semantics ensures that your code behaves as intended and
produces the desired outcome.

In-Text Questions
1. Why documentation is necessary in programming languages?
2. Does the absence of a syntax error in a piece of code guarantee that the
intended result will always be achieved? Explain using an example.

1.9 PYTHON INTERPRETER AND SHELL

In Python, the interpreter and shell are two separate components that work together
to execute Python code. Let’s understand each of them:
 Python Interpreter: A program that reads and runs Python code is known as
the Python interpreter. It is in charge of reading the code line by line, running it,
Self-Instructional and creating the desired result. The interpreter can be seen as the engine that
14 Material
powers the execution of Python programs.

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


School of Open Learning, University of Delhi
Introduction to Python Programming

 Python Shell: The Python shell is an interactive interface that allows you to NOTES
enter and execute Python code interactively. When you type Python commands
or expressions into the prompt, the shell immediately executes them and outputs
the results. The Python shell is helpful for performing fast experiments, testing
brief sections of code, and learning how Python constructs behave.
In conclusion, the Python shell is a user-friendly interface that offers an interactive
way to deal with the interpreter, whereas the Python interpreter is the underlying program
that runs Python code.

1.9.1 Interpreted vs. Compiled Languages

Python is generally categorized as an interpreted language, but it is more accurate to


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

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 1.9.2 Installing Python and Setting up the Interpreter on Windows

Step 1) Downloading the Python Installer

 Go to the official Python download page: https://www.python.org/downloads/


windows/ for Windows.
 Find a stable Python 3 release and click the appropriate link for your system to
download the executable file: Windows installer (64-bit) or Windows installer
(32-bit).

Step 2) Running the Executable Installer

 We assume you have chosen 64-bit windows installer. After the installer is
downloaded, double-click the .exe file, for example python-3.10.10-amd64.exe,
to run the Python installer.
 Select the “Install launcher for all users” checkbox, which enables all users of
the computer to access the Python launcher application.
 It is advisable to select the “Add python.exe to PATH” checkbox, which enables
users to launch Python from the command line.
Self-Instructional
16 Material

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


School of Open Learning, University of Delhi
Introduction to Python Programming

NOTES

 Click Next to continue.

Step 3) Locate the Python directory in your system


 C:\Program Files\Python310: If you selected “Install launcher for all users”
during installation, then the directory will be system wide.
 C:\Users\Your_Name\AppData\Local\Programs\Python\Python310: If
you didn’t select “Install for all users” during installation, then the directory will
be in the Windows user path.

Step 4) Verify the Python Installation

You can verify whether the Python installation is successful either through the command
line or through the Integrated Development Environment (IDLE) application, if you
chose to install it.
 Using Command Prompt
Go to Start and enter “cmd” in the search bar. Click Command Prompt.
Enter the following command in the command prompt:
python —version #This command is used to check which python
version has been installed on your machine

Self-Instructional
Material 17

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES

 Using Python IDLE application


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

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

1.10 EXECUTING SIMPLE PYTHON PROGRAMS

To execute Python programs, multiple options are available. Let’s discuss them in
detail below:
1. Using the Python Interpreter
You can run a Python program by executing it directly using the Python interpreter
from the command line or terminal. To open the interactive mode, command
line or terminal and type python command.
Self-Instructional
18 Material

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


School of Open Learning, University of Delhi
Introduction to Python Programming

It will open the following prompt where we can execute the Python statement. NOTES

At the Python prompt, you can directly type Python statements or expressions
and press Enter to execute them. For example, you can perform simple arithmetic
calculations, assign values to variables, define functions, import modules, etc.

2. Using an Integrated Development Environment (IDE)


If you wish to execute the python program inside an IDE like Visual Studio
Code, PyCharm, Spyder or Atom, you can create a new Python file, enter your
code in it. The “Run” or “Execute” button is typically present in IDEs, however
you can alternatively run programs by utilizing keyboard shortcuts as well.
3. Using a Code Editor
First, create Python file using any editor like Notepad, Notepad++, or Vim.
Then, write your code, and save it with a .py extension. Open a command
prompt or terminal, go to the directory where the file is located, and use the
python or python3 command followed by the filename to run the program.

Self-Instructional
Material 19

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES $ python program.py


Regardless of the method you choose, the Python interpreter will read your
code, interpret it, and execute it, producing any desired output or performing the
actions specified in the program. Make sure that Python is installed and properly set
up on your system before attempting to execute Python programs.

1.10.1 Writing your First Python Program

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

The Python interpreter will execute the print statement, and you should see the
output Hello World displayed on console.
Option 2: Using code Editor
To run this program, you can follow these steps:
1. Open a text editor and create a new file.
2. Type the following statement into the file.
print(“Hello World !!”)

Self-Instructional
20 Material

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


School of Open Learning, University of Delhi
Introduction to Python Programming

NOTES

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

Now, you have a Python program saved as firstPythonProgram.py. To execute it,


follow these instructions:
1. Open a command prompt (Windows) or a terminal (macOS/Linux).
2. Navigate to the directory where file named firstPythonProgram.py is located.
You can use the cd command to change directories.
Self-Instructional
Material 21

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES

3. Type python firstPythonProgram.py and press Enter.

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

1.11 SUMMARY

Python is a popular programming language that enables you to create code that is easy
to understand. It is a great pick for beginners due to its simplicity and use. Overall,
Python is a strong and user-friendly language that enables users to use computers to
solve problems and produce a wide range of fascinating things. Python relies heavily
on indentation to define code blocks and statement scope.
Self-Instructional
22 Material

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


School of Open Learning, University of Delhi
Introduction to Python Programming

Python is a hybrid language that combines performance enhancements similar NOTES


to compiled languages with the adaptability and simplicity of an interpreted language.
Python interpreter, which reads and executes the Python commands line by line, is
needed for the seamless running of Python programs. The Python shell enables interactive
use of the Python interpreter.

1.12 GLOSSARY

 High Level Programming Language: A programming language which allows


a programmer to write codes that are closer to human languages.
 Low Level Programming Language: Programming languages that provides
little or no abstraction from the computer architecture.
 Compiler: It is a program that coverts whole source code into intermediate
machine code.
 Interpreter: It refers to a software which converts the high-level instructions
to machine-level language line by line.
 Syntax: Syntax refers to the structure, grammar, and rules of a programming
language.
 Semantics: It refers to the interpretation of the code.
 Python Shell: It provides a medium to use python interpreter in an interactive
manner.
 IDE: It is a software for building applications that combines common developer
tools into a single Graphical User Interface (GUI).

1.13 SELF-ASSESSMENT QUESTIONS

1. What are the features of Python?


2. Differentiate between Compiled and Interpreted Language?
Self-Instructional
Material 23

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

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

1.14 REFERENCES

1. Kamthane, A. N., & Kamthane, A. A. (2020). Programming and Problem


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

Self-Instructional
24 Material

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


School of Open Learning, University of Delhi
UNIT II: CREATING PYTHON PROGRAMS

LESSON 2: FUNDAMENTALS OF PYTHON


PROGRAMMING

LESSON 3: CONTROL STRUCTURES

LESSON 4: ERROR AND EXCEPTION HANDLING IN


PYTHON
Fundamentals of Python Programming

LESSON 2 NOTES

FUNDAMENTALS OF PYTHON PROGRAMMING

Pratibha Yadav
Assistant Professor
Shyama Prasad Mukherji College
Email-Id: pratibha.123@spm.du.ac.in
Structure
2.1 Learning Objectives
2.2 Introduction
2.3 Tokens
2.4 Literals
2.4.1 Numeric Literals
2.4.2 String Literals
2.4.3 Boolean Literals
2.4.4 Literal Collections
2.4.5 Special Literals
2.5 Data Types
2.6 Variables
2.6.1 Variable Assignment
2.6.2 Variable Types
2.7 Keywords & Identifier
2.7.1 Keywords
2.7.2 Identifier
2.8 Expressions & Operators
2.8.1 Arithmetic Operators
2.8.2 Relational Operators
2.8.3 Logical Operators
2.8.4 Bitwise Operators
2.8.5 Assignment Operators
2.8.6 Identity Operators
2.8.7 Membership Operators
2.8.8 Operators Precedence
2.9 Statements Vs Expressions Self-Instructional
Material 27

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 2.10 Strings


2.11 Input Output Statements
2.11.1 Input
2.11.2 Eval Function
2.11.3 Output
2.12 Summary
2.13 Glossary
2.14 Self-Assessment Questions
2.15 References

2.1 LEARNING OBJECTIVES

After completion of this lesson, you will be able to learn about:


 Tokens
 Literals and their usage in representing data
 Identifiers and keywords in Python and their significance
 Data types available in Python
 Operators and expressions in Python
 String declaration
 Capturing user input and displaying output in Python

2.2 INTRODUCTION

Python is one of the most popular languages used today. Amidst the various features it
provides, a key advantage is that it has a simple syntax and it is very easy to learn. In
the previous chapter, we saw how easy it was to print a statement onto the screen.
The syntax of Python is readily adaptable and bears a number of similarities with the
English language constructs. In this chapter, we will understand the basic building
Self-Instructional
blocks of the Python language that can be used to write programs suited for the
28 Material

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

application at hand. We will learn about the concept of tokens and the different types NOTES
of Python literals and available built-in data types. Then, we will explore the usage of
variables, keywords and identifiers in Python. We will further see how to write
expressions in Python and the different operators available, their usage, precedence
and associativity with the help of several examples. The chapter also covers basics on
strings and how to use them in your program. Finally we discuss on the essential
component of handling input and output in Python programs.

2.3 TOKENS

In Python, a token refers to the smallest individual unit of a program that the Python
interpreter can understand. It can be thought of as a building block of the Python
language. Python programs are made up of various tokens, which include identifiers,
keywords, operators, literals, and punctuations.
1. Identifiers: These are names given to variables, functions, classes, or other
entities. They must follow certain naming rules and conventions. For example:
x=5
2. Keywords: These are reserved words that have special meanings in Python
and cannot be used as identifiers. For Example: while, for, if, else etc.
3. Operators: These are symbols used to perform operations on operands. Python
supports various operators, such as arithmetic operators (+, -, *, /), assignment
operators (=, +=, -=), comparison operators (==, !=, <, >), logical operators
(and, or, not), and more.
4. Literals: These are fixed values that are directly specified in the code.
5. Punctuations: These are symbols used for grouping, separating, or marking
different parts of the code. Examples of punctuations in Python include
parentheses (()), commas (,), colons (:), semicolons (;), and more.
Tokens are important for the Python interpreter to correctly parse and understand
the program structure. They help in determining the syntax and semantics of the code,
allowing the interpreter to execute the program accordingly.
Self-Instructional
Material 29

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES
2.4 LITERALS

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

2.4.1 Numeric Literals

Numeric literals represent numerical values and falls under three categories: integer,
float and complex.

2.4.1.1 Integer Literals

The numerical literals that are zero, positive or negative natural numbers and contain
no decimal points are integers. The different types of integers are:
 Decimal- It contains digits from 0 to 9. The base for decimal values is 10.
For Example:
# Decimal literal
x = 10
y = -5

 Binary- It contains only two digits - 0 and 1. The base for binary values is 2
and prefixed with “0b or 0B”.

Self-Instructional
30 Material

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

For Example: NOTES


# Binary literal
b1 = 0B1010 # this is binary representation of decimal value 10
b2 = 0b00111 # this is binary representation of decimal value 7

 Octal- It contains the digits from 0 to 7. The base for octal values is 8. In
Python, such values are prefixed with “0o or 0O”.
For Example:
# Octal literals
x = 0o123 # this is octal representation of decimal value 83
x = 0O34 # this is octal representation of decimal value 28

 Hexadecimal- It contains digits from 0 to 9 and alphabets from [A-F] or [a-f].


It starts with “0x or 0X”
For Example:
# Hexadecimal literals
x = 0xA1 # this is hexadecimal representation of decimal value
161
y = 0X9b # this is hexadecimal representation of decimal value
155
y = 0x20 # this is hexadecimal representation of decimal value
32

2.4.1.2 Floating-Point Literals

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

Self-Instructional
Material 31

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 2.4.1.3 Complex Literals

Complex Literals are represented using X+Yj, where X is the real part and Y is the
imaginary part.
For Example:
# Complex literals
c1 = 3+6j
c2 = complex(2,9)

2.4.2 String Literals

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

In the above examples, Peter, Smith and Mr. Peter Smith 24, My Street,
Kingston, New York are string literals

2.4.3 Boolean Literals

Boolean literals represent the truth values: True or False.

For Example:
# Boolean literals
flag = True
x = False
Self-Instructional
32 Material

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

2.4.4 Literal Collections NOTES

Python provides literals for representing collections of values, such as lists ([4, 5, 8]),
tuples (("John", "Mary", "Mike")), dictionaries ({'key': 'value'}), and sets ({1, 2, 3}).
For Example:
# List literal
fruits = [“Apple”, “Mango”, “Orange”]
print(fruits)

————— OUTPUT —————


[‘Apple’, ‘Mango’, ‘Orange’]

2.4.5 Special Literals

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

2.5 DATA TYPES

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

Self-Instructional
Material 33

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES Data Type Category Description Example


Numeric Int used to store signed age = 18
integers sem = 4
Float used to store floating weight = 40.8
point(real) numbers average = 78.5
Complex used to store complex c = 2 + 3j
numbers a = 7 – 5j
Text Str used to store sequence of name = "John"
characters address = "New York, US"
Boolean Bool holds either of the two flag = False
values: True or False is_Available = True
Sequence list holds ordered collection of l = [ 1, 2, 3, 4, 5]
items and are mutable names = ["Preeti", "Asha",
"James" ]
tuple holds ordered collection of t = (1, 3, 5, 8)
items but are immutable
range returns a sequence of a = range(5)
numbers [0, 1, 2, 3, 4]
Set set holds unordered collection s = {10, 15, 20}
of unique items and are
mutable
frozenset holds unordered collection s = {10, 15, 20}
of unique items and are fz = frozenset(s)
immutable s1 = frozenset({'A', 'B', 'C'
}}
Mapping dict Holds key-value pair person = {'name' : 'Jane',
'country' : 'USA', 'age': 35}
None None used to define a null or no a = None
value

2.6 VARIABLES

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

2.6.1 Variable Assignment

Self-Instructional
Variable assignment is done using a single equals sign (=). To assign a value to a
34 Material variable, you just assign the variable name on the left hand side of ‘=’ and value on the

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

right hand side of ‘=’ and then start using it. Python supports chained assignment as NOTES
well which means we can assign same value to multiple variables.
For Example:
age = 25 # age is a variable which is assigned value 25
print(age)

————— OUTPUT —————


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

————— OUTPUT —————


40 40 40

2.6.2 Variable Types

Unlike many programming languages, Python, is a dynamically typed language which


means variables need not be declared or defined in advance. The python interpreter
binds the data type of a variable on the basis of the value assigned to it.
In Python, we can check the type of the variable via type() function. This function
returns the type of the data passed to it as argument.
For Example:
a = 10 # a is a variable which is assigned value 10
print(a)
print(type(a)) # Since 10 is an integer value, here type of
variable a is integer

————— OUTPUT —————


10
<class ‘int’>

a = “Hello World!!” Self-Instructional


Material 35

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES print(a)
print( type(a)) # Since “Hello World!!” is a string, hence type
of variable a is now string not integer

————— OUTPUT —————


Hello World!!
<class ‘str’>

In Python programming, everything is an object, therefore variables are actually


instances (objects) of data types, which are classes.

2.7 KEYWORDS & IDENTIFIER

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

2.7.1 Keywords

Keywords are reserved words in Python that have predefined meanings. These
keywords are used to define the syntax and structure of the language. Here are some
commonly used keywords in Python:
False def if raise
None del import return
True elif in try
And else is while
As except lambda with
Assert finally nonlocal yield
Break for not
Class from or
Continue global pass

Self-Instructional
36 Material

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

2.7.2 Identifier NOTES

A name assigned to an entity, such as a variable, a function, a class, etc., is called an


identifier. It acts as a unique identifier within the program and is used to access and
control these entities. Identifiers are case-sensitive i.e., sum and Sum are different
identifiers. There are some rules for naming the identifiers which have been discussed
below:
• An identifier can only be a combination of letters [a-z, A-Z], digits [0-9] or
underscore ( _ )
• It must not start with a digit
• It should not be a reserved word i.e., keyword
• It should not contain whitespace or any special character except underscore
Let’s see some examples of valid and invalid identifiers:
Valid Identifiers Invalid Identifiers
firstName first Name
num1 1num
true True
_var1 *var
find_largest find:largest
calculate_sum Calculate sum

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

Self-Instructional
Material 37

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES
In-Text Questions
1. Is python static typed or dynamic typed language?
2. Which of the following literals are invalid? Give reasons.
• pass
• age_of_person
• minute
• 10th_student
• My-income
• Return

2.8 EXPRESSIONS & OPERATORS

Operators are special symbols that perform some operation on data or variables. The
values that an operator acts upon are called operands. An expression is a combination
of operands and operators.
For Example:
a=5
a + 5 # this is an expression where a and 5 are operands and + is
operator

Python provides many built-in operators to perform computations on data values.


There are primarily 7 types of operators:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment operators

Self-Instructional
38 Material

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

6. Identity operators NOTES


7. Membership operators

2.8.1 Arithmetic Operators

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

Operator Description
+ addition
- subtraction
* multiplication or product
/ division
// floor division, returns floored value of the
quotient
% modulo, returns the remainder
** exponent

For Example:
a = 10
b=3
print(a + b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)

————— OUTPUT —————


13
3.3333
3
1
1000

Self-Instructional
Material 39

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 2.8.2 Relational Operators

Relational operators compared two operands and accordingly returns Boolean value
i.e, True or False depending on the outcome of the comparison.
Operator Description
> greater than
>= greater than or equal
< less than
<= less than or equal
== equal to
!= not equal to

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

————— OUTPUT —————


True
False
True
True

2.8.3 Logical Operators

Logical operators are used for decision making and returns True or False depending
on the condition. They are generally used to combine multiple conditional statements.

Self-Instructional
40 Material

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

Operator Description NOTES


and returns True if both LHS and RHS operands are True
or returns True if either of the LHS or RHS operand is True
not returns True if operand is False and vice-versa

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

————— OUTPUT —————


False
False
True

2.8.4 Bitwise Operators

Bitwise operators act on bits and allows a programmer to access and manipulate
individual bits of the operands.
Operator Name Description
& Bitwise AND produces 1 if both the bits of the operands
are 1 and 0 otherwise
| Bitwise OR produces 0 if both the bits of the operands
are 0 and 1 otherwise
^ Bitwise XOR produces 1 if both the bits of the operands
are different and 0 otherwise
~ Bitwise NOT it inverts all the bits of operand
>> Right Shift shifts the value of the left-hand side operand
to the right as many times as the value on the
right of the operator
<< Left Shift shifts the value of the left-hand side operand
to the left as many times as the value on the
Self-Instructional
right of the operator Material 41

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES For Example:


a = 10 # binary representation of the value 10 : 0000 1010
b = 20 # binary representation of the value 20 : 0001 0100
c = 15 # binary representation of the value 15 : 0000 1111
print(a & b) # binary representation of result after & : 0000 0000
print(a | c) # binary representation of result after | : 0000 1111
print(a ^ b) # binary representation of result after ^ : 0001 1110
print(a >> 2) # binary representation of result after >> : 0000 0010
print(b << 3) # binary representation of result after <<: 1010 0000
print(~a) # binary representation of result after ~ : 1111 0101

———— OUTPUT —————


0
15
30
2
160
-11

2.8.5 Assignment Operators

Assignment operators are used to assign values to the variables.


Operator Description
= Assignment operator: assigns the value of the right
expression to the left-hand side operand
+= add left and right operands and assigns the result to the left
operand
-= subtract left and right operands and assigns the result to the
left operand
*= multiply left and right operands and assigns the result to the
left operand
/= divide left and right operands and assigns the result to the left
operand
Self-Instructional
42 Material

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

NOTES
//= performs floor division of the left and right operands and
assigns the result to the left operand
%= performs division of the left and right operands and assigns
the remainder to the left operand
**= performs exponentiation of the left operand by the value of
right operand and assigns the result to the left operand
&= performs bitwise AND to the left and right operands and
assigns the result to the left operand
|= performs bitwise OR to the left and right operands and
assigns the result to the left operand
^= performs bitwise XOR to the left and right operands and
assigns the result to the left operand
~= performs bitwise NOT to the left and right operands and
assigns the result to the left operand
>>= performs bitwise right shift to the left operand using the right
operand and assigns the result to the left operand
<<= performs bitwise left shift to the left operand using the right
operand and assigns the result to the left operand

For Example:
a = 5
b = 50
c = 10
a +=c # a = a + c
b *=2 # b = b * 2
c %=4 # c = c % 4
print(a)
print(b)
print(c)

————— OUTPUT —————


15
100
Self-Instructional
2 Material 43

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 2.8.6 Identity Operators

Identity operators compare the memory location of two objects. It returns True or
False depending on whether both the objects refer to same memory or not. Python
provides a built-in id() function to fetch the unique id of an object.

Operator Description
is returns True if both LHS and RHS operands points to same
memory location
is not returns True if both LHS and RHS operands points to
different memory location

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

————— OUTPUT —————


1865754018320 # unique id assigned to variable a
1865754018320 # unique id assigned to variable b
True
False
1865791630400 # unique id assigned to c
1865791630080 # unique id assigned to d
False
Self-Instructional
44 Material

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

2.8.7 Membership Operators NOTES

Membership operators checks the presence of a value in a sequence. It returns True


or False as outcome after checking whether a given value exists in a sequence or not.

Operator Description
in returns True if value is present in sequence and False
otherwise
not in returns True if value is not present in sequence and
False otherwise

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

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


False
True
False

2.8.8 Operators Precedence

The sequence in which operations are carried out is referred to as operator precedence.
If the expression contains two operators of equal precedence, then associativity rule is
applied to break the tie. Almost all operators obey left to right associativity, with the
exception of ** (Exponentiation). Associativity from left to right means that an
expression will be evaluated in a left to right fashion.

Self-Instructional
Material 45

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES Operator Description


() Parentheses
** Exponentiation
+ - ~ Unary plus, unary minus, and bitwise NOT
Multiplication, division, floor division, and
* / // %
modulus
+ - Addition and subtraction
<< >> Bitwise left and right shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is Relational operators, identity operators,
not in not in and membership operators
Not Logical NOT
And Logical AND
Or Logical OR

Understanding operator precedence and associativity is crucial for writing correct


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

2.9 STATEMENTS VS EXPRESSIONS

In Python, a statement is a line of code that performs an action or a command. It


usually doesn’t produce a value or return anything. Some examples of statements in
Python include variable assignments, function definitions, control flow structures (such
as if-else statements and loops), and import statements.
On the other hand, an expression is a piece of code that evaluates to a value. It
can be a combination of variables, literals, operators, and function calls that produce a
result. Expressions can be used within statements or on their own.
Self-Instructional
46 Material

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

NOTES
2.10 STRINGS

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

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


Jade
New York
US

In later chapters, you will learn about indexing and slicing in strings, concatenating
strings, and various string manipulation methods.

In-Text Questions
1. Explain the significance of precedence and associativity during evaluation of
an expression?
2. What is the difference between expressions and statement?
3. What are the different ways of declaring a string in Python?
4. Does the fact that two objects have the same value imply that they will always
have the same identity? Explain with the help of an example.

Self-Instructional
Material 47

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES
2.11 INPUT OUTPUT STATEMENTS

Input and output are essential concepts in programming that allow communication
between a program and its users. Input refers to the data or information provided to a
program, while output refers to the information produced or displayed by the program.

2.11.1 Input

input() function is used to capture the user input from the console. It displays a prompt,
waits for the user to enter a value, and returns the input as a string.

The syntax of the input function is:


input( ‘prompt string’ )
# prompt is an optional string which we wish to display on
screen

When using the input() function, it is advisable to include descriptive prompts to


guide the user on what to enter. The descriptive prompts help in enhancing the user
experience.
For Example:
userName = input(“Enter the name of user:”)
When you run the above statement in Python IDLE, it will
wait until user enters some input.

Self-Instructional
48 Material

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

NOTES

The input() function can be used to accept various types of input, such as
numbers, strings, or even expressions. However, the input is always stored as a string,
so you may need to convert it to the desired data type.

Try executing the below statements in python IDLE:


num1 = input( “Enter the first number:”)
print(type(num1))

Irrespective of the value entered by the user, input() function always returns
string value. Hence, if you check the data type of the value returned by input(), outcome
will always be ‘str’ only.

Now, to convert the user input to a specific data type, you can use type casting
functions like int(), float(), or bool(). Type casting is necessary when performing
calculations or comparisons with the input.

Try executing the below statements in python IDLE:


num1 = int(input(“ Enter the value :”))
print(type(num1))
# int() will change the data type of user input from string
to integer.

Self-Instructional
Material 49

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES

2.11.2 Eval Function

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

The general syntax of eval() function is:


eval( string expression )

For Example:
result = eval( “4 + 5”)
print( result)
result = eval( ‘ 3 ** 3’ )
print( result)
print( eval( ‘7 - 6’))

————— OUTPUT —————


9
27
1

2.11.3 Output

Python provides print() function to display the output on console or any other standard
output device.

Self-Instructional
50 Material

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

The syntax of the output function is: NOTES


output (value(s), sep = “, end = ”, file = file, flush =
flush)

• value(s) are the values to be printed on the screen


• sep specifies how values will be separated inside the same print statement.
Default is ‘ ‘ i.e., space
• end specifies what to print at the end of the print statement. Default is ‘\n’
i.e., new line
• file specifies where to display the output. Default is sys.stdout i.e., screen
• flush specifies whether output will be flushed (True) or buffered (False).
Default is False
For Example:
print(‘Hello’, ‘World’)
print(‘Hello’, ‘World’, ‘!!’, sep = ‘-’)
print(‘Hello’, ‘World’ , sep = ‘\t’, end = ‘$$’)

————— OUTPUT —————


Hello World # values are separated by default with space
and new line is added after print
Hello-World-!! # values are now separated by ‘-’ and new
line is added after print
Hello World$$ # values separated by tab and ‘$$’ added
after print

Input and output are crucial for building interactive and dynamic programs.
Input can be used to gather user preferences and output allows programs to display
results or save data to files.

2.12 SUMMARY

In Python, the constant values that can’t be mutated are called literals. Variable is the
name of a memory location and are used to store and manipulate data values. Python Self-Instructional
Material 51

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES is a dynamically typed language, meaning that the type of a variable is decided based
on the data that is provided to it. In Python, variables are actually objects and data
types are actually classes. Operators are widely used to perform computations on the
variables or data values. Integration of input and output functions are required to build
an interactive and dynamic program. User preferences can be captured by input()
functions, and print() can be used to display results.

2.13 GLOSSARY

• Token: It is the smallest individual unit in a program.


• Identifier: It represents fixed value in a program which cannot be changed.
• Variable: It is the name of a memory location where we store data.
• Operators: These are used to perform operations on values or variables.
• Punctuations: These are used to separate and mark different parts of code.
• Statement: It is a line of code that performs some action but does not produce
any output.
• Expression: It is a combination of variables, literals, operators, and function
calls that produce a result.
• Precedence: It determines the priority of operators.
• Associativity: It is used to determine the order of evaluation, when two operators
have same precedence.
• Input function: It is used to capture the user input from the console.
• Eval function: It evaluates the expression passed in the form of string as input
and returns the result.
• Output function: It is used to display results on screen or any other standard
output device.

Self-Instructional
52 Material

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


School of Open Learning, University of Delhi
Fundamentals of Python Programming

NOTES
2.14 SELF-ASSESSMENT QUESTIONS

1. What is the difference between following operators:


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

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

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

2.15 REFERENCES

1. Kamthane, A. N., & Kamthane, A. A. (2020). Programming and Problem


Solving with Python. McGraw-Hill Education.
2. Balaguruswamy, E. (2018). Introduction to Computing and Problem Solving
using Python, 2nd edition, McGraw Hill Education.
3. Saeed, A., Ayeva, A., Ayeva, K. (2020). Python In - Depth: Use Python
Programming Features, Techniques, and Modules to Solve Everyday
Problems. India: BPB PUBN.
Self-Instructional
54 Material

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


School of Open Learning, University of Delhi
Control Structures

LESSON 3 NOTES

CONTROL STRUCTURES

Pratibha Yadav
Assistant Professor
Shyama Prasad Mukherji College
Email-Id: pratibha.123@spm.du.ac.in
Structure
3.1 Learning Objectives
3.2 Introduction
3.3 Conditional Statements
3.3.1 if Statement
3.3.2 If - Else Statement
3.3.3 If – ELIF - Else LADDER
3.4 Loops in Python
3.4.1 For Loop
3.4.2 while Loop
3.4.3 Nested Loop
3.5 Loop Control Statements
3.5.1 Break Statement
3.5.2 Continue Statement
3.5.3 Pass Statement
3.6 Summary
3.7 Glossary
3.8 Self-Assessment Questions
3.9 References

3.1 LEARNING OBJECTIVES

In this chapter, you will be able to explore about:


 conditional statements and their significance
Self-Instructional
Material 55

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES  iterative statements


 loop control statements

3.2 INTRODUCTION

Programs in the real world almost always need the ability to check some conditions
and respond accordingly. In order to bring out this effect, programming languages
have conditional statements that help incorporate change of flow of control on the
basis of decisions taken as per the conditions outlined by real world scenarios. In
Python, if-elif-else are the conditional constructs that help achieve conditional execution
of code. Also, we often need to repeat a set of statements until a particular condition
is satisfied. Looping hence is also an essential programming construct. Python provides
two statements for implementing loops: for and while. In this chapter, we explore the
conditional and loop statements in Python with the help of various examples. Further,
we also look at the loop control statements provided in Python to alter the flow of
iterations. Python has three loop control commands: break, continue and pass. These
are frequently used to manage the controlled execution of iterative statements. An
adequate knowledge of these constructs is quintessential for writing efficient, compact
and powerful code.

3.3 CONDITIONAL STATEMENTS

Conditional statements as the name implies allow us to execute different blocks of


code based on specific conditions. In Python, we have three types of conditional
statements: if statement, if - else statements, if - elif - else ladder. Let’s discuss each of
the conditional statements in detail.

3.3.1 if Statement

The if statement determines whether a block of code will be executed or not on the
Self-Instructional basis of a specified condition.
56 Material

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


School of Open Learning, University of Delhi
Control Structures

The general syntax is as follows: NOTES


if condition:
Statement 1
Statement 2
Statement 3
Statement 4
# In the above syntax, Statement 1, Statement 2, and Statement
3 will execute only if the condition associated with the if
statement is True.

Let’s understand the working of if statement using an example.


For Example:
age = int(input(“Enter the age of person”)) #input function
is used to capture user input
if age >= 18:
print(“Congratulations !!”)
print(“You are eligible to vote”)
print(“You are Outside if block now”)

Let’s understand the working of above example based on different scenarios.

Scenario 1:

If user enters the value of age = 20


Output:
Congratulations !!
You are eligible to vote
You are Outside if block now

Scenario 2:

If user enters the value of age = 10.


Output:
You are Outside if block now Self-Instructional
Material 57

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES Working of if statement

Condition is True Condition is False


if age >= 18: if age >= 18:
# Block of code # Block of code
# code outside if block # code outside if block
The block of code associated with the if block The block of code associated with the if block
will execute only when the value of age will be skipped if the value of age variable is
variable is greater than or equal to 18 less than 18

3.3.2 If - Else Statement

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

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

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

Let’s understand the working of above example based on different scenarios.

Scenario 1:

Self-Instructional If user enters the value of age = 35.


58 Material

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


School of Open Learning, University of Delhi
Control Structures

Output: NOTES
Congratulations!!
You are eligible to vote
You are outside of if-else block now

Scenario 2:

If user enters the value of age = 16.


Output:
You are not eligible
You are outside of if-else block now

Working of if - else statement

Condition is True Condition is False


if age >= 18: if age >= 18:
# Block of code # Block of code
else: else:
# Block of code # Block of code
# code outside if # code outside if
(a) The block of code associated with if (c) The block of code associated with else
statement will execute only when statement will execute if the value of age
the value of age variable is greater variable is less than 18.
than or equal to 18 (d) Code block associated with if statement
(b) Code block associated with else will be skipped
statement will be skipped

3.3.3 If – ELIF - Else LADDER

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

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES .
.
.
else:
# Code to be executed if none of the above conditions are
true

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

if marks >= 60:


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

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

Let’s understand the working of above example based on different scenarios.

Scenario 1:

If user enters the marks = 85


Output:
You scored First Division
You are outside if - elif block now

Scenario 2:

If user enters the marks = 58.


Self-Instructional
60 Material

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


School of Open Learning, University of Delhi
Control Structures

Output: NOTES
You scored Second Division
You are outside the if - elif block now

Scenario 3:

If user enters the marks = 35.


Output:
You scored Third Division
You are outside if - elif block now

Working of if - elif statement

Condition 1 is True Condition 1 is False and Condition 1 is False and


Condition 2 is True Condition 2 is False
if marks >= 60: if marks >= 60: if marks >= 60:
# Block of code # Block of code # Block of code
elif marks >= 40 and marks elif marks >= 40 and marks < elif marks >= 40 and marks <
< 60: 60: 60:
# Block of code # Block of code # Block of code
else: else: else:
# Block of code # Block of code # Block of code
# code outside if # code outside if # code outside if
(a) The block of code (c) The block of code (e) The block of code
associated with if- associated with elif- associated with else-
statement will statement will execute statement will execute if
execute if the value of if the value of marks the value of marks
marks variable is variable is in range [ 40, variable is less than 40.
greater than or equal 60). (f) Code block associated
to 60. (d) Code block associated with if and elif
(b) Code block associated with if and else statements will be
with elif and else statements will be skipped
statements will be skipped
skipped

In-Text Questions
1. What is the purpose of a conditional statement in programming language?
2. Under what circumstances would you prefer the if - elif ladder to if else?? Self-Instructional
Material 61

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES
3.4 LOOPS IN PYTHON

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

3.4.1 For Loop

Python’s for loop is designed to iterate over a sequence such as list, tuple, dictionary,
or other iterable objects of Python. The for loop iterates over a sequence and executes
a block of code for each element present in the sequence. The process of traversing a
sequence is known as iteration. The for loop is usually used when the number of
iterations is known.

The general syntax is as follows:


for item in sequence:
# block of code to be executed for each item

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

for color in colors:


print(color)

————— OUTPUT —————


Red
Yellow
Green
Blue
Black

In the above example, we have created a list of colors. Initially, the color
Self-Instructional
62 Material variable is assigned the first element of the list, i.e., Red. Then, the print statement

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


School of Open Learning, University of Delhi
Control Structures

inside the loop is executed and “Red” will be displayed on the output screen. For the NOTES
next iteration, color variable is updated with the next element of the list, and the print
statement is executed again. The above for loop will execute until the last element of
the list has been accessed and after that loop will terminate.
Let’s have a look on another example to have a better understanding of the for
loop.
For Example:
numbers = range(4) # range function will create a sequence
of numbers from 0 to 3 i.e., [0, 1, 2, 3]
for i in numbers:
print(i)

————— OUTPUT —————


0
1
2
3

In the above example, first a sequence of numbers have been generated using
range() function and stored in numbers variable. Now, i will iterate over the sequence
and will process elements of the list one by one.

3.4.2 while Loop

In Python, while loops are used to iterate over a block of code until a certain condition
is satisfied. It repeatedly checks the condition before each iteration and the statement
that comes after the while loop is executed as soon as the condition becomes false.
The while loop is usually used when the number of iterations is unknown.

The general syntax is as follows:


while condition:
# Code to be executed while the condition is true

For Example:
count = 10 # initializing the loop variable Self-Instructional
Material 63

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES while count <= 15:


print(count)
count += 1

print(“Outside While Loop”)

————— OUTPUT —————


10
11
12
13
14
15
Outside While Loop

In the above example, count variable is initialized with 10. For 1 st iteration,
condition is True since 10 is less than 15. Hence, the block of code associated with
while loop will execute. First the print statement will execute and then value of count
variable will be increased by 1, making count = 11. Now, for next iteration, again
condition will be checked which is True as 11 <= 15. Again, block of code associated
with while loop will execute and count will be incremented by 1. This process will
repeat until value of count exceeds 15. When the value of count = 16, the loop will
terminate and program control will come outside the loop.
For Example:
counter = 5
while counter >= 0:
print(counter)
counter = counter - 2
print(“Exit”)

————— OUTPUT —————


5
3
Self-Instructional
64 Material

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


School of Open Learning, University of Delhi
Control Structures

1 NOTES
Exit

In this example, counter variable is initially set to 5 and value has been
decremented by 2 for each iteration. The loop will keep running until value of counter
is >= 0. When the condition becomes False, loop will terminate and program control
will jump outside of the loop.

3.4.3 Nested Loop

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

Syntax of using a nested for loop in Python


for element in sequence: # outer for loop
for element in sequence: # inner for loop
body of inner for loop
body of outer for loop

For Example:
#Printing multiplication table of 2 to 5
for i in range(2, 6): # outer loop iterates 4 times
for j in range(1, 11): # nested loop iterates 10 times
for each occurrence of i
print(i * j, end = ‘ ’ )
print() # empty print displays a blank
line
print(“Exit”)

Self-Instructional
Material 65

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES ————— OUTPUT —————


2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
Exit

Let’s try to understand the flow of loops given in above example.

i J Output
1 2 * 1 is printed
2 2 * 2 is printed
3 2 * 3 is printed
4 2 * 4 is printed
5 2 * 5 is printed
2
6 2 * 6 is printed
7 2 * 7 is printed
8 2 * 8 is printed
9 2 * 9 is printed
10 2 * 10 is printed
1 3 * 1 is printed
2 3 * 2 is printed
3 3 * 3 is printed
4 3 * 4 is printed
5 3 * 5 is printed
3
6 3 * 6 is printed
7 3 * 7 is printed
8 3 * 8 is printed
9 3 * 9 is printed
10 3 * 10 is printed
i * j expression will be executed
4 j will execute ten times
according to value of i and j
i * j expression will be executed
5 j will execute ten times
according to value of i and j
Self-Instructional
66 Material

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


School of Open Learning, University of Delhi
Control Structures

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

In-Text Questions
1. What is the difference between for loop and while loop?
2. What will be the output of the following code:
for i in range(5):
for j in range(1, 4):
print(i, j)

3. Find error(s) in the following code (if any) and rewrite the code after resolving
error(s):
counter = 10
while counter <= 20:
print(counter)

print(“We are outside of the while loop now”)

3.5 LOOP CONTROL STATEMENTS

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

3.5.1 Break Statement

The break statement is used to terminate a loop prematurely. When encountered, it


immediately exits the loop, and the program continues with the next statement after the
loop. When we wish to terminate the loop’s execution depending on a given
circumstance, we frequently utilize the break statement.
Self-Instructional
Material 67

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES The syntax of the break statement is:


break

Working of break statement

for Loop while loop


for item in sequence: while condition:
if condition: if condition:
break break
# code outside for # code outside while
For both the loops i.e, for and while, as soon as the break statement is encountered, it
terminates the loop and control of the program will jump outside of the loop.

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

————— OUTPUT —————


1
2
3
break
Exit from Loop

In the above example, for first three iterations, num will be printed as if condition
is not satisfied. Once the value of num is 4, the break is encountered and loop will be
terminated immediately. The control flow of program will jump outside of the loop.

Self-Instructional
68 Material

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


School of Open Learning, University of Delhi
Control Structures

Here’s an example that demonstrates the usage of break statement within a NOTES
loop:
languages = [ “JAVA” , “C”, “Python”, “C++”] # list of
programming language

for lang in languages:


if lang == “Python”:
break
print(lang)
print(“Exit from Loop”)

————— OUTPUT —————


JAVA
C
Exit from Loop

In the above example, for loop that iterates over the list of programming languages.
The if statement checks if the value of lang is equal to “Python” or not. When the lang
variable holds the value “Python”, the break statement is encountered, and the loop is
immediately exited. As a result, “Python” is not printed, and the loop is terminated.
The program then continues with the statement after the loop.

3.5.2 Continue Statement

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

The syntax of the continue statement is:


continue

Self-Instructional
Material 69

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES Working of continue statement

for Loop while loop


for item in sequence: while condition:
if condition: if condition:
continue continue
# code outside for loop # code outside while loop
As soon as the continue statement is encountered,current iteration is skipped, then the loop and
control of the program will start executing next iteration.

Example:
for num in range(1,6):
if num == 4:
print(“continue”)
continue
print(num)
print(“Exit”)

————— OUTPUT —————


1
2
3
continue
5
Exit

In the above example, the loop will execute 5 times staring from 1 till 5. When
value of num = 4, the continue statement is encountered and loop control will skip
executing the current iteration and immediately jump to beginning of the loop.

3.5.3 Pass Statement

The pass statement, which is a null statement, is frequently used as a placeholder for
Self-Instructional creating empty loops. The pass statement is also used to create classes, statements,
70 Material

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


School of Open Learning, University of Delhi
Control Structures

and functions that are empty. When pass statement is encountered, nothing happens. NOTES
Pass statements are typically used when a loop or function has not yet been implemented
but may be done in the future.

The syntax of the pass statement is:

pass
For Example:
for num in range(1,6):
pass
print(num)
print(“Exit”)

————— OUTPUT —————


5
Exit

In the above example, for loop does nothing. It will be iterated 5 times and once
the program control reaches the end of sequence, loop will terminate.
Note: pass statement and comment are entirely different. Comments are completely
ignored by the interpreter whereas pass is not.

3.6 SUMMARY

The most crucial feature of practically all programming languages is decision-making.


Decision structures enable you to alter the execution path of your program based on
the outcome of numerous expressions that return True or False. while loop control
statements are used to regulate the execution of loops, conditional statements are used
to execute certain code blocks based on specific criteria. To change the behaviour of
loops and conditional statements, utilize the break, continue, and pass statements.
Programmers can create Python programs that are more potent and efficient by knowing
these control structures.
Self-Instructional
Material 71

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES
3.7 GLOSSARY

 Conditional statement: Statements that allow us to execute different blocks


of code based on specific conditions.
 Loop: Programming construct to repeatedly execute a block of code until a
certain condition is met.
 Iteration: A single execution instance of a set of statements in a loop.
 Sequence: It is a generic term for an ordered set in Python.
 Nested loop: Loop inside the body of the outer loop allowing chaining of
loops.
 Control statements: These are statements that are used to manage how loops
are executed.
 Break: These are statements that are used to terminate a loop prematurely.
 Continue: These are statements that are used to skip the current iteration of a
loop and move to the next iteration.
 Pass: Null statement is referred to as pass.

3.8 SELF-ASSESSMENT QUESTIONS

1. Which loop control statement would you choose to exit from a loop early?
2. What is the difference between the break and continue statements in Python?
3. Write a program to find the largest among three numbers. Take input from the
user.
4. Write a program to check whether a given number is even or odd.
5. What is the usage of pass statement in Python?
6. Write a program to check whether a given number is prime or not.
7. Write a program to compute factorial of a number.
Self-Instructional
72 Material

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


School of Open Learning, University of Delhi
Control Structures

8. Write a program to compute factors of a given number. NOTES


9. Write a program to find the sum of following series:
 1 + 2 + 3 + ... + n
 1 – 3 + 5 – 7 + ...

1 1 1 1
   
1 2 3 n

1 1 1 1
   
1! 2! 3! n!
10. Write a program to print the following patterns on output screen:
# 1 2 3 4 5 5 5 5 5 5
# # 1 2 3 4 5 4 4 4 4
# # # 1 2 3 4 5 3 3 3
# # # # 1 2 3 4 5 2 2
# # # # # 1 2 3 4 5 1
(a) (b) (c)

* 5 4 3 2 1 *
* * * 4 3 2 1 * * *
* * * * * 3 2 1 * * * * *
* * * * * * * 2 1 * * * * *
* * * * * * * * * 1 * * *
*
(d) (e) (f)

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

Self-Instructional
Material 73

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES
3.9 REFERENCES

1. Kamthane, A. N., & Kamthane, A. A. (2020). Programming and Problem


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

Self-Instructional
74 Material

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


School of Open Learning, University of Delhi
Error and Exception Handling in Python

LESSON 4 NOTES

ERROR AND EXCEPTION HANDLING IN PYTHON

Mansi Sood
Assistant Professor
Shyama Prasad Mukherji College
Email-Id: mansi.sood@spm.du.ac.in

Structure
4.1 Learning Objectives
4.2 Introduction
4.3 What is Error?
4.4 What Is Exception?
4.5 Handling Exceptions
4.5.1 The try-except Block
4.5.2 Multiple Except blocks
4.5.3 Else Block
4.5.4 Finally Block
4.6 Raising Exceptions
4.7 Nested Try Block
4.8 Exception Chaining
4.9 Common Built-in Exceptions
4.9.1 TypeError
4.9.2 ValueError
4.9.3 NameError
4.9.4 Most used Built-in Exceptions
4.10 Best Practices for Exception Handling
4.11 Summary
4.12 Glossary
4.13 Self-Assessment Questions
4.14 References

Self-Instructional
Material 75

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES
4.1 LEARNING OBJECTIVES

After completion of this lesson, readers will be equipped to understand:


 Difference between Error and Exception
 Mechanisms available in Python for handling exceptions
 Advanced exception handling techniques like exception chaining
 Different types of errors and exceptions that can occur in Python programs
 Best practices and guidelines for writing reliable and robust code

4.2 INTRODUCTION

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

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


School of Open Learning, University of Delhi
Error and Exception Handling in Python

NOTES
4.3 WHAT IS ERROR?

Software development treats errors and exceptions as two distinct concepts. Errors
are syntax errors that are also known as parsing errors. They are in fact the first and
most common errors encountered when a user starts with Python programming or
rather any programming language.
For example:
x = 1
if x == 1
print(“True”)

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


File “< >”, line 2
if x == 1
^
SyntaxError: expected ‘:’

The parser repeats the statement at fault and marks the point where the error
was found with the symbol ‘^’. In the given example, the error is detected at line 2,
after the token ‘1’, since a colon (‘:’) is missing there. File name (blank in the example
to avoid any confusion) and line number are also printed to make the error handling
easier.
Another very common example of a syntax error is indentation error which
occurs due to incorrect indentation in the program. For instance, in the given example
the print(i) statement should be indented inside for loop.
For example:
count = 10
for i in range (count):
print(i)

————— OUTPUT —————


File “<ipython-input-1-a11740cc5449>”, line 3
print(i) Self-Instructional
Material 77

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES ^
Indentation Error: expected an indented block after ‘for’
statement on line 2

4.4 WHAT IS EXCEPTION?

Even if a piece of code does not have a syntax error, it may still cause a logical error
during execution, an error that could not be detected before execution. Exceptions are
raised when a logical error occurs during program execution. For example, attempt to
divide a number by zero, performing an operation on incorrect variable types like
adding an integer with a string. When an exception occurs, the normal flow of the
program is interrupted and an exception handler is looked for. If no handler is found,
the program terminates, and an error message is displayed. Different types of exceptions
exist in Python. The type of exception that has occurred in the program is printed as
part of the error message. For instance, in the given example, the last line of the error
message indicates the type of exception that occurred and a little detail based on the
type of exception. ZeroDivisionError is the name of the exception that deals with the
logical error of dividing any number by zero.
For example:
x = 10
y = 0
print(x / y)

————— OUTPUT —————


ZeroDivisionError Traceback (most recent
call last)
< > in <cell line: 3>()
1 x = 10
2 y = 0
——> 3 print(x / y)
ZeroDivisionError: division by zero
Self-Instructional
78 Material

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


School of Open Learning, University of Delhi
Error and Exception Handling in Python

Exceptions can be caused by various factors, including invalid input, resource NOTES
unavailability, or any other unexpected behaviour. For instance, the below given example
expects an integer as an input and raises a ValueError on receiving a string instead.
For example:
x = int(input(“Enter an integer value:”))
print(x)

————— OUTPUT —————


Enter an integer value: a
—————————————————————————————————————
ValueError Traceback (most recent call last)
<ipython-input-6-bccae38e0109> in <cell line: 1> ()
——> 1 x = int(input(“Enter an integer value:”))
2 print(x)
ValueError: invalid literal for int() with base 10: ‘a’

Exceptions may not be unconditionally fatal if handled appropriately in the


program. This ensures that a program can gracefully handle errors and provide meaningful
feedback to the users.

4.5 HANDLING EXCEPTIONS

Exceptions can be handled gracefully in Python programs through a try-except


statement. Exception handling not only improves the reliability of the code but also
allows for graceful error recovery and user-friendly error messages.

4.5.1 The try-except Block

The try-except block is a fundamental construct in Python used for managing exceptions.
It provides a way to designate a code section where exceptions may occur and offers a
mechanism for capturing and handling those exceptions. The try block encompasses the
code segment that might generate exceptions, while the except block outlines the approach
Self-Instructional
for catching and handling them. The try-except block operates in the following manner: Material 79

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 1. Initially, the try block, which consists of the statement(s) positioned between
the try and except keywords, are executed.
2. If no exception arises the execution of the try block is completed and the except
block is bypassed.
3. However, if an exception occurs during the execution of the try block, the
remaining portion of the try block is skipped, and the program flow moves to
the except block.
Python provides the ability to capture specific exceptions by specifying the type
of exception after the except keyword. By doing so, users can customize the handling
of different exceptions and implement quite specific error management. When the type
of exception that occurred matches the one specified after the except keyword, the
corresponding except block is executed, and the program execution continues after
the try/except block. For instance, as shown in the example below, ZeroDivisionError
is an exception name used to handle the logical error of division by zero.
For Example:
try:
# Code that might raise exceptions
x = int(input(“Enter Numerator:”))
y = int(input(“Enter Denominator:”))
print(x / y)
except ZeroDivisionError:
# Exception handling
print(“Denominator is Zero: Division by Zero Error”)
print(“Done”)

————— OUTPUT —————


Enter Numerator: 5
Enter Denominator: 0
Denominator is Zero: Division by Zero Error
Done

————— OUTPUT —————


Self-Instructional Enter Numerator: 5
80 Material

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


School of Open Learning, University of Delhi
Error and Exception Handling in Python

Enter Denominator: 5 NOTES


1.0
Done

By enclosing a specific set of statements within a try block and including an


except block without any specific label, we can effectively capture any potential errors.
This broad except clause is designed to handle all possible exceptions that may arise
as shown in the given example.
For Example:
try:
x = int(input(“Enter Numerator:”))
y = int(input(“Enter Denominator:”))
print(x / y)
except:
print(“Invalid input”)
print(“Done”)

————— OUTPUT —————


Enter Numerator: 5
Enter Denominator: 0
Invalid input
Done

————— OUTPUT —————


Enter Numerator: 5
Enter Denominator: a
Invalid input
Done

In-text Questions
1. What is the difference between an error and an exception in Python?
2. Why are error and exception handling important in software development?
3. What is an exception? Explain with the help of an example. Self-Instructional
Material 81

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 4.5.2 Multiple Except blocks

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

————— OUTPUT —————


Enter Numerator: a
Input not a number
Done

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

Self-Instructional
82 Material

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


School of Open Learning, University of Delhi
Error and Exception Handling in Python

————— OUTPUT ————— NOTES


Enter Numerator: a
Either Denominator is Zero or input not a number
Done

4.5.3 Else Block

The try-except statement can include an optional else clause, which must appear after
all the except clauses. This clause is beneficial for code that needs to be executed
when the try block does not raise any exceptions. The else clause within a try-except
block is triggered solely if no exceptions occur during the execution of the try block. If
an exception is raised within the try block, the else clause is skipped.
For Example:
try:
x = int(input(“Enter Numerator:”))
y = int(input(“Enter Denominator:”))
z = x / y
except ZeroDivisionError:
print(“Denominator is Zero”)
else:
print(z)

————— OUTPUT —————


Enter Numerator: 3
Enter Denominator: 1
3.0

4.5.4 Finally Block

The try statement includes an optional clause known as the finally block. It is designed
to define cleanup actions that must be executed regardless of whether an exception
occurred or not. If a finally block is present, it will be executed as the final step
Self-Instructional
Material 83

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES before the try statement completes, irrespective of whether an exception was raised
or not.
For Example:
try:
x = int(input(“Enter a number:”))
except ValueError as V:
print(“You had to enter a valid number”)
else:
print(x)
finally:
print(“the code completed”)

————— OUTPUT —————


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

————— OUTPUT —————


Enter a number: 1
1
the code completed

4.6 RAISING EXCEPTIONS

Python provides a mechanism for explicitly raising exceptions using the raise statement.
When a raise statement is encountered, it interrupts the normal flow of the program
and triggers the specified exception. This capability is valuable when dealing with
scenarios that are not covered by existing built-in exceptions. By raising exceptions,
you can communicate the occurrence of a specific condition, allowing the program to
handle it appropriately. For example, the given program asks the user to input a positive
number and raises an exception if the input number is negative. The argument provided
Self-Instructional with the raise statement determines the type of exception to be raised.
84 Material

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


School of Open Learning, University of Delhi
Error and Exception Handling in Python

For Example: NOTES


try:
x = int(input(“Enter a positive number:”))
if x < 0:
raise ValueError
except ValueError:
print(“Negative number not allowed”)
else:
print(x)

————— OUTPUT —————


Enter a positive number: -1
Negative number not allowed

————— OUTPUT —————


Enter a positive number: 5
5

In-Text Questions
1. What are the mechanisms available in Python for handling exceptions?
2. How does the try-except block work in Python?
3. How can you handle multiple exceptions in a try-except block?
4. What is the purpose of the else block in a try-except statement?
5. What is the purpose of the finally block in a try-except statement?
6. How do you raise an exception in Python? Explain with an example.

4.7 NESTED TRY BLOCK

In Python, a nested try block is a construct where one try block is placed within
another try block. This allows for a more granular and fine-grained exception handling
approach. The nested try block is useful when you want to handle exceptions separately Self-Instructional
Material 85

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES at different levels of your code. In case there is no handler available to handle the
exception raised in a try block, the program will initiate a search for a suitable handler
in the outer try-except block. Here is an example to illustrate the concept of nested try
blocks in Python.
For Example:
try:
# Outer try block
x = int(input(“Enter the numerator:”))
y = int(input(“Enter the denominator:”))
try:
# Inner try block
if y == 0:
print(“Denominator should not be zero”)
y = int(input(“Enter the denominator again:”))
print(x / y)
except ZeroDivisionError:
# Exception handling specific to the inner try block
print(“Denominator was zero”)
except ValueError:
# Exception handling specific to the outer try block
print(“Numerator and Denominator should be numbers”)

————— OUTPUT —————


Enter the numerator: 5
Enter the denominator: 0
Denominator should not be zero
Enter the denominator again: a
Numerator and Denominator should be numbers

Here in this example, on receiving zero as input for the denominator initially, the
program asks the user to enter the denominator again in the inner try block. Since the
user entered a string instead of a number for the denominator, a ValueError is raised
Self-Instructional
86 Material

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


School of Open Learning, University of Delhi
Error and Exception Handling in Python

from the inner try block. However, inner try block has no except block to handle NOTES
ValueError and hence outer try-except block is searched and executed.

4.8 EXCEPTION CHAINING

To indicate that one exception is a direct result of another, the ‘raise’ statement offers
an optional ‘from’ clause. By using exception chaining, the code can retain the original
exception context when raising a new exception. In the given example, the program
asks the user to enter a positive number. However, on receiving a string instead of a
number, it raises an exception and asks the user to re-enter the number from the
except block. However, if the re-entered number is zero a new exception is raised.
For Example:
try:
x = 5
y = int(input(“Enter a positive number:”))
except ValueError as V:
print(“You had to enter a valid number. Do it again.”)
y = int(input(“Enter a positive number:”))
if y == 0:
raise ZeroDivisionError from V
else:
print(x / y)

————— OUTPUT —————


Enter a positive number: a
You had to enter a valid number. Do it again.
Enter a positive number: 0

————— OUTPUT —————


ValueError Traceback (most recent
call last)
<ipython-input-5-490acdc67a58> in <cell line: 1> () Self-Instructional
Material 87

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 2 x = 5
——> 3 y = int(input(“Enter a positive number:”))
4 except ValueError as V:
ValueError: invalid literal for int() with base 10: ‘a’
The above exception was the direct cause of the following
exception:
ZeroDivisionError Traceback (most recent
call last)
<ipython-input-5-490acdc67a58> in <cell line: 1>()
6 y = int(input(“Enter a positive number: “))
7 if y == 0:
——> 8 raise ZeroDivisionError from V
9 else:
10 print(x / y)
ZeroDivisionError:

4.9 COMMON BUILT-IN EXCEPTIONS

Python has a comprehensive collection of built-in exceptions that encompass a wide


range of error types and exceptional circumstances. Familiarity with these common
exceptions is essential for effectively handling exceptions and debugging. In this section,
we will delve into some of the commonly encountered built-in exceptions in Python.

4.9.1 TypeError

The ‘TypeError’ exception occurs when an operation or function is applied to an


object of an unsuitable type. This situation can arise when incompatible data types are
combined or when a function is invoked with incorrect arguments. For example, if the
division operation is invoked with string arguments

Self-Instructional
88 Material

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


School of Open Learning, University of Delhi
Error and Exception Handling in Python

For Example: NOTES


try:
x = “ABC”
y = “DEF”
z = x/y
except TypeError as T:
print(“Exception Detail:”, T)
print(“Incorrect type for division operation”)
else:
print(z)

————— OUTPUT —————


Exception Detail: unsupported operand type(s) for /: ‘str’
and ‘str’
Incorrect type for division operation

4.9.2 ValueError

The ‘ValueError’ exception is triggered when a function is provided with an argument


of the correct type but with an unsuitable value. This situation arises when a function
anticipates a certain range of values and receives a value that falls outside that range.
For instance, the int() function raises a ValueError on receiving a string as input as a
string cannot be converted to an integer.
For Example:
try:
x = “ABC”
y = int(x)
except ValueError as V:
print(“Exception Detail:”, V)
else:
print(z)

Self-Instructional
Material 89

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES ————— OUTPUT —————


Exception Detail: invalid literal for int() with base 10:
‘ABC’

4.9.3 NameError

This exception occurs whenever a name being referenced in a statement is not found
globally. For instance, trying to access a variable that has not been defined. The given
program defines a variable num1, but accidently uses the variable num and hence the
error. Another common error scenario is when the developer mistakenly uses an
incorrect function name like ‘prints’ instead of ‘print.’
For Example:
num1 = int(input(“Enter an integer:”))
print(“Received integer is:”, num)

————— OUTPUT —————


Enter an integer: 5
—————————————————————————————————————
NameError Traceback (most recent call last)
<ipython-input-30-91408e397ce0> in <cell line: 2>()
1 num1 = int(input(“Enter an integer”))
——> 2 print(“Received integer is:”, num)
3
NameError: name ‘num’ is not defined

For Example:
num1 = int(input(“Enter an integer:”))
prints(“Received integer is:”, num1)

————— OUTPUT —————


Enter an integer: 5
—————————————————————————————————————
NameError Traceback (most recent
call last)
Self-Instructional
90 Material

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


School of Open Learning, University of Delhi
Error and Exception Handling in Python

<ipython-input-31-94b319a8effa> in <cell line: 2>() NOTES


1 num1 = int(input(“Enter an integer”))
——> 2 prints (“Received integer is:”, num1)
3
NameError: name ‘prints’ is not defined

4.9.4 Most used Built-in Exceptions

Following are some of the most used built-in exceptions available in Python.

Exception Name Description


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

4.10 BEST PRACTICES FOR EXCEPTION HANDLING

The following are the best practices for efficient exception handling in the code:
 Practicing good exception handling involves narrowing the scope of your try
block. This means focusing on the specific code that may raise exceptions,
rather than encompassing larger sections of code in try block. Self-Instructional
Material 91

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES  By narrowing the scope, you can effectively isolate and handle exceptions,
which improves the readability and maintainability of your code.
 Meaningful error messages including the relevant variables and the execution
context should be provided to clearly communicate the cause of the exception
to the user or developer, helping them understand the issue and how to resolve
it.
 It is crucial to gracefully close resources when your code utilizes external resources
like files, network connections, or database connections, ensuring proper release
even in the presence of exceptions to prevent resource leaks and maintain
program integrity.
 Offering alternative paths or fallback mechanisms when an exception occurs
can be beneficial. For instance, if an incorrect input is given by the user, the
program could prompt the user to enter a different value or provide default
values.
 By handling exceptions gracefully and striving for recovery, you can develop
more robust and user-friendly software applications.

4.11 SUMMARY

Error and exception handling are indispensable aspects of software development. It


enables developers to effectively manage unexpected circumstances and ensure the
reliability of their code. Python distinguishes between two types of errors: syntax errors
and exceptions. Developers employ try-except blocks to handle exceptions in Python.
A try block can have multiple except blocks to address various types of exceptions. In
addition to exception handling, Python allows the use of the else and finally clauses
within a try-except block. Python provides a wide range of built-in exceptions that
cover common error scenarios, such as ValueError, TypeError, ZeroDivisionError,
etc. By understanding the different types of exceptions, developers can appropriately
handle specific error conditions.
Adhering to best practices when handling exceptions can help to create robust
Self-Instructional and maintainable code. A crucial guideline is to limit the scope of the try block to the
92 Material

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


School of Open Learning, University of Delhi
Error and Exception Handling in Python

code that may raise an exception. This approach isolates potential errors and enhances NOTES
code readability. It is also advisable to provide meaningful error messages that convey
relevant information to users or developers, facilitating the debugging and troubleshooting
process. Anticipating potential errors and providing alternative logic, developers can
enhance their code’s resilience and enhance the user experience.

4.12 GLOSSARY

 Error: In software development, these are syntax errors in the code that are
also known as parsing errors.
 Exception: These are logical errors raised during program execution.
 try-except: These are python statements for handling exceptions.
 Handler: This is a piece of code written to handle exception(s).
 Abnormal Termination: Situation when a program crashes and terminates
due to an unhandled exception.
 Finally: These are blocks designed to define cleanup actions that must be
executed regardless of whether an exception occurred or not.
 Raise: Python statement used to trigger an exception.
 Exception chaining: Python mechanism to allow the code to retain the original
exception context when raising a new exception.

4.13 SELF-ASSESSMENT QUESTIONS

1. Create a Python program that requests the user to input two numbers and
performs their division. Implement exception handling to deal with non-numeric
input values.
2. Implement a Python program that asks the user to enter a negative number and
prints its absolute value. Utilize exception handling to handle scenarios where
the user inputs a positive number. Self-Instructional
Material 93

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 3. What are the different types of errors and exceptions that can occur in Python
programs?
4. State best practices for writing reliable and robust code using exception handling.
5. What is the role of the finally block in exception handling?
6. How can you raise exceptions explicitly using the raise statement in Python?
7. What is exception chaining?
8. Provide examples of commonly encountered built-in exceptions in Python.
9. Why is it important to provide meaningful error messages when handling
exceptions?
10. How does effective exception handling contribute to the development of more
robust and user-friendly software applications?

4.14 REFERENCES

1. Balagurusamy E., (2018). Introduction to Computing and Problem Solving


using Python (2 ed.). McGraw Hill Education.
2. Taneja, S., & Kumar, N. (2018). Python Programming- A modular Approach.
India: Pearson Education.
3. Saeed, A., Ayeva, A., Ayeva, K. (2020). Python In - Depth: Use Python
Programming Features, Techniques, and Modules to Solve Everyday
Problems. India: BPB PUBN.
4. Kamthane, A. N., &amp; Kamthane, A. A. (2020). Programming and
Problem Solving with Python. McGraw-Hill Education.

Self-Instructional
94 Material

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


School of Open Learning, University of Delhi
UNIT III: USER DEFINED FUNCTIONS

LESSON 5: USER DEFINED FUNCTIONS IN PYTHON


User Defined Functions in Python

LESSON 5 NOTES

USER DEFINED FUNCTIONS IN PYTHON

Mansi Sood
Assistant Professor
Shyama Prasad Mukherji College
Email-Id: mansi.sood@spm.du.ac.in
Structure
5.1 Learning Objectives
5.2 Introduction
5.3 Defining Functions
5.4 Passing Arguments to Functions
5.4.1 Positional and Keyword Arguments
5.4.2 Default Arguments
5.5 Scope of Variables
5.6 Purpose of Functions
5.7 Recursive Functions
5.8 Summary
5.9 Glossary
5.10 Self-Assessment Questions
5.11 References

5.1 LEARNING OBJECTIVES

After completion of this lesson, you will be able to:


 Understand the concept of function definition in Python and its role in code
organization and reusability.
 Explore the significance of docstrings in documenting functions and improving
code readability.

Self-Instructional
Material 97

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES  Recognize the different ways to pass arguments to functions, including positional
and keyword arguments.
 Understand the concept of default arguments and their role in allowing functions
to be called with fewer arguments.
 Define recursive functions.

5.2 INTRODUCTION

To create a programming application, it is best to break down a big program into


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

5.3 DEFINING FUNCTIONS

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

Self-Instructional
98 Material

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


School of Open Learning, University of Delhi
User Defined Functions in Python

For example: NOTES


def func():
‘‘‘ This is an example function named as ‘func’
to demonstrate how to define functions in Python’’’
print(“My first function”)
func()

————— OUTPUT —————


My first function

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

func()

————— OUTPUT —————


Enter first number: 5
Enter second number: 7
The sum of the two numbers: 12

When a function is defined, its name becomes associated with the corresponding
function object in the symbol table. This association allows the interpreter to identify
the function as a user-defined entity. Additionally, multiple names can refer to the same
function object, providing alternative ways to access it as shown in the given example.
For example:
def func():
‘‘‘this is an example function Self-Instructional
Material 99

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES to demonstrate how to define functions in python’’’


print(“My first function”)

func2 = func
func()
func2()

————— OUTPUT —————


My first function
My first function

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

a,b = func()
print(“a, b:”, a, b)

————— OUTPUT —————


a, b: 5 test

Functions without a return statement implicitly return the None object i.e., if a
function reaches its end without encountering a return statement, it returns None. The
interpreter usually hides the None value when it is the only return value. However, if
desired, it can be displayed using the print() function as shown in the example below.
For example:
def func():
Self-Instructional ‘‘‘this function implicitly returns None’’’
100 Material

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


School of Open Learning, University of Delhi
User Defined Functions in Python

x=5 NOTES
y = “test”
a = func()
print(“a:”, a)

————— OUTPUT —————


a: None

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

In-text Questions
1. How are functions defined in Python? Explain the syntax and the role of the
‘def’ keyword.
2. Explain the concept of functions returning the None object. How is the return
statement used to specify a value to be returned?
3. What is the purpose of a function definition in Python? How does it contribute
to code organization and reusability?

5.4 PASSING ARGUMENTS TO FUNCTIONS

Functions in Python have the flexibility to accept zero or more arguments. Multiple
arguments can be included, separated by commas. Arguments are used to pass values
or data into functions for processing. These arguments are specified within the
parentheses of the function definition. The given example accepts a single argument
and displays its value.
For example:
def Display(str):
‘‘‘ This function accepts a parameter and displays it’’’
Self-Instructional
Material 101

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES print(str)

Display(“Hello there!”)

————— OUTPUT —————


Hello there!

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

calculate_sum(10, 20) # Actual parameters are 10 and 20

————— OUTPUT —————


The sum of the received parameters is: 30

By default, when calling a function, the correct number of arguments must be


provided. This means that if a function expects two arguments, it should be called with
exactly two arguments, neither more nor less. In the given example, the function
calculate_sum has two arguments a and b. When the function is called, the values
passed for these arguments will be used to compute the sum of passed values. The
example also shows the error message on receiving a single argument instead of two
as specified by the function definition.

Self-Instructional
102 Material

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


School of Open Learning, University of Delhi
User Defined Functions in Python

For example: NOTES


def calculate_sum(a, b):
‘‘‘ This function calculates the sum of its input arguments’’’
sum = a + b
print(“sum of the arguments:”, sum)

calculate_sum(3, 4)
calculate_sum(3)

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


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

TypeError: calculate_sum() missing 1 required positional


argument: ‘b’

5.4.1 Positional and Keyword Arguments

Python has two mechanisms for passing arguments to a function: Positional arguments
and Keyword arguments. Positional arguments are passed based on their position in
the function call. The order and number of arguments in the function call must match
the order and number of parameters in the function definition.
Keyword arguments allow arguments to be specified by their corresponding
parameter names during a function call. This approach eliminates the need to remember
the order of arguments. The given example demonstrates using positional and keyword
arguments while invoking a function. In the first invocation of the function param_order,
keyword arguments are used to pass the values. However, the second invocation uses
Self-Instructional
Material 103

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES positional arguments. This implies that the first argument is assigned to the first formal
parameter, the second argument to the second formal parameter, and so on. In the
third invocation, again positional arguments are being used but a string is passed to the
first formal parameter (a) and an integer to the second formal parameter (b). Hence, it
causes an error as a string is being added to an integer variable.
For example:
def param_order(a, b, str):
‘‘‘ This function demonstrates that order of parameters is
important’’’
sum = a + b
print(str, sum)
param_order(str = “sum of the arguments:”, b=3, a=4) #keyword
arguments
param_order(3, 4, “sum of the arguments:”) #positional arguments
in correct order
param_order(“sum of the arguments:”, 3, 4) #positional arguments

————— OUTPUT —————


sum of the arguments: 7
sum of the arguments: 7
—————————————————————————————————————
TypeError Traceback (most recent call last)
<ipython-input-5-c9bbf26647ce> in <cell line: 6>()
4 print(str, sum)
5 param_order(str = “sum of the arguments:”, b = 3, a = 4)
——> 6 param_order(“sum of the arguments:”, 3, 4)

<ipython-input-5-c9bbf26647ce> in param_order(a, b, str)


1 def param_order(a, b, str):
2 ‘‘‘this function demonstrates that order of parameters is
important’’’
——> 3 sum = a + b
Self-Instructional
104 Material

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


School of Open Learning, University of Delhi
User Defined Functions in Python

4 print(str, sum) NOTES


5 param_order(str = “sum of the arguments:”, b=3,a=4)
TypeError: can only concatenate str(not “int”) to str

Important points to note:

1. When making a function call, keyword arguments should come after positional
arguments as shown in the given example.
For example:
def param_order(a, b, str):
‘‘‘this function demonstrates Positional and Keyword
arguments’’’
print(a, b, str)
param_order(a = 3, b = 4.0, “test string”)

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


File “<ipython-input-11-0b6d29383af3>”, line 6
param_order(a = 3, b = 4.0, “test string”)
^
SyntaxError: positional argument follows keyword argument

2. All the provided keyword arguments must correspond to one of the function’s
defined arguments. For example, in the following code, “strng” would not be a
valid argument for the defined “str” variable in the function.
For example:
def param_order(a, b, str):
‘‘‘this function demonstrates Positional and Keyword
arguments’’’
print(a, b, str)
param_order(3, 4.0, strng = “test string”)

Self-Instructional
Material 105

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES ————— OUTPUT —————


TypeError Traceback (most recent call last)
<ipython-input-12-3972ec4284eb> in <cell line: 5>()
3 print(a, b, str)
4
——> 5 param_order(3, 4.0, strng = “test string”)
TypeError: param_order() got an unexpected keyword argument
‘strng’

3. It is not permissible to assign a value to an argument more than once. The


following example demonstrates a failure that occurs when this restriction is
violated
For example:
def param_order(a, b, str):
‘This function demonstrates Positional and Keyword arguments’’’
print(a, b, str)
param_order(3, 4.0, str = “test string”, b = 4.0)

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


TypeError Traceback (most recent call last)
<ipython-input-13-b3dcd8654e2e> in <cell line: 5>()
3 print(a, b, str)
4
——> 5 param_order(3, 4.0, str = “test string”, b = 4.0)

TypeError: param_order() got multiple values for argument ‘b’

5.4.2 Default Arguments

One of the most valuable forms of defining functions involves specifying default values
for one or more arguments. This allows the function to be called with fewer arguments
than it is originally defined to accept. Default arguments are assigned a predetermined
Self-Instructional
106 Material

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


School of Open Learning, University of Delhi
User Defined Functions in Python

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

default_values(3, 5.0, “new string”)


default_values(3, 5.0)
default_values(3)
default_values(3, “new string”)
default_values()
3 5.0 new string
3 5.0 basic string
Self-Instructional
Material 107

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 3 4.0 basic string


3 new string basic string

————— OUTPUT —————


TypeError Traceback (most recent call last)
<ipython-input-15-9731a7f56f81> in <cell line: 9>()
7 default_values(3)
8 default_values(3, “new string”)
——> 9 default_values()
TypeError: default_values() missing 1 required positional
argument: ‘a’

In function definition, a mandatory argument can not follow a default argument.


For instance, defining the optional or the default argument before a mandatory argument
in the given example causes an error scenario.
For example:
def default_values(a, b = 4.0, c):
‘‘‘ This function demonstrates default_values’’’
print(a, b, c)
default_values(3, 5.0, 6.0)

————— OUTPUT —————


File “<ipython-input-16-be3a4b62be68>”, line 1
def default_values(a, b=4.0, c):
^
SyntaxError: non-default argument follows default argument

A function having default arguments can also be called using positional arguments.
There could be many ways to call such a function. The given example demonstrates
the same using one mandatory argument a and three optional (default) arguments b, c,
and str.
For example:
def default_values_pos_arg(a, b = 4, c = 5.0, str = “test string”):
‘‘‘This function demonstrates how default_values can be used
Self-Instructional
108 Material when passing positional arguments’’’

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


School of Open Learning, University of Delhi
User Defined Functions in Python

print(a, b, c, str) NOTES

default_values_pos_arg(1) #1 positional argument


for mandatory parameter
default_values_pos_arg(a = 1) #1 Keyword argument for
mandatory parameter
default_values_pos_arg(a = 1, c = 6.0) #2 Keyword arguments
(for mandatory parameter
a and optional parameter
c)
default_values_pos_arg(c = 6.0, a = 1) # 2 Keyword arguments
(for mandatory a and
optional c but not in
defined order)
default_values_pos_arg(1, 2) # 2 Posi tio nal
parameter for a and b
default_values_pos_arg(1, c = 6.0) #1 positional and
1 keyword parameter

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


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

5.5 SCOPE OF VARIABLES

In Python programming, variables can have either local or global scope, which
determines their accessibility and visibility in different parts of the program. The
properties of a local variable are as follows:
Self-Instructional
Material 109

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 1. When variables are declared within a function, they have a local scope, meaning
they are only accessible within that specific function.
2. Local variables are created when the function is called and cease to exist once
the function completes its execution. They are useful for storing temporary or
intermediate values that are specific to a particular function.
3. Trying to access a local variable outside of its function will result in an error
since it is out of scope.
For example:
def demo_local_scope(a): # a is a local variable
‘‘‘This function demonstrates the local scope of a variable’’’
print(“value of a is:”, a)

demo_local_scope(5)
print(“a is:”, a) # This line will generate an error as a is a
local variable, can’t be accessed here

————— OUTPUT —————


value of a is: 5
—————————————————————————————————————
NameError Traceback (most recent call last)
<ipython-input-15-a3d655af4260> in <cell line: 7>()
5
6 demo_local_scope(5)
——> 7 print(“value of a is:”, a) # this line will generate an error
as a is a local variable and does not exist here
8
9
NameError: name ‘a’ is not defined

4. These variables are independent of other variables with the same name in other
functions or the global scope. For instance, in the given example, local variable
Self-Instructional
110 Material
a defined inside function demo_local_scope receives a value of 5 and the one

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


School of Open Learning, University of Delhi
User Defined Functions in Python

defined inside function demo_local_scope_again receives a value of 10. They NOTES


both come into existence when their corresponding functions are invoked and
then cease to exist.
For example:
def demo_local_scope(a): # a is a local variable
‘‘‘ This function demonstrates the local scope of a variable’’’
print(“value of a is:”, a)

def demo_local_scope_again(a): # a is a local variable


‘‘‘ This function demonstrates the local scope of a variable’’’
print(“value of a is:”, a)
demo_local_scope(5)
demo_local_scope_again(10)

————— OUTPUT —————


value of a is: 5
value of a is: 10

The properties of a global variable are as follows:

1. Variables declared outside of any function, at the top level of the program, have
a global scope.
2. Global variables are accessible from anywhere within the program, including
inside functions.
3. Global variables retain their values throughout the program’s execution until
they are explicitly changed.
4. Global variables are handy for storing information that needs to be shared and
accessed across multiple functions or modules.
For example:
b = 10 # This is global variable b
def demo_local_scope(a): # a is a local variable, b is global
print(“value of a is:”, a)
Self-Instructional
Material 111

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES print(“b is accessible inside function:”, b)

demo_local_scope(5)
print(“b is accessible outside function:”, b)

————— OUTPUT —————


value of a is: 5
b is accessible inside function: 10
b is accessible outside function: 10

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

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

————— OUTPUT —————


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

For example:
a=5
def global_var_in_func():
Self-Instructional
112 Material
global a

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


School of Open Learning, University of Delhi
User Defined Functions in Python

print(‘The value of a in function:’, a) # this will print global NOTES


variable a having value 5
a = 15 # Accessing global a and its value is changed to 15
print(‘The value of a in function:’, a) # this will print global
variable a having value 15
global_var_in_func()
print(‘The value of a outside function:’, a) # prints global a
and the value is 15 as set in the func

————— OUTPUT —————


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

It is recommended to limit the use of global variables to maintain code clarity


and prevent unintended side effects and accidental changes to the variables.
Understanding variable scope in Python is essential for writing well-structured
and maintainable code. By managing variable scope effectively, you can control their
visibility and ensure their values are accessible where needed, promoting code clarity,
and avoiding naming conflicts.

5.6 PURPOSE OF FUNCTIONS

Functions in Python programming serve the purpose of performing specific tasks by


encapsulating a block of code and giving it a name. They offer several advantages:
1. Organization: Functions help break down programs into smaller, manageable
parts, improving clarity and ease of maintenance.
2. Reusability: Once defined, functions can be called multiple times from different
parts of the program, avoiding repetition, and promoting efficiency.
3. Modularity: Functions enable the separation of different tasks into independent
modules, enhancing code readability and simplifying testing and debugging (the
process of finding and removing errors from code). Self-Instructional
Material 113

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 4. Abstraction: Functions hide the internal details, allowing users to focus on
high-level functionality rather than implementation specifics.
The following example demonstrates all the above advantages. The program is
divided into small and manageable parts. First, a display function is created to print the
arguments along with the custom messages passed as arguments to the function. This
helps to reuse the code of the display() function every time a variable and the associated
description is to be printed. get_input function is defined to make a separate module
that asks the user, the required input. Functions – sum() and divide() add and divide
the input arguments. The divide() function is reused to calculate the average of two
numbers. get_input_and_process() function can be exposed to the users to find the
sum, division, and average of two numbers taken as inputs from the user. Users need
not know the details of how the function is implemented.
For example:
‘‘‘ a program to display the benefits of using functions in
programming ’’’
def Display(a, str1, b = None, str2 = None):
print(str1, a)
if b != None:
print(str2, b)

def get_input():
a = int(input(“Enter first number:”))
b = int(input(“Enter second number:”))
return a, b

def sum(a, b):


return a + b

def divide(a, b):


return a / b

Self-Instructional
114 Material

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


School of Open Learning, University of Delhi
User Defined Functions in Python

def get_input_and_process(): NOTES


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

get_input_and_process()

————— OUTPUT —————


Enter first number: 20
Enter second number: 10
first number: 20
second number: 10
sum of the input numbers: 30
division of the input numbers: 2.0
average of the input numbers: 15.0

5.7 RECURSIVE FUNCTIONS

Recursive functions in Python provide a powerful approach to solving complex problems


by breaking them down into smaller subproblems. Here are some key points to grasp
about recursive functions:
1. Recursive functions consist of two vital parts: the recursive case and the base
case.
2. The recursive case determines when the function calls itself, usually with smaller
input.
3. The base case acts as the stopping condition, ending the recursive calls and
producing a result. Self-Instructional
Material 115

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES For example:


‘‘‘ this function calculates the sum of n natural numbers
recursively ’’’
def sum(n):
if n == 1: # base case: terminate recursion when n is 1
return 1
ans = n + sum(n-1) # recursive step: call sum function recursively
to find sum of n-1 natural numbers
return ans

sum(5)

————— OUTPUT —————


15

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

4. Ensuring that the recursive calls eventually reach the base case is crucial to
avoid infinite recursion. For example, the given programs always execute the
recursive step first and hence the base case is never reached.

Self-Instructional
116 Material

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


School of Open Learning, University of Delhi
User Defined Functions in Python

For example: NOTES


‘‘‘ this function calculates sum of n natural numbers recursively
however, the base case is never reached as it always executes
after recursive step
hence this code causes infinite recursion’’’
def sum(n):
ans = n + sum(n-1) # recursive step: call sum function recursively
to find sum of n-1 natural numbers
if n == 1: # base case: terminate recursion when n is 1
return 1
return ans

sum(5)

————— OUTPUT —————


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

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

<ipython-input-45-2eb14de6246f> in sum(n)
2 however, the base case is never reached as it always execute
after recursive step and hence this code causes infinite
recursion’’’
3 def sum (n):
——> 4 ans = n + sum(n-1) # recursive step: call sum function
recursively to find sum of n-1 natural numbers

Self-Instructional
Material 117

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 5 if n == 1: # base case: terminate recursion when n is 1


6 return 1
RecursionError: maximum recursion depth exceeded

When utilizing recursive functions, it is essential to design them carefully and


have a good understanding of the problem at hand.

5.8 SUMMARY

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

5.9 GLOSSARY

 Function: Independent module within a program is known as function.


 def: It is a keyword that marks the beginning of a function definition.
 Formal parameters: These are variables declared inside the parenthesis of a
function definition that serve as placeholders for the actual values to be passed
when the function is called.
 Docstring: A string literal that serves as documentation to state the function’s
purpose.
 return: Python statement employed to explicitly specify the single or multiple
values to be returned from a user-defined function.
 Arguments: These are the actual values that are provided when the function is
invoked.
Self-Instructional
118 Material

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


School of Open Learning, University of Delhi
User Defined Functions in Python

 Positional arguments: Arguments passed based on their position in the function NOTES
call.
 Keyword arguments: Arguments to be specified by their corresponding
parameter names during a function call.
 Default arguments: Arguments assigned a predetermined value in the function
definition.
 Local variable: These are variables that are declared within a function and
have a local scope.
 Scope: Accessibility/ visibility within a program is known as scope.
 Global variable: Variables that are declared outside of any function, at the top
level of the program and have a global scope.
 Modularity: It is the separation of different tasks into independent modules.
 Abstraction: It means hiding the internal details, allowing users to focus on
high-level functionality rather than implementation specifics.
 Recursive functions: Functions that call themselves are known as recursive
function.

5.10 SELF-ASSESSMENT QUESTIONS

1. Create a Python function that determines whether a given number is prime or


not.
2. Implement a Python function to identify the largest number among two or three
given numbers.
3. What are the different ways to pass arguments to functions in Python? Describe
the differences between positional and keyword arguments.
4. What are default arguments, and how do they allow functions to be called with
fewer arguments? Provide an example.
5. How can you determine the order and number of arguments required for a
function call based on its definition?
Self-Instructional
Material 119

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 6. Can a function be called with more arguments than specified in its definition?
Explain why or why not.
7. What is a docstring, and why is it beneficial to include it in function definitions?
How does it improve code readability?

5.11 REFERENCES

1. Balagurusamy E., (2018). Introduction to Computing and Problem Solving


using Python (2 ed.). McGraw Hill Education.
2. Saeed, A., Ayeva, A., Ayeva, K. (2020). Python In - Depth: Use Python
Programming Features, Techniques, and Modules to Solve Everyday
Problems. India: BPB PUBN.
3. Kamthane, A. N., &amp; Kamthane, A. A. (2020). Programming and
Problem Solving with Python. McGraw-Hill Education.

Self-Instructional
120 Material

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


School of Open Learning, University of Delhi
UNIT IV: BUILT-IN DATA STRUCTURES

LESSON 6: BUILT-IN DATA STRUCTURES IN PYTHON


Built-in Data Structures in Python

LESSON 6 NOTES

BUILT-IN DATA STRUCTURES IN PYTHON

Mansi Sood
Assistant Professor
Shyama Prasad Mukherji College
Email-Id: mansi.sood@spm.du.ac.in
Structure
6.1 Learning Objectives
6.2 Introduction
6.3 Strings
6.3.1 Concatenation
6.3.2 In and Not In Operator
6.3.3 String comparison
6.3.4 Indexing and Slicing
6.3.5 Built-in Function – Len, Min, Max
6.3.6 Strings are Immutable
6.4 Lists
6.4.1 Concatenation
6.4.2 In and Not in operator
6.4.3 del Operator - Remove Element
6.4.4 Indexing and Slicing
6.4.5 Lists are Mutable
6.4.6 Adding and Removing Elements
6.4.7 Built-in Functions – len, max, min, sum
6.5 Tuples
6.5.1 Concatenation
6.5.2 Indexing and Slicing
6.5.3 Built-in functions
6.5.4 Tuples are Immutable
6.5.5 Packing and Unpacking
6.6 Sets
6.6.1 Membership Test
6.6.2 Union of two sets Self-Instructional
Material 123

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 6.6.3 Intersection of two sets


6.6.4 Difference between two sets
6.6.5 Symmetric difference of two sets
6.7 Dictionaries
6.7.1 Accessing Elements
6.7.2 Updating and Adding Elements
6.7.3 Removing Elements
6.7.4 Nested Dictionaries
6.7.5 Immutable Keys
6.7.6 Missing Key value
6.8 Data Structures with Loop and Conditional Statements
6.9 Summary
6.10 Glossary
6.11 Self-Assessment Questions
6.12 References

6.1 LEARNING OBJECTIVES

After completion of this lesson, you will be able to:


 Understand the characteristics and properties of built-in data structures in Python
including strings, lists, tuples, sets, and dictionaries
 Manipulate and access data stored in built-in data structures using indexing,
slicing, and built-in functions
 Apply built-in functions, methods, and operators specific to strings, lists, tuples,
sets, and dictionaries effectively in Python programming
 Recognize the appropriate use cases for each data structure and choose the
most suitable one based on specific requirements
 Develop problem-solving skills by applying the knowledge of data structures in
practical programming scenarios.

Self-Instructional
124 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

NOTES
6.2 INTRODUCTION

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

6.3 STRINGS

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

————— OUTPUT —————


Str(<class ‘str’> <class ‘str’>

The example below shows another method to create a string.


For example:
str1 = str(“test string”)
str2 = str() #empty string
Self-Instructional
Material 125

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES print(type(str1), type(str2))


print(str1, str2)

————— OUTPUT —————


<class ‘str’> <class ‘str’>
test string

Strings are immutable, which implies that they cannot be modified once created.
This is explained in detail below.
If a string includes a single quote but no double quotes, it is enclosed within
double quotes. Otherwise, if it contains double quotes, it is enclosed within single
quotes. Also, ‘\’ can be used to escape quotes. This implies that ‘\’ or a double quote
can be used to treat a single quote (‘) as a part of the string. For instance, the example
below prints a string ‘’It’s easy’’ using the two mentioned methods.
For example:
print(“It’s easy”)
print(‘It\’s easy’)

————— OUTPUT —————


It’s easy
It’s easy

Special characters like ‘\n’ for representing a newline have a backslash (‘\’)
character to identify them. To prevent special characters from being interpreted when
preceded by a backslash, you can utilize raw strings by adding an ‘r’ before the initial
quote as shown in the example below.
For example:
print(“Read the file in C:\new_folder”) # \n in C:\new_folder
is treated as a special character here
print(r“Read the file in C:\new_folder”) #adding r (raw
string) prevents \n to be treated as a special character

Self-Instructional
126 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

————— OUTPUT ————— NOTES


Read the file in C:
ew_folder
Read the file in C:\new_folder

Strings offer a range of operations, such as concatenation, indexing, slicing, etc.


which empower users with robust string manipulation and text processing abilities.

6.3.1 Concatenation

The process of merging multiple strings into a single string is known as string
concatenation. ‘+’ operator is used to concatenate strings and ‘*’ operator is used to
repeat strings. The given example shows the usage of ‘+’ and ‘*’.
For example:
str1 = “First String”
str2 = “Second String”
print(str1+str2)
print(str1*2)

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


First StringSecond String
First StringFirst String

When two or more string literals (i.e., those enclosed between quotes) are
placed consecutively, they are automatically combined into a single string. This capability
proves especially handy when you need to split lengthy strings. However, it is important
to note that this concatenation feature only applies to literals and does not work with
variables. The below example displays the same.
For example:
str1 = (“Long strings literals can be”
“broken down into multiple lines like this”)
str2 = “two strings” “concatenated”
print(str1)
print(str2) Self-Instructional
Material 127

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES #str3 = str1 str2 - string variable cannot be concatenated


like this

————— OUTPUT —————


Long strings literals can be broken down into multiple lines
like this
two stringsconcatenated

6.3.2 In and Not In Operator

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

————— OUTPUT —————


Test found
test not found

6.3.3 String comparison

In Python, operators like ==, <, >, <=, >=, and != are used to compare strings. String
comparison involves comparing each character of the strings in consideration as shown
by the example below.
For example:
str1 = “ABCD”
str2 = “WXYZ”
if str1 == str2:
Self-Instructional print(‘two strings equal’)
128 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

elif str1 < str2: NOTES


print(‘str1 < str2’)
elif str1 > str2:
print(‘str1 > str2’)

————— OUTPUT —————


str1 < str2

6.3.4 Indexing and Slicing

String indexing allows us to access specific characters within a string by using subscripts.
The first character is assigned an index of 0. In Python, there is no distinct character
type, as a character is essentially a string with a length of one. Additionally, negative
numbers (starting from -1) can be used as indices to count from the right side of the
string as shown in the example below.
For example:
str = “This is test string”
print(str[0], str[1], str[2])
print(str[-1], str[-2], str[-3])

————— OUTPUT —————


T h i
g n i

Indexing is used to retrieve individual characters from a string, whereas slicing


enables you to extract substrings. Slices are given in square brackets like [a:b], where
the first number a denotes the starting index and the second number b denotes where
to end the slice. It is important to note that when slicing, the starting index is always
inclusive, while the ending index is always exclusive as shown in the example.
For example:
str = “This is test string”
print(str[0 : 2]) # string slicing extracts character at
index 0 and 1

Self-Instructional
Material 129

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES —————- OUTPUT —————


Th

Slices in Python come with convenient default values: if the first index is omitted,
it defaults to zero, and if the second index is omitted, it defaults to the size of the string
being sliced as shown in the example.
For example:
str = “This is test string”
print(str[ : 4]) # starting index defaults to 0
print(str[ 4: ]) # ending index defaults to end of string.
Notice the first space in the output
print(str[-3 : ]) # starting index is the third last character
in the string
print(str[:6] + str[6:]) # this will print the entire string

————— OUTPUT —————


This
is test string
ing
This is test string

If you attempt to use an index that exceeds the string’s length, an error will
occur. However, when employing slice indexes that are out of range, Python handles
them gracefully when performing slicing operations.
For Example:
str = “This is test string”
print(str[ : 50]) # ending index is way beyond the length of
string
print(str[50])

————— OUTPUT —————


This is test string
———————————————————————
IndexError Traceback (most recent call last)
Self-Instructional <ipython-input-7-4f9dbce744d7> in <cell line: 3> ()
130 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

1 str = “This is test string” NOTES


2 print(str [ : 50]) # ending index is way beyond the
length of string
——> 3 print(str [50])
4
IndexError: string index out of range

6.3.5 Built-in Function – Len, Min, Max

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

————— OUTPUT —————


10
S
t

6.3.6 Strings are Immutable

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

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES ————— OUTPUT —————


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

6.4 LISTS

Lists are collections of elements that are ordered and enclosed in square brackets ([]).
It is represented using a series of comma-separated values(elements) enclosed in square
brackets. They have the flexibility to store elements of different data types. Although
lists can accommodate items of varying types, it is common for the items within a list to
share the same data type. Lists are majorly utilized for tasks that involve organizing
and manipulating related data.
For Example:
list1 = [1, 2, 3, ‘a’]
list2 = [] #empty list
print(list1)
print(list2)
print(type(list1))

————— OUTPUT —————


[1, 2, 3, ‘a’]
[]
<class ‘list’>

The example below shows another method to create lists.


Self-Instructional
132 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

For Example: NOTES


list1 = list([1,2.0,’test’])
list2 = list() #create empty list
print(list1)
print(list2)
print(type(list1)))

————— OUTPUT —————


[1, 2.0, ‘test’]
[]
<class ‘list’>

A list can be created from the characters of a string.


For Example:
string = “Test String”
list1 = list(string)
print(list1)

————— OUTPUT —————


[‘T’, ‘e’, ‘s’, ‘t’, ‘ ’, ‘S’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’]

Unlike strings, lists can be modified, making them mutable. This is further
explained below in detail. Python Programming offers a range of operations on Lists,
including appending, inserting, removing, sorting, and slicing.

In-Text Questions
1. Write a Python code snippet to concatenate two strings using the ‘+’ operator.
2. Write a Python code snippet to extract a substring from a given string using
slicing.
3. What is a string in Python and how is it represented?
4. How can you access individual characters within a string?
5. Explain the concept of string immutability in Python.
Self-Instructional
Material 133

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 6.4.1 Concatenation

Lists can be concatenated in the same way as that of strings.


For Example:
list1 = [1, 2, 3]
list2 = [4, 5]
list3 = list1 + list2
list4 = list1 * 2
print(list3)
print(list4)

————— OUTPUT —————


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

6.4.2 In and Not in operator

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

————— OUTPUT —————


list element found in list
element not found

Self-Instructional
134 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

6.4.3 del Operator - Remove Element NOTES

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

————— OUTPUT —————


[2, 3]

6.4.4 Indexing and Slicing

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

————— OUTPUT —————


1 2 3
3 2 1
[2, 3] [1] [1, 2, 3]

6.4.5 Lists are Mutable

Lists are mutable and can be modified unlike strings.


For Example:
list1 = [1, 2, 3]
list1[0] = 5 Self-Instructional
Material 135

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES print(list1)

————— OUTPUT —————


[5, 2, 3]

6.4.6 Adding and Removing Elements

append() function is used to append elements to the list, insert(i, a) function is used to
insert element ‘a’ at index ‘i’. remove(a) function is used to remove first element that
matches ‘a’. It raises a ValueError if ‘a’ is not found in the list. Slices of lists can also be
assigned values, which can modify the list. The example given below demonstrates all
these functions.
For Example:
list1 = [2, 3]
print(list1)
list1.append(4) # this will add 4 to the last position
print(list1)
list1.insert(0,1) # this will add element 1 at index 0
print(list1)
list1.remove(2) # This will remove element 2
print(list1)
list1[0 : 2] = [0, 1, 2, 3] # this will modify slice [0:2] to
contain 4 elements - 0,1,2, and 3
print(list1)

————— OUTPUT —————


[2, 3]
[2, 3, 4]
[1, 2, 3, 4]
[1, 3, 4]
[0, 1, 2, 3, 4]

Self-Instructional
136 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

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

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

————— OUTPUT —————


3
3
1
6

6.5 TUPLES

Tuples are commonly utilized to represent collections of diverse data enclosed in


parentheses (). They act as containers for storing related pieces of information. Tuples,
when displayed, are always encompassed within parentheses to ensure the proper
interpretation of nested tuples. When inputting tuples, parentheses may or may not be
included, although they are frequently necessary, particularly when the tuple forms
part of a larger expression.

Self-Instructional
Material 137

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES For Example:


tup1 = (1, ‘a’, 4.0)
tup2 = 3, 4, “test”, (1, 2) # Parenthesis not necessary
at the time of input
tup3 = tuple([1,2]) # a tuple may be created through a
list
print(tup1)
print(tup2)
print(tup3)

————— OUTPUT —————


(1, ‘a’, 4.0)
(3, 4, ‘test’, (1, 2))
(1, 2)

A unique consideration arises when constructing tuples containing zero or one


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

————— OUTPUT —————


()
(1,)
Self-Instructional 2
138 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

6.5.1 Concatenation NOTES

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

————— OUTPUT —————


(1, 2, 3, 4, 5)
(1, 2, 3, 1, 2, 3)

6.5.2 Indexing and Slicing

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

————— OUTPUT —————


(1, ‘a’, 4.0)
((1, ‘a’, 4.0), ‘test’, (1, 2))
(1, ‘a’, 4.0)
((1, ‘a’, 4.0), ‘test’)
Self-Instructional
Material 139

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 6.5.3 Built-in functions

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

————— OUTPUT —————


3
2
1
5

6.5.4 Tuples are Immutable

Tuples are immutable which implies assigning values to individual items within a tuple is
not possible, although tuples can contain mutable objects such as lists.
For Example:
tup1 = (1, ‘a’, 4.0, [“test”, “str”])
tup1[0] = 2 # causes error as tuples are immutable

————— OUTPUT —————


TypeError Traceback (most recent
call last)
<ipython-input-31-8dd568d64489> in <cell line: 2> ()
1 tup1 = (1, ‘a’, 4.0, [“test”, “str”])
——> 2 tup1[0] = 2
3
TypeError: ‘tuple’ object does not support item assignment
Self-Instructional
140 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

However, a tuple may contain mutable elements like list and can be accessed NOTES
and manipulated as shown in the example.
For Example:
tup1 = (1, ‘a’, 4.0, [“test”, “str”])
list1 = tup1[3] # element at index 3 is the last element
([“test”, “str”]) in tup1
list1[0] = “change” # first element of the list is set to
“change”
print(list1)
print(tup1) # tup1 still has the same list element at index
3 as tup1 is immutable.
# But since the list is mutable, its first element can
be modified

————— OUTPUT —————


[‘change’, ‘str’]
(1, ‘a’, 4.0, [‘change’, ‘str’])

6.5.5 Packing and Unpacking

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

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES ————— OUTPUT —————


(1, ‘a’, [‘test’, ‘str’])
1
a
[‘test’, ‘str’]

In-Text Questions
1. How do you create a tuple in Python?
2. How do you access individual elements of a tuple?
3. Can you use indexing and slicing with tuples? Provide an example.
4. Can you modify the elements of a tuple once it is created? Why or why not?
5. How do you unpack the elements of a tuple into separate variables?
6. Can a tuple contain mutable objects, such as lists or dictionaries?

6.6 SETS

In Python programming, a Set is an unordered collection of unique elements (i.e., no


duplicate elements unlike lists and tuples). It is represented by curly braces ({}) or
created using the set() function. The given example shows how to create a set and
how it is different from lists and tuples.
For Example:
s1 = {1, 2, 3}
s2= set()
print(type(s1))
print(type(s2))

————— OUTPUT —————


<class ‘set’>
<class ‘set’>

Self-Instructional
142 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

For Example: NOTES


x = (1,2,1) # tuple can contain duplicate elements
y = [1,2,1] # list can contain duplicate elements
z = {1,2,1} # duplicate element 1 will be allowed just once
as shown in the output below
print(x, y, z)

————— OUTPUT —————


(1, 2, 1) [1, 3, 1] {1, 2}
A set may be created using a list or a tuple as shown in the given example.

For Example:
l1 = [1, 2, 3, 1] # create a list
t1= (4, 5, 4) # create a tuple
str1 = ‘abcda’ # create a string
print(type(l1))
print(type(t1))
s1 = set(l1) # create set from list
s2 = set(t1) # create set from tuple
s3 = set(str1) # create set from string
print(type(s1), s1)
print(type(s2), s2)
print(typ (s3), s3)

————— OUTPUT —————


<class ‘list’>
<class ‘tuple’>
<class ‘set’> {1, 2, 3}
<class ‘set’> {4, 5}
<class ‘set’> {‘c’, ‘a’, ‘b’, ‘d’}

Also, it is important to note that when creating an empty set, the set() function
should be used instead of using curly braces ({}), as the latter constructs an empty
dictionary (a data structure covered in the subsequent section). Self-Instructional
Material 143

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES For Example:


l1 = [1, 2, 3, 1] # Create a list
s1 = set() # creates an empty set
s2 = {} #creates a dictionary
print(type(s1), type(s2))

————— OUTPUT —————


<class ‘set’> <class ‘dict’>

Sets are particularly valuable when working with mathematical sets and performing
operations like unions, intersections, and differences. Sets offer efficient membership
testing and enable the removal of duplicate elements with ease.

6.6.1 Membership Test

The ‘in’ operator is used to verify whether an element exists within a set. When applied,
the in operator yields True if the element is found in the set. On the other hand, the ‘not
in’ operator returns True if the specified element is absent from the set.
For Example:
s = {1, 2, 3}
if 1 in s:
print(“1 is an element of set s”)
if 4 not in s:
print(“4 is not an element of set s”)

————— OUTPUT —————


1 is an element of set s
4 is not an element of set s

6.6.2 Union of two sets

The union method or the | operator is used to find the union of two sets S1 and S2. It
forms a new set that contains elements present in either S1, in S2, or in both S1 and
S2.
Self-Instructional
144 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

For Example: NOTES


s1 = {1, 2, 3}
s2 = {1, 2, 3, 4, 5}
s3 = s1 | s2 # take union of two sets using | operator
s4 = s1.union(s2) #take the union of two sets
using the union function
print(s3, s4)

————— OUTPUT —————


{1, 2, 3, 4, 5} {1, 2, 3, 4, 5}

6.6.3 Intersection of two sets

The intersection method or the & (ampersand) operator is used to find the intersection
of two sets S1 and S2. It creates a new set having elements common in S1 and S2.
For Example:
s1 = {1, 2, 3}
s2 = {1, 2, 3, 4, 5}
s3 = s1 & s2 # take intersection of two sets using &
operator
s4 = s1.intersection(s2) #take the intersection of two sets
using the intersection function
print(s3, s4)

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


{1, 2, 3} {1, 2, 3}

6.6.4 Difference between two sets

The difference method or the - (minus) operator is used to find the difference of two
sets S1 and S2. It creates a new set having elements present in set S1 but not in set
S2. In simpler terms, the difference represents the elements unique to set A.

Self-Instructional
Material 145

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES For Example:


s1 = {1, 2, 3}
s2 = {1, 2, 3, 4, 5}
s3 = s1 - s2 # returns a blank set as s1 does not have any
element that is not present in s2
s4 = s2.difference(s1) # returns s2 - s1
print(s3, s4)

————— OUTPUT —————


set() {4, 5}

6.6.5 Symmetric difference of two sets

The symmetric_difference method or the ^ (exclusive) operator is used to find the


symmetric difference of two sets S1 and S2. It creates a new set having elements
present in either set S1 or in set S2 but not in both. In simpler terms, the
symmetric_difference represents the elements that are unique to either set.
For Example:
s1 = {1, 2, 3, 6}
s2 = {1, 2, 3, 4, 5}
s3 = s1 ^ s2 # returns elements present in either
set s1 or in set s2 but not in both
s4 = s2.symmetric_difference(s1)
print(s3, s4)

————— OUTPUT —————


{4, 5, 6} {4, 5, 6}

6.7 DICTIONARIES

Dictionaries in Python are collections of key-value pairs that can be represented by


curly braces ({}) or created using the ‘dict()’ method. The key and value are separated
Self-Instructional
146 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

by a colon (:). Dictionaries are different from Lists as Lists organize elements based on NOTES
their positions. However, there are situations where the programmer is less concerned
about the position of an item in the data structure and more interested in the association
of that element (key) with another element (value) in the structure.

In-Text Questions
1. What is a set in Python, and what are its key characteristics?
2. How do you create an empty set in Python?
3. How do you check if an element exists in a set?
4. Can a set contain duplicate elements? Why or why not?

For Example:
d1 = {‘name’ : ‘Mita’, ‘RollNo’ : 21, ‘admsn_no’ : 112} # for
key ‘name’, ‘Mita’ is the value.
#Similarly for key ‘RollNo’, 21 is the value
print(type(d1))
print(d1)

————— OUTPUT —————


<class ‘dict’>
{‘name’: ‘Mita’, ‘RollNo’: 21, ‘admsn_no’: 112}

There are multiple ways to create a dictionary as shown in the given example.
One approach is to use the dict() constructor. It allows us to create dictionaries from
keyword arguments.
For Example:
d1 = dict(name = ‘Mita’, RollNo = 21, admsn_no = 112) #
dictionary created using keyword arguments, where the argument
names are the keys and their values are provided.
print(type(d1))
print(d1)
Self-Instructional
Material 147

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES ————— OUTPUT —————


<class ‘dict’>
{‘name’: ‘Mita’, ‘RollNo’: 21, ‘admsn_no’: 112}

Another method is to create a dictionary from an iterable of key-value pairs:


For Example:
pairs = [(‘name’, ‘Mita’), (‘RollNo’, 21), (‘admsn_no’, 1)]
d1 = dict(pairs) # dict() constructor converts the iterable
of pairs into a dictionary
print(type(d1))
print(d1)

————— OUTPUT —————


<class ‘dict’>
{‘name’: ‘Mita’, ‘RollNo’: 21, ‘admsn_no’: 1}

Yet another method is to create an empty dictionary and add key: value pairs to it.
For Example:
d1 = {}
d1[‘name’] = ‘Mita’
d1[‘RollNo’] = 21
print(type(d1))
print(d1)

————— OUTPUT —————


<class ‘dict’>
{‘name’: ‘Mita’, ‘RollNo’: 21}

Dictionaries provide efficient lookup and retrieval of values based on keys,


making them suitable for mapping and storing data. Also, they offer the ability to
Self-Instructional
148 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

update or add new key-value pairs. Hence, they are mutable and support operations NOTES
such as adding, updating, and deleting elements.

6.7.1 Accessing Elements

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

————— OUTPUT —————


Mita

6.7.2 Updating and Adding Elements

Dictionaries are mutable, allowing users to modify or insert new key-value pairs. To
update a value, the existing key is referenced and assigned a new value. To add a new
key-value pair, a value is assigned to a previously non-existent key.
For Example:
d1 = {‘name’ : ‘Mita’, ‘RollNo’ : 21, ‘admsn_no’ : 112}
print(d1)
d1[‘name’] = ‘Mitali’
d1[‘ContactNo’] = 9899989998
print(d1)

————— OUTPUT —————


{‘name’: ‘Mita’, ‘RollNo’: 21, ‘admsn_no’: 112}
{‘name’: ‘Mitali’, ‘RollNo’: 21, ‘admsn_no’: 112, ‘ContactNo’:
9899989998}

Self-Instructional
Material 149

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 6.7.3 Removing Elements

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

————— OUTPUT —————


{‘name’: ‘Mita’, ‘RollNo’: 21, ‘admsn_no’: 112}
{‘name’: ‘Mita’, ‘RollNo’: 21}
21
{‘name’: ‘Mita’}

6.7.4 Nested Dictionaries

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

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

print(students) NOTES
print(students[‘Mita’])

————— OUTPUT —————


<class ‘dict’>
<class ‘dict’>
{‘Mita’: {‘RollNo’: 21, ‘admsn_no’: 112}, ‘Smriti’: {‘RollNo’:
22, ‘admsn_no’: 115}, ‘Chetna’: {‘RollNo’: 23, ‘admsn_no’:
117}}
{‘RollNo’: 21, ‘admsn_no’: 112}

6.7.5 Immutable Keys

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

6.7.6 Missing Key value

Accessing a key that does not exist, raises a KeyError. get() method can be used to
handle the error. It returns a default value (None) if the key is not found.
For Example:
d1 = {‘name’ : ‘Mita’, ‘RollNo’ : 21, ‘admsn_no’ : 112}
print(d1.get(‘section’))
print(d1[‘section’])

————— OUTPUT —————


None
KeyError Traceback (most recent
call last)
<ipython-input-21-8f10b3fafc3d> in <cell line: 3>()
1 d1 = {‘name’ : ‘Mita’, ‘RollNo’ : 21, ‘admsn_no’ :
112} Self-Instructional
Material 151

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 2 print(d1.get(‘section’))
——> 3 print(d1[‘section’])
4
KeyError: ‘section’

6.8 DATA STRUCTURES WITH LOOP AND


CONDITIONAL STATEMENTS

Powerful real-world applications can be created using different built-in data structures
together along with loops and conditional statements.
For Example:
Q: Write a Python program to remove all the vowels from a given string.
Sol:
string = “TestString”
vowelChars = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘A’, ‘E’, ‘I’, ‘O’,
‘U’]
NewString = “”

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


of string
if string[i] not in vowelChars: #if ith character of
string is not a vowel
NewString = NewString + string[i]

print(“\nString without vowels:”, NewString)

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


String without vowels: TstStrng

Self-Instructional
152 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

For Example: NOTES


Q: Write a Python program to count the occurrence of a given character in
an input string.
Sol:
str1 = “This is test string”
char_to_count = ‘t’ # Python is case-sensitive language,
‘T’ is not same as ‘t’
count = 0
for i in range(len(str1)):
if(str1[i] == char_to_count):
count = count + 1

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


times in the string:”, str1)

————— OUTPUT —————


Character t occurs 3 times in the string: This is test
string

6.9 SUMMARY

This chapter discussed the characteristics and properties of various built-in data
structures in Python, including strings, lists, tuples, sets, and dictionaries. Each data
structure is described in detail, along with its fundamental characteristics, how to
manipulate and access its elements, and the built-in functions, operators, and operations
associated with it.
Strings are collections of characters and can be enclosed in single or double
quotes. This chapter covered topics such as escaping quotes, special characters, string
concatenation, indexing, slicing, and the immutability of strings.
Lists are introduced as ordered collections of elements enclosed in square
brackets. They are mutable and can store items of different data types. This chapter Self-Instructional
Material 153

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

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

6.10 GLOSSARY

 Data structures: Specialized format for organizing, processing, retrieving and


storing data is known as data structures.
 String: It is the collection of characters.
 Mutable: Values that can be modified are known as mutable.
 Immutable: Values that cannot be modified once created are known as
immutable.

Self-Instructional
154 Material

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


School of Open Learning, University of Delhi
Built-in Data Structures in Python

 Special characters: These are characters that have been assigned special NOTES
meanings like ‘\n’ for new line.
 Concatenation: Merging multiple strings into a single string is known as
concatenation.
 Append: Concatenating at the end is known as append.
 String indexing: It is a Mechanism that allows us to access specific characters
within a string by using subscripts.
 String slicing: It is the extraction of substrings from a string using subscripts.
 List: It is a collection of elements that are ordered (mutable).
 Tuple: It is a collection of diverse data enclosed in parentheses (immutable).
 Set: In Python, set is an unordered collection of unique elements.
 Dictionary: The collection of key-value pairs is known as dictionary.

6.11 SELF-ASSESSMENT QUESTIONS

1. Write a Python program to remove all the vowels from a given string.
2. Write a Python program to check if a string contains only digits.
3. Write a Python program to find the most frequent character in a string.
4. Write a Python program to check if a given string is a palindrome or not.
5. Write a Python program to find the largest element in a list.
6. Write a Python program to find the sum of all elements in a list.
7. Write a Python program to remove all even numbers from a list.
8. How do you find the length of a tuple in Python?
9. Write a Python program to access the third element of a tuple.
10. Write a Python program to create a set with the following elements: 1, 2, 3, 4,
5. Display the set.
Self-Instructional
Material 155

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


School of Open Learning, University of Delhi
Programming Fundamentals Using Python

NOTES 11. Write a Python program to check if the element ‘2’ exists in the set created in
the above question. Display a message indicating whether it exists or not.
12. Write a Python program to create a second set with the following elements: 4,
5, 6, 7, 8. Perform a union operation between the first and second sets and
display the result.
13. Write a Python program to create a third set with the following elements: 6, 7,
8, 9, 10. Perform an intersection operation between the second and third sets
and display the result.
14. Write a Python program to create a dictionary with three key-value pairs: “onion”
with a value of 3, “tomato” with a value of 2, and “potato” with a value of 5.
Display the dictionary.
15. Write a Python program to access and print the value associated with the key
“onion” from the dictionary created in above question.
16. Write a Python program to add a new key-value pair “cucumber” with a value
of 4 to the dictionary created in the above question. Display the updated
dictionary.
17. Write a Python program to check if the key “garlic” exists in the dictionary
created in the above question. Display “Exists” if it does, or “Does not exist”
otherwise.

6.12 REFERENCES

1. Kamthane, A. N., &amp; Kamthane, A. A. (2020). Programming and


Problem Solving with Python. McGraw-Hill Education.
2. Saeed, A., Ayeva, A., Ayeva, K. (2020). Python In - Depth: Use Python
Programming Features, Techniques, and Modules to Solve Everyday
Problems. India: BPB PUBN.
3. Balagurusamy E., (2018). Introduction to Computing and Problem Solving
using Python (2 ed.). McGraw Hill Education.
Self-Instructional
156 Material

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


School of Open Learning, University of Delhi
ISBN

DEPARTMENT OF DISTANCE AND CONTINUING EDUCATION


UNIVERSITY OF DELHI

You might also like