Programming Fundamentals Using Python (Unit 1-4)
Programming Fundamentals Using Python (Unit 1-4)
FUNDAMENTALS
USING PYTHON
B.A. (PROGRAMME) IN COMPUTER SCIENCE DISCIPLINE
SEMESTER-I
DSC-1 (A/B)
(MAJOR PAPER - I)
Editors
Prof. Ajay Jaiswal
Content Writers
Pratibha Yadav, Mansi Sood
Academic Coordinator
Mr. Deekshant Awasthi
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
Printed at: Vikas Publishing House Pvt. Ltd. Plot 20/4, Site-IV, Industrial Area Sahibabad, Ghaziabad - 201 010 ( Copies)
SYLLABUS
Programming Fundamentals Using Python
Syllabus Mapping
CONTENTS
UNIT I
LESSON 1 INTRODUCTION TO PYTHON PROGRAMMING 3-24
UNIT II
LESSON 2 FUNDAMENTALS OF PYTHON PROGRAMMING 27-54
UNIT III
LESSON 5 USER DEFINED FUNCTIONS IN PYTHON 97-120
UNIT IV
LESSON 6 BUILT-IN DATA STRUCTURES IN PYTHON 123-156
LESSON 1 NOTES
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
NOTES
1.1 LEARNING OBJECTIVES
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
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.
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?
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.
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
Self-Instructional
Material 7
NOTES
1.6 PROBLEM SOLVING STRATEGIES
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. 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
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
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”””
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.
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
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
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
1.8.2 Semantics
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
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.
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.
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.
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
NOTES
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
NOTES
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.
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
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.
Self-Instructional
Material 19
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
NOTES
3. Click on Save As option and save the file with a .py extension, say
firstPythonProgram.py.
NOTES
4. The Python interpreter will execute the code, and the output Hello World !!
displayed in the console.
Congratulations! You’ve just run your first Python program that prints “Hello
World!!” to the console.
1.11 SUMMARY
Python is a popular programming language that enables you to create code that is easy
to understand. It is a great pick for beginners due to its simplicity and use. Overall,
Python is a strong and user-friendly 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
1.12 GLOSSARY
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
Self-Instructional
24 Material
LESSON 2 NOTES
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
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
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
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
Numeric literals represent numerical values and falls under three categories: integer,
float and complex.
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
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
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
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)
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
For Example:
# Boolean literals
flag = True
x = False
Self-Instructional
32 Material
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)
In Python there is special literal None which represents the absence of a value.
For Example:
# Special literal
var = None
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
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.
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
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)
NOTES print(a)
print( type(a)) # Since “Hello World!!” is a string, hence type
of variable a is now string not integer
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
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
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
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
Self-Instructional
38 Material
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)
Self-Instructional
Material 39
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)
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
For Example:
a = 10
b = 30
c = 15
print(( c >= 15) and (b < a))
print( not(a <= c))
print(( b != c) or (a == 11))
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
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)
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)
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)
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
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)
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
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.
Self-Instructional
48 Material
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.
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.
Self-Instructional
Material 49
NOTES
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.
For Example:
result = eval( “4 + 5”)
print( result)
result = eval( ‘ 3 ** 3’ )
print( result)
print( eval( ‘7 - 6’))
2.11.3 Output
Python provides print() function to display the output on console or any other standard
output device.
Self-Instructional
50 Material
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
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
Self-Instructional
52 Material
NOTES
2.14 SELF-ASSESSMENT QUESTIONS
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
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.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.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
Scenario 1:
Scenario 2:
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”)
Scenario 1:
Output: NOTES
Congratulations!!
You are eligible to vote
You are outside of if-else block now
Scenario 2:
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
NOTES .
.
.
else:
# Code to be executed if none of the above conditions are
true
For Example:
marks = int(input(“Enter the marks of student”))
Scenario 1:
Scenario 2:
Output: NOTES
You scored Second Division
You are outside the if - elif block now
Scenario 3:
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
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.
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.
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”]
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
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)
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.
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.
For Example:
count = 10 # initializing the loop variable Self-Instructional
Material 63
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”)
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.
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.
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
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
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)
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.
For Example:
for num in range(1,6):
if num == 4:
print(“break”)
break
print(num)
print(“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
Here’s an example that demonstrates the usage of break statement within a NOTES
loop:
languages = [ “JAVA” , “C”, “Python”, “C++”] # list of
programming language
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.
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.
Self-Instructional
Material 69
Example:
for num in range(1,6):
if num == 4:
print(“continue”)
continue
print(num)
print(“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.
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
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.
pass
For Example:
for num in range(1,6):
pass
print(num)
print(“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
NOTES
3.7 GLOSSARY
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
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)
Self-Instructional
Material 73
NOTES
3.9 REFERENCES
Self-Instructional
74 Material
LESSON 4 NOTES
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
NOTES
4.1 LEARNING OBJECTIVES
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.
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”)
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)
NOTES ^
Indentation Error: expected an indented block after ‘for’
statement on line 2
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)
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)
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
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”)
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
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”)
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
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)
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
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”)
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
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.
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
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”)
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
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.
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)
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.1 TypeError
Self-Instructional
88 Material
4.9.2 ValueError
Self-Instructional
Material 89
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)
For Example:
num1 = int(input(“Enter an integer:”))
prints(“Received integer is:”, num1)
Following are some of the most used built-in exceptions available in Python.
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
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
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.
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
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
Self-Instructional
94 Material
LESSON 5 NOTES
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
Self-Instructional
Material 97
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
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
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()
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
func2 = func
func()
func2()
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)
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
x=5 NOTES
y = “test”
a = func()
print(“a:”, a)
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?
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
NOTES print(str)
Display(“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)
Self-Instructional
102 Material
calculate_sum(3, 4)
calculate_sum(3)
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
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
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”)
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
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
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)
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’’’
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
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
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
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
demo_local_scope(5)
print(“b is accessible outside function:”, b)
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
For example:
a=5
def global_var_in_func():
Self-Instructional
112 Material
global a
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
Self-Instructional
114 Material
get_input_and_process()
sum(5)
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
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
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
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.
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
Self-Instructional
120 Material
LESSON 6 NOTES
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
Self-Instructional
124 Material
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))
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’)
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
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)
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
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’)
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
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])
Self-Instructional
Material 129
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
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])
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))
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
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))
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
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”)
Self-Instructional
134 Material
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)
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[ : ])
NOTES print(list1)
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)
Self-Instructional
136 Material
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))
6.5 TUPLES
Self-Instructional
Material 137
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)
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
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))
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
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
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
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
Self-Instructional
142 Material
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)
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
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.
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”)
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
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)
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
6.7 DICTIONARIES
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)
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
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)
update or add new key-value pairs. Hence, they are mutable and support operations NOTES
such as adding, updating, and deleting 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’])
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)
Self-Instructional
Material 149
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)
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’]))
print(students) NOTES
print(students[‘Mita’])
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.
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’])
NOTES 2 print(d1.get(‘section’))
——> 3 print(d1[‘section’])
4
KeyError: ‘section’
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 = “”
Self-Instructional
152 Material
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
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
Self-Instructional
154 Material
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.
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
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