Python Programming
Python Programming
Python Programming
Dr. C. K. Dhaliwal
Assistant Professor
Chandigarh Business School of Administrations
Mohali, Punjab
***
Poonam Rana
Assistant Professor
Chandigarh Business School of Administrations
Mohali, Punjab
***
Dr. T. P. S. Brar
Professor & Head of Department
Chandigarh Group of Colleges
Mohali, Punjab
First published 2025
by CRC Press
4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN
and by CRC Press
2385 NW Executive Center Drive, Suite 320, Boca Raton FL 33431
CRC Press is an imprint of Informa UK Limited
© 2025 Manakin Press Pvt. Ltd
The right of of C. K. Dhaliwal, Poonam Rana and Dr. T. P. S. Brar to be identified as authors
of this work has been asserted in accordance with sections 77 and 78 of the Copyright,
Designs and Patents Act 1988.
All rights reserved. No part of this book may be reprinted or reproduced or utilised in any
form or by any electronic, mechanical, or other means, now known or hereafter invented,
including photocopying and recording, or in any information storage or retrieval system,
without permission in writing from the publishers.
For permission to photocopy or use material electronically from this work, access www.
copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive,
Danvers, MA 01923, 978-750-8400. For works that are not available on CCC please contact
mpkbookspermissions@tandf.co.uk
Trademark notice: Product or corporate names may be trademarks or registered trademarks,
and are used only for identification and explanation without intent to infringe.
Print edition not for sale in South Asia (India, Sri Lanka, Nepal, Bangladesh, Pakistan or
Bhutan).
British Library Cataloguing-in-Publication Data
A catalogue record for this book is available from the British Library
ISBN: 9781032646558 (hbk)
ISBN: 9781032669571 (pbk)
ISBN: 9781032691053 (ebk)
DOI: 10.4324/9781032691053
Typeset in Times New Roman
by Manakin Press, Delhi
Organization of the Book
Chapter 1 This is an introductory chapter that provides an overview of Python,
covering its history, features, applications, and installation process. It highlights
Python's dynamic, high-level, and object-oriented language features and cross-
platform compatibility. The chapter emphasizes the use of Python in web development,
data science, and machine learning. It also explains Python interactive help and
demonstrates how to install and execute Python on different platforms. Additionally,
the chapter covers how Python differs from other programming languages.
Chapter 4 This chapter covers conditional statements in Python, including if, if-
else, and if-elif-if statements. It also covers loops in Python, including while, for,
and infinite loops, along with examples of how to use them. Additionally, the chapter
covers the use of the break, continue, and pass statements in Python loops, which are
used to change the flow of control in a program.
Chapter 5 This chapter covers the native data types in Python, including numbers,
lists, tuples, sets, dictionaries, and strings. It provides examples and use cases for
each data type. The chapter highlights the differences between mutable and immutable
data types and how to work with them. Additionally, it covers how to manipulate and
operate on data types, including slicing and indexing.
Chapter 6 This chapter covers Python functions, including the types of functions in
Python, such as built-in functions, user-defined functions, and anonymous functions.
It discusses the advantages of using functions, such as code reusability, modularity,
and easier debugging. The chapter also covers the differences between pass by value
and pass by reference and demonstrates recursion, which is the ability of a function
to call itself.
vi Python Programming: A Step-by-Step Guide to Learning the Language
Chapter 7 This chapter covers Python modules, which are files that contain Python
definitions and statements. It demonstrates how to create a module and how to import
it into another Python program. Additionally, the chapter covers standard modules,
which are built-in modules that come with Python, and Python packages, which are
directories containing modules. It highlights how to use and install standard modules
and how to create and install Python packages.
Chapter 8 This chapter covers Python exceptions, which are errors that occur during
program execution. It explains the different types of built-in exceptions in Python,
such as ZeroDivisionError and TypeError. The chapter demonstrates how to handle
exceptions using the try-except block and how to raise and catch user-defined
exceptions. It also provides examples of exception handling and how to use the else
and finally clauses with the try-except block.
Chapter 9 This chapter covers file operations in Python, including how to create,
open, read, write, and close files using file methods such as read() and write(). The
chapter also covers renaming and deleting files, as well as creating and navigating
directories in Python using the os module. It provides examples of how to use file
methods and how to handle file exceptions.
Chapter 10 This chapter covers designing classes in Python, which are templates for
creating objects that have similar properties and behaviors. It explains how to create
objects from a class, how to access object attributes, and how to use built-in class
attributes, such as name and doc. The chapter also covers garbage collection in Python,
which is the process of freeing up memory that is no longer being used by a program.
It provides examples of how to design and use classes in Python.
Chapter 11 This chapter covers inheritance in Python, which is the ability to create
a new class from an existing class. It explains the different types of inheritance in
Python, including single inheritance, multiple inheritance, and multilevel inheritance.
The chapter also covers method overriding in Python, which is the ability to redefine a
method in a subclass. Additionally, the chapter discusses special functions in Python,
which are predefined methods that are called under certain circumstances, such as init
and str. It provides examples of how to use inheritance and special functions in Python.
Chapter 12 This chapter covers operator overloading in Python, which is the ability to
redefine the behavior of an operator in a class. It explains how to overload the + and -
operators in Python, as well as bitwise and relational operators. The chapter provides
examples of how to use operator overloading to customize the behavior of operators
in Python.
The Appendix- I is given which provides the list of Python Standard Modules with
the description of each.
Authors
Detailed Contents
Introduction to Python
Language
Highlights
l Introduction and History of Python Language
l Features of Python
l Applications of Python
l Python Interactive Help
l Installing and Executing Python
l How Python Differs from Other Languages
Today, Python is one of the most popular programming languages in the world,
and is used in a wide variety of applications, including web development, data
analysis, artificial intelligence, and scientific computing. It is a powerful and
flexible language that is well-suited to many different tasks, and it has a large
and vibrant community of developers who continue to work on improving the
language and developing new libraries and tools.
Introduction to Python Language 5
your platform, you can compile the source code manually using a C compiler.
The installation process for Python may differ slightly depending on the
platform, and specific instructions can be found on the official website for
each platform, such as Unix or Linux.
running Python code. Some popular IDEs for Python include PyCharm,
Visual Studio Code, and Spyder.
Once you have Python installed and set up, you can start writing and running
Python code to perform various tasks and solve problems.
This will execute the script, and you should see the output Hello, World! in
the terminal or command prompt.
You can also pass command-line arguments to a Python script by including
them after the script name. For example, if you have a script called add.py
14 Python Programming: A Step-by-Step Guide to Learning the Language
that takes two numbers as arguments and adds them together, you could run
it with the following command:
python add.py 2 3
This would execute the script with the arguments 2 and 3, and the output
would be 5.
Note that in order to run a Python script from the command-line, you must
have Python installed on your computer and the Python executable must be
in your system’s PATH variable.
This would define a variable x with the value 5, and then define a variable y
with the value 10 (which is the result of multiplying x by 2). Finally, it would
print the value of y to the console.
16 Python Programming: A Step-by-Step Guide to Learning the Language
You can exit the interactive interpreter by typing exit() or quit() at the
command prompt and pressing Enter. This will return you to the terminal or
command prompt.
13. Memory Safety: C++ is a language that provides the programmer with
the ability to manually manage memory. While this gives the programmer
more control over how memory is used, it also means that the program
can be susceptible to memory-related bugs, such as buffer overflows
and memory leaks. Python has built-in garbage collection, meaning that
it automatically manages memory, which makes it less susceptible to
memory-related bugs.
These are just a few of the many differences between C++ and Python. While
both languages are widely used and powerful, they have different strengths
and weaknesses, and the choice of language will depend on the specific needs
of the project and the preferences of the programmer.
into objects and classes. Python, on the other hand, allows for more
procedural and functional programming styles as well.
6. Application: Java is often used for web development, desktop application
development, and mobile app development. Python is often used for web
development, scientific computing, data analysis, machine learning, and
automation.
7. Performance: Java is generally faster than Python because it is
a compiled language, and the JVM can optimize the bytecode for
performance. Python, on the other hand, is an interpreted language,
meaning that the code is executed directly by an interpreter, which can
be slower. However, Python has some libraries that are implemented in
C or C++ that can boost its performance.
8. Garbage Collection: Java has a more advanced garbage collector than
Python, meaning that it can handle memory more efficiently.
9. Learning Curve: Java is generally considered more difficult to learn
and use than Python. Java has a steep learning curve because it is a more
complex language with a larger number of features and more stringent
syntax rules. Python, on the other hand, has a simpler syntax and a
smaller set of features, making it easier to learn and use.
These are just a few of the many differences between Java and Python. While
both languages are widely used and powerful, they have different strengths
and weaknesses, and the choice of language will depend on the specific needs
of the project and the preferences of the programmer.
1.15 Summary
In this chapter, we have learned about the programming language and its
needs. Then we gave a brief look at the origin and history of the Python
language along with its features and limitations. We have explored in detail
how Python language differs from other existing and prominent programming
languages such as C,C++, and Java. The setup and installation of Python
language along with a simple first program are also discussed in detail.
Review Questions
1. What is Python and what makes it a popular programming language?
2. How does Python differ from other programming languages?
Introduction to Python Language 23
Highlights
l Keywords and identifiers
l Python statements
l Documentation and indentation
l Python Variables
l Python data types
l Input and output
l Import
Python has several built-in data types including strings, integers, and
lists. These data types can be used to store and manipulate different kinds
of information in a program. In addition to these basic data types, Python
also has advanced data types such as dictionaries and sets.
Python also has a built-in module for input/output operations, which
allows a program to read from and write to external sources, such as files
and streams. The module, called io, provides several functions to perform
these operations, such as open(), read(), and write().
2.1 Keywords
In Python, a keyword is a word that has a special meaning in the Python
language. Keywords are used to define the syntax and structure of the
26 Python Programming: A Step-by-Step Guide to Learning the Language
Python language, and they cannot be used as identifiers (i.e., variable names,
function names, etc.) in Python code.
Keyword Description
and Logical operator returns True if both operands are True,
otherwise, it returns False.
as Used to create an alias for a module or variable when
importing or renaming.
assert Used to check if a given condition is True, and raises an
exception if it is False.
async Used to define an asynchronous function or context manager.
await Used inside an async function to wait for an asynchronous
operation to complete.
break Used to exit a loop early, before the loop condition is met.
class Used to define a new class.
continue Used to skip the current iteration of a loop and continue with
the next iteration.
def Used to define a new function.
del Used to delete an object or an item from a collection.
elif Short for “else if”, used in a conditional statement to check
for additional conditions.
else Used in a conditional statement as a catch-all option if no
other conditions are met.
except Used to handle exceptions that are raised in a try block.
False Boolean value that represents the absence of truth.
finally Used in a try-except block to specify a block of code that
will always be executed, regardless of whether an exception
was raised or not.
for Used to iterate over a sequence of items, such as a list or a
tuple.
from Used in an import statement to import specific items from
a module.
global Used to indicate that a variable is a global variable, accessible
from anywhere in the code.
if Used to start a conditional statement.
import Used to import a module or a specific item from a module.
Python Data Types and Input Output 27
Keyword Description
in Used to check if an item is in a sequence, such as a list or
a tuple.
is Used to check if two variables refer to the same object.
lambda Used to create small anonymous functions.
None Special value that represents the absence of a value or a null
value.
nonlocal Used to indicate that a variable is nonlocal to the current
function, meaning it is defined in an outer function.
not Logical operator that negates a boolean value.
or Logical operator that returns True if at least one of the
operands is True, otherwise it returns False.
pass Used as a placeholder for a block of code that does nothing.
raise Used to raise an exception.
return Used to exit a function and return a value to the calling code.
True Boolean value that represents the presence of truth.
try Used to specify a block of code that might raise an exception.
while Used to start a loop that will continue to execute as long as
the loop condition is True.
with Used to create a context manager, which is used to
automatically set up and tear down resources.
yield Used in a function
2.2 Identifiers
In Python, an identifier is a name used to identify a variable, function, class,
module, or other objects. There are a few rules and conventions for naming
identifiers in Python:
• Identifiers must start with a letter or an underscore (_).
• Identifiers cannot start with a number.
• Identifiers can only contain letters, numbers, and underscores.
• Identifiers are case-sensitive, so myVariable and myvariable are
considered to be different identifiers.
• Python reserves a set of keywords that cannot be used as identifiers.
Examples include if, else, for, class, etc.
28 Python Programming: A Step-by-Step Guide to Learning the Language
2.4 Indentation
Indentation is used in Python to indicate blocks of code. The standard
indentation is four spaces, and most Python code follows this convention.
For example
Code 2.1 Illustration of indentation in Python
def foo():
# This line is indented by four spaces
x=5
if x > 0:
# This line is also indented by four spaces
print(“x is positive”)
# This line is not indented, so it’s not part of the if block
It is important to be consistent with your indentation, as the meaning of the
code can change based on the indentation level. For example
Code 2.2 Illustration of indentation in Python
x=5
if x > 0:
print(“x is positive”)
print(“This line is not indented, so it’s not part of the if block”)
This code will print both messages because the second print statement is not
indented, so it is not part of the if block.
Code 2.3 Illustration of indentation in Python
x=5
if x > 0:
print(“x is positive”)
print(“This line is indented, so it is part of the if block”)
print(“This line is not indented, so it’s not part of the if block”)
30 Python Programming: A Step-by-Step Guide to Learning the Language
This code will only print the first message, because the second print statement
is indented, so it is part of the if block.
lines and are commonly used for longer explanations and docstrings. Here is
an example:
Code 2.7 Illustration of double quotes in Python
“””
This is a multiline
comment. It can span
multiple lines.
“””
You can also use triple single quotes to create a multiline comment:
Code 2.8 Illustration of single quotes in Python
‘’’
This is also a
multiline comment. It
can also span multiple
lines.
‘’’
Both triple quotes (single or double) can be used to create a multiline
comment in Python. The advantage of using triple quotes is that you can
create a multiline comment even if it contains multiple lines of the same type
of quote character.
2.6 Docstrings
In Python, a docstring is a string literal that appears as the first statement
in a module, function, class, or method definition. It is used to provide
documentation for the code, and can be accessed using the built-in help()
function or the __doc__ attribute. Docstrings are enclosed in triple quotes
(either single or double) and are typically written in plain text, but can also
include markdown formatting.
It is a good practice to include a docstring in any function or class you write,
as it makes your code more readable and user-friendly.
Here is an example of a simple Python function with a docstring:
32 Python Programming: A Step-by-Step Guide to Learning the Language
Parameters:
a (int): The first number
b (int): The second number
Returns:
int: The sum of a and b
“””
return a + b
In this example, the function add takes two numbers as input, adds them
together, and returns the result. The docstring provides a brief description of
what the function does, and explains the parameters and return value.
To access the docstring of this function, you can use the help() function like
this:
help(add)
You can also access the docstring programmatically using the __doc__
attribute:
print(add.__doc__)
2.7 Variables
A Python variable is a reserved memory location to store values. In other
words, a variable in a python program gives data to the computer for
Python Data Types and Input Output 33
assigned to it during its lifetime must always have that type. Variables in
Python are not subject to this restriction. In Python, a variable may be
assigned a value of one type and then later re-assigned a value of a different
type:
Code 2.11 Illustration of variable in Python
var = 21.09
print(var)
21.09
Let’s see another example:
Code 2.12 Illustration of variable in Python
>>> var = “Welcome to Python”
>>> print(var)
Welcome to Python
Parenthesis are optional around tuples in Python and they’re also optional
in multiple assignment (which uses a tuple-like syntax). All of these are
equivalent:
Python Data Types and Input Output 35
Integer String
Float Numbers List
Complex numbers Tuples
In Python, there are several built-in data types that you can use to store values
in your program. These data types include
1. Integers: These are whole numbers, both positive and negative. For
example 42, -7, 0.
2. Floating-point numbers: These are numbers with a decimal point, such
as 3.14 or -0.01.
3. Complex Numbers: These are the numbers that has both a real and an
imaginary component. For example 3+6j.
4. Strings: These are sequences of characters, represented using quotes.
You can use single quotes (‘) or double quotes (“) to represent strings.
For example: ‘hello’, “world”, ‘42’.
5. Booleans: These represent truth values and can be either True or False.
6. Lists: These are ordered collections of other values. You can define a list
by enclosing a comma-separated sequence of values in square brackets
([]). For example: [1, 2, 3], [‘a’, ‘b’, ‘c’], [True, False].
Python Data Types and Input Output 37
7. Tuples: These are like lists, but they are immutable (i.e., you cannot
modify them). You can define a tuple by enclosing a comma-separated
sequence of values in parentheses (()). For example: (1, 2, 3), (‘a’, ‘b’,
‘c’), (True, False).
8. Sets: These are unordered collections of unique values. You can define a
set by enclosing a comma-separated sequence of values in curly braces
({}). For example: {1, 2, 3}, {‘a’, ‘b’, ‘c’}, {True, False}.
9. Dictionaries: These are unordered collections of key-value pairs. You
can define a dictionary by enclosing a comma-separated sequence of
key-value pairs in curly braces ({}). The key and value are separated by
a colon (:). For example: {‘a’: 1, ‘b’: 2, ‘c’: 3}, {‘a’: ‘A’, ‘b’: ‘B’, ‘c’:
‘C’}, {True: ‘Yes’, False: ‘No’}.
2.9.1.1 Integers
In Python, an integer is a whole number that can be positive, negative, or
zero. It has no fractional part and is represented by a series of digits. For
example, the integers 123, -456, and 0 are all integers. To create an integer
in Python, you can simply assign a whole number to a variable. For example:
Code 2.15 Illustration of integer number data types
x = 123
y = -456
z=0
You can also use the int() function to convert a string or a floating-point
number to an integer. For example
38 Python Programming: A Step-by-Step Guide to Learning the Language
You can also create a complex number using the built-in complex() function.
For example:
x = complex(3, 4)
You can access the real and imaginary components of a complex number
using the real and imag attributes, respectively. For example:
Code 2.19 Illustration of complex number data types
x = 3 + 4j
print(x.real) # Output: 3.0
print(x.imag) # Output: 4.0
You can also perform mathematical operations with complex numbers, such
as addition, subtraction, multiplication, and division. For example:
Code 2.20 Illustration of mathematical operations with complex numbers
x = 3 + 4j
y = 2 + 3j
print(x + y) # Output: (5+7j)
print(x - y) # Output: (1+1j)
print(x * y) # Output: (-6+17j)
print(x / y) # Output: (1.6+0.4j)
40 Python Programming: A Step-by-Step Guide to Learning the Language
2.9.2 Strings
In Python, a string is a sequence of characters enclosed in quotation marks.
You can use either single quotes or double quotes to create a string. For
example:
string1 = ‘Hello, world!’
string2 = “Hello, world!”
Both of these expressions create a string with the value “Hello, world!”.
You can use the “+” operator to concatenate (join) two strings together. For
example:
Code 2.21 Illustration of Strings in Python
greeting = “Hello”
name = “Alice”
message = greeting + “, “ + name + “!”
print(message) # prints “Hello, Alice!”
repeat = “*” * 10
print(repeat) # prints “**********”
There are many other operations and methods available for working
with strings in Python. You can learn more about strings in the Python
documentation.
2.9.2.3 Slicing
Negative indexing can use to extract a range of characters from a string
or to extract a substring from a string by specifying the start and end
index separated by a colon : , known as slicing. The syntax for slicing is
string[start:stop:step], where start is the index of the first character to include
stop is the index of the first character to exclude and step is the number of
indices between characters
Code 2.24 Illustration of slicing operator in Python
string = “Hello, World!”
print(string[7:12]) # Output: ‘World’
print(string[:5]) # Output: ‘Hello’
print(string[7:]) # Output: ‘World!’
You can also use negative indexing and positive indexing together in the
slicing.
Code 2.25 Illustration of negative and positive indexing in Python
string = “Hello, World!”
print(string[0:-1]) # Output: ‘Hello, World’
print(string[-12:5]) # Output: ‘Hello’
42 Python Programming: A Step-by-Step Guide to Learning the Language
2.9.3 Booleans
In Python, a boolean is a data type that represents one of two values: True or
False. Booleans are often used to represent the truth value of an expression
or to represent the state of a toggle. Here are a few examples of boolean
expressions in Python:
Code 2.26 Illustration of Booleans in Python
>>> 2 < 3
True
>>> 2 > 3
False
>>> 3 == 3
True
>>> ‘hello’ == ‘goodbye’
False
>>> True and False
False
>>> True or False
True
You can also use boolean values in control statements such as if and while to
execute code conditionally. For example:
Code 2.26 Illustration of Booleans values in control statements
>>> x = 10
>>> if x > 5:
>>> print(‘x is greater than 5’)
x is greater than 5
2.9.4 Lists
In Python, a list is an ordered collection of objects. You can create a list by
enclosing a comma-separated sequence of objects in square brackets ([]). For
example:
Python Data Types and Input Output 43
This will return a new list with elements at indices 1 and 2 (i.e., 2 and 3).
Slice a[1:3] does not include the element at index 3. If you want to include
the element at index 3, you can use slice a[1:4].
2.9.5 Tuples
In Python, a tuple is an immutable sequence type. Tuples are similar to lists,
but they are created using parentheses instead of square brackets. Because
tuples are immutable, you can’t add or remove elements from them or
sort them in place. However, you can use tuples to create new tuples, by
concatenating or slicing them. Here’s an example of how to create a tuple.
44 Python Programming: A Step-by-Step Guide to Learning the Language
You can access the elements of a tuple using indexing, just like with a list:
>>> t[1]
‘a
You can also slice a tuple, to get a new tuple with only a portion of the
original tuple:
>>> t[1:]
(‘a’, 3.14)
Tuples also support all of the common sequence operations, such as
concatenation, repetition, and membership testing.
Code 2.31 Illustration of tuple in Python
>>> t * 3
(1, ‘a’, 3.14, 1, ‘a’, 3.14, 1, ‘a’, 3.14)
>>> 3 in t
False
>>> t + (4, 5, 6)
(1, ‘a’, 3.14, 4, 5, 6)
Because tuples are immutable, you can be sure that the values in the tuple
won’t be changed accidentally.
2.9.6 Sets
In Python, a set is a collection of items that is unordered, changeable, and does
not allow duplicates. Sets are written with curly braces, and the elements are
separated by commas. Here’s an example of how to create a set in Python:
Code 2.32 Illustration of set in Python
# Create a set
fruits = {‘apple’, ‘banana’, ‘mango’}
# Check the type of the object
print(type(fruits))
# Output: <class ‘set’>
Python Data Types and Input Output 45
Sets are useful for storing and working with data when you don’t need to
preserve the order of the items, or when you want to eliminate duplicates. For
example, you might use a set to store a list of unique words in a document
or to store a list of unique user IDs in a database. You can perform various
operations on sets, such as adding and removing items, computing the
intersection and union of sets, and so on. Here are some examples:
Code 2.33 Illustration of set in Python
# Add an element to the set
fruits.add(‘orange’)
print(fruits)
# Output: {‘apple’, ‘banana’, ‘mango’, ‘orange’}
2.7.8 Dictionaries
In Python, a dictionary is a collection of key-value pairs. It is an unordered
data structure that allows you to store and access data efficiently. Here is an
example of how you can create a dictionary in Python:
Code 2.34 Illustration of dictionary in Python
>>> my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
>>> print(my_dict)
{‘a’: 1, ‘b’: 2, ‘c’: 3}
You can access the values in a dictionary by using the keys:
>>> my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
>>> print(my_dict[‘a’])
1
>>> print(my_dict[‘b’])
2
>>> print(my_dict[‘c’])
3
You can also use the get() method to access the values in a dictionary. This
method returns the value for the given key if it exists in the dictionary. If the
key does not exist, it returns a default value:
Code 2.35 Illustration of dictionary in Python
>>> my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
>>> print(my_dict.get(‘a’))
1
>>> print(my_dict.get(‘d’))
None
>>> print(my_dict.get(‘d’, ‘key does not exist’))
‘key does not exist’
>>> my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
>>> print(my_dict.get(‘a’))
1
>>> print(my_dict.get(‘d’))
None
>>> print(my_dict.get(‘d’, ‘key does not exist’))
‘key does not exist’
Python Data Types and Input Output 47
you expect. It also improves the readability of the code and makes it easier
to understand.
There are other ways to accept input in Python, such as using the argparse
module or reading from a file, but these are the most basic methods. To
provide output to the user, you can use the print() function. For example:
Python Data Types and Input Output 51
print(“Hello, world!”)
This would print the string “Hello, world!” to the console.
2.12 Import
In Python, the import statement is used to import modules whose functions
or variables can be used in your current program. For example, to import the
math module, you can use the following code:
import math
This allows you to access the functions and variables defined in the math
module using the dot notation. For example, you can use the sqrt() function
from the math module like this:
Code 2.41 Illustration of import statement in Python
import math
x = math.sqrt(25)
print(x) # Output: 5.0
You can also import specific functions or variables from a module using the
from keyword. For example:
Code 2.42 Illustration of import statement in Python
from math import sqrt
x = sqrt(25)
print(x) # Output: 5.0
2.13 Summary
In this chapter, we covered the fundamentals of the Python language,
including keywords, identifiers, variables, and the rules for using them. We
also discussed Python documentation, single-line and multi-line comments,
and various data types such as numbers, strings, lists, tuples, sets, dictionaries,
and files. We demonstrated how to use interactive input and output functions
in Python and showed how to do formatted input and output. Finally, we
demonstrated how to use the import command to call and use one module
in another.
52 Python Programming: A Step-by-Step Guide to Learning the Language
Review Questions
1. What are the Python keywords and how are they used in a program?
2. What is the difference between a Python identifier and a Python keyword?
3. How does identation affect the structure of a Python program?
4. What are some common Python statements used for flow control and
iteration?
5. How does the input() function work in Python and what is its output data
type?
6. What is the purpose of using documentation in a Python program and
how is it written?
7. How does the import statement work in Python and what are the different
types of imports?
8. What are the different ways to perform output operations in Python?
9. How can we handle errors and exceptions in Python programs and what
are the built-in exception types?
10. What is the difference between a local and global variable in Python and
when should each be used?
11. Which of the following is not a Python data type?
a. list
b. tuple
c. dictionary
d. Matrix
12. What is the data type of ‘Hello, World!’ in Python?
a. int
b. float
c. string
d. boolean
3
Operators and
Expressions
Highlights
l All Python operators
l Precedence and associativity of operators
l Expressions
3.1 Operator
Operators in Python are special symbols that perform specific operations on
one, two or more operands (values) and produce a result. Operators can be
classified into different categories such as arithmetic, comparison, logical,
bitwise, assignment and identity operators, each with a specific purpose.
54 Python Programming: A Step-by-Step Guide to Learning the Language
• Arithmetic operators
• Comparison (Relational) operators
• Logical operators
• Boolean operators
• Assignment operators
• Bitwise operators
• Membership operators
• Identity operators
# Subtraction
x=3-4
print(x) # Output: -1
# Multiplication
x=3*4
print(x) # Output: 12
# Division
x=3/4
print(x) # Output: 0.75
# Modulus
x=7%3
print(x) # Output: 1
56 Python Programming: A Step-by-Step Guide to Learning the Language
# Exponentiation
x = 3 ** 4
print(x) # Output: 81
# Floor division
x = 7 // 3
print(x) # Output: 2
It’s also important to note that Python follows the order of operations
(PEMDAS) when evaluating arithmetic expressions.
PEMDAS stands for Parentheses, Exponents, Multiplication and Division,
and Addition and Subtraction. It is the order in which Python (and most other
programming languages and math systems) evaluates arithmetic operations in
an expression.
1. Parentheses: Expressions within parentheses are evaluated first.
2. Exponents: Exponentiation (ie raising to a power) is done next.
3. Multiplication and Division (from left to right): These operations are
done next, from left to right.
4. Addition and Subtraction (from left to right): These operations are done
last, from left to right.
# Not equal to
x=3
y=4
print(x != y) # Output: True
# Greater than
x=3
y=4
print(x > y) # Output: False
# Less than
x=3
y=4
print(x < y) # Output: True
It is important to note that the right-hand side of the operator must be a valid
expression that can be evaluated to a value. Also, the above table is meant to
give you an idea of the operations being performed and the resulting values,
but in practice, you would need to assign the values to the variable and then
perform the operations.
The and operator returns True if both the expressions on either side of it are
True, and False otherwise.
The or operator returns True if either of the expressions on either side of it
are True, and False otherwise.
The not operator negates the boolean value of the expression that follows it.
So, if the expression is True, not will make it False, and if the expression is
False, not operator will make it True.
Lets understand with an example that shows the results of different logical
operations using the and, or, and not operators in Python in the table.
Expression Result
True and True True
True and False False
False and False False
True or True True
True or False True
False or False False
not True False
not False True
Note that the and, or, and not keywords are used to perform logical operations
in Python, as opposed to the symbols &, |, and ! commonly used in other
programming languages.
Keep in mind that these operators only work on integers and the result is also
an integer.
Here another example of each operator:
Code 3.7 Illustration of bitwise operators
# & operator (bitwise AND)
x = 0b10101010 # 170
y = 0b01010101 # 85
z = x & y # 0b00000000 = 0
It’s important to note that the identity operators check for object identity, not
object equality. In other words, they check if two objects are the same object
in memory, not if they have the same content. For example
Code 3.9 Illustration of identity operators
x = [1, 2, 3]
y = [1, 2, 3]
3.2 Expressions
Expressions are statements that can be evaluated to a value. In Python, an
expression is a combination of values, variables, and operators that can be
evaluated to a single value. For example, the expression 2 + 3 is a numerical
expression that evaluates to the value 5. The expression “Hello, “ + “World!”
is a string expression that evaluates to the value “Hello, World!”.
66 Python Programming: A Step-by-Step Guide to Learning the Language
You can use parentheses to override the precedence and specify the order in
which the operations should be performed. For example, in the expression
(4 + 5) * 2, the parentheses indicate that the addition should be performed
before the multiplication, so the expression is evaluated as (4 + 5) * 2, which
is equal to 14.
3.2.2 Associativity
In Python, the associativity of an operator determines the order in which
operations with the same precedence are performed. Most operators in Python
are left-associative, which means that operations are performed from left to
right.
For example, in the expression 2 + 3 - 4, the addition (+) and subtraction (-)
operators have the same precedence, so they are performed from left to right.
The expression is evaluated as (2 + 3) - 4, which is equal to 1.
However, some operators are right-associative. This means that operations are
performed from right to left. The exponentiation operator (**) is an example
of a right-associative operator in Python.
For example, in the expression 2 ** 3 ** 4, the exponentiation operator (**)
has the same precedence, so it is performed from right to left. The expression
is evaluated as 2 ** (3 ** 4), which is equal to 2 ** 81, or 43046721.
Here is a list of the operators in Python, along with their associativity:
Left-associative:
• + - Addition and subtraction
• * / % // Multiply, divide, modulo and floor division
• >> << Right and left bitwise shift
• & Bitwise ‘AND’
• ^ | Bitwise exclusive OR and regular OR
• <= < > >= Comparison operators
• == != Equality operators
• = %= /= //= -= += *= **= Assignment operators
• is is not Identity operators
• in not in Membership operators
• not or and Boolean NOT, OR, and AND
68 Python Programming: A Step-by-Step Guide to Learning the Language
Right-associative:
• ** Exponentiation (raise to the power)
3.3 Summary
In this chapter, we have learned about different operators such as arithmetic,
comparison, logical, bitwise, special operators, identity, and membership
operators available in the Python language. All the operators are described
with appropriate examples of each. We have learned how operators and
operands form an expression, which is the basic sentence of a programming
language. The precedence decides which operator will be evaluated first
and associativity decides how to evaluate an expression if two operators
exhibit the same precedence. Finally, we have learned how Python language
evaluates expressions.
Review Questions
1. What are the different types of operators available in Python?
2. Can you explain the precedence of operators in Python?
3. What is the associativity of the Python operators?
Operators and Expressions 69
Control Structures
Highlights
l Python if, if else, if-elif-if statements
l Python while, for, infinite loop
l Python break, continue and pass statements
The code block inside the if statement will only be executed if the condition
num > 0 is true. In this case, the condition is true, so the code block will be
executed and the message “The number is positive” will be printed to the
console.
Another example of using an “if” statement to print multiple statements in
Python:
Code 4.2 A Program to print multiple statements when a given condition
is true.
x=5
if x > 0:
print(“x is positive”)
print(“x is greater than 0”)
print(“x is a positive number”)
In this example, the “if” statement is used to check if the variable x is greater
than 0. If it is, the code inside the “if” block will be executed and all the three
print statements will be executed, resulting in the following output:
x is positive
x is greater than 0
x is a positive number
true
condition
false
statement (s)
rest of code
In this program, the input function is used to take the age of the user as an
integer and store it in the variable “age”. Then, the “if-else” statement is used
to check if the variable “age” is greater than or equal to 18. If it is, the code
inside the “if” block will be executed and the message “You are eligible to
vote.” will be printed. If the condition is not met, the code inside the “else”
block will be executed and the message “You are not eligible to vote.” will
be printed.
x = 10
if x < 0:
print(“x is a negative number”)
elif x == 0:
print(“x is zero”)
else:
print(“x is a positive number”)
Output:
x is a positive number
In this example, the variable x is first given the value of 10. The program
then checks if the value of x is less than 0. Since it is not, the program moves
on to the next elif statement and checks if x is equal to 0. Since it is not, the
program moves on to the final else statement and executes the code within it,
which is to print “x is positive”.
The if elif else statement allows you to check multiple conditions and execute
different code for each one. The if statement checks the first condition, if the
condition is true, it will execute the corresponding block of code and exit the
statement. If the condition is false, the program will move on to the next elif
statement and check the next condition. If none of the conditions are true, the
code in the else block will be executed.
Code 4.6 A Program to demonstrate the use of multiple if elif conditions.
grade = “B”
if grade == “A”:
print(“Excellent work!”)
elif grade == “B”:
print(“Good job!”)
elif grade == “C”:
print(“Average performance.”)
elif grade == “D”:
print(“Needs improvement.”)
else:
print(“Invalid grade.”)
Control Structures 77
In this example, the variable grade is assigned the value “B”. The program
then checks each elif statement in order, starting with the first one. When
it finds the first condition that is true (grade == “B”), it will execute the
corresponding block of code (printing “Good job!”) and exit the statement. If
none of the conditions are true, it will execute the code in the else statement,
printing “Invalid grade.”
You can see from the example, the if elif else statement is useful when you
have multiple conditions that you want to check and different actions to take
depending on the outcome of those checks.
Body of Body of
Body of if nested if nested else
Statement just
below if
if x > y:
print(“x is greater than y”)
if x > 10:
print(“x is also greater than 10”)
78 Python Programming: A Step-by-Step Guide to Learning the Language
else:
print(“x is not greater than 10”)
else:
print(“x is not greater than y”)
if x > 0:
if y > 0:
print(“Both x and y are greater than 0”)
elif y<0:
print(“x is greater than 0, but y is less than 0”)
else:
print(“x is not greater than 0”)
i=0
while True:
i += 1
if i % 2 == 0:
continue
print(i)
if i == 10:
break
This while loop will also run indefinitely, but the continue statement will
cause it to skip the remainder of the current iteration when i is even, and the
break statement will cause it to exit when i becomes 10. The output will be
the odd numbers 1 through 9.
Here’s another program that demonstrates the use of while loop in Python:
Code 4.10 Program to calculate the sum of numbers entered by the user.
# Initialize variables
sum = 0
number = 1
# Ask the user to enter numbers
while number != 0:
number = int(input(“Enter a number (0 to quit): “))
sum = sum + number
# Print the result
print(“The sum of the numbers is”, sum)
Output:
Enter a number (0 to quit): 5
Enter a number (0 to quit): 10
Enter a number (0 to quit): 15
Enter a number (0 to quit): 0
The sum of the numbers is 30
Control Structures 81
In the above program, the while loop continues to execute as long as the
value of the number is not equal to 0. The user is asked to enter a number,
and the input is converted to an integer using int(). The entered number is
then added to the sum of all previous numbers. When the user enters 0, the
loop terminates, and the final result is printed.
This loop will print “Hello, World!” indefinitely because the condition True
is always True.This loop will keep printing the message “Hello, World!” until
the program is interrupted. To interrupt the program, you can use CTRL + C
in the terminal or CTRL + Break in the IDLE editor.
It is important to be careful when using while loops, as infinite loops can
cause your program to crash or become unresponsive. To avoid infinite loops,
make sure that the condition of the loop can eventually become False, or use
a break statement to exit the loop when a certain condition is met.
i=0
while True:
print(i)
i += 1
if i == 10:
break
In this example, the break statement causes the loop to exit when i becomes
10, preventing the loop from running indefinitely. The output will be the
numbers 0 through 9.
the loop completed normally (i.e., if the loop was not exited prematurely by
a break statement). Here is an example of using an else clause with a while
loop in Python:
Code 4.11 A Program to demonstrate the use of else clause with a while
loop.
i=0
while i < 10:
print(i)
i += 1
else:
print(“Done!”)
In this example, the while loop will print the numbers 0 through 9, and then
the else clause will be executed, printing “Done!”. If the while loop is exited
prematurely by a break statement, the else clause will not be executed. For
example
i=0
while True:
print(i)
i += 1
if i == 5:
break
else:
print(“Done!”)
In this example, the while loop will print the numbers 0 through 4, and then
exit when i becomes 5. The else clause will not be executed.
The else clause of a while loop can be useful for executing clean-up code or
for handling cases where the loop did not execute at all (e.g., if the loop’s
condition was False from the start).
This for loop will print the numbers 1 and 2, and then exit when it encounters
the number 3.
for i in [1, 2, 3, 4, 5]:
if i % 2 == 0:
continue
print(i)
This for loop will print the odd numbers 1, 3, and 5, because the continue
statement causes the loop to skip the remainder of the current iteration when
i is even.
Code 4.13 A Program to print sum of all the numbers given in a list.
numbers = [1, 2, 3, 4, 5]
sum = 0
for num in numbers:
sum += num
print(“Sum of all numbers:”, sum)
84 Python Programming: A Step-by-Step Guide to Learning the Language
The range() function is often used with a for loop to repeat a block of code
a specific number of times. For example:
for i in range(5):
print(“Hello, World!”)
Note that the range() function returns a sequence of numbers, but does not
actually create a list. To create a list from a range(), you can use the list()
function.
numbers = list(range(10))
print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In this example, the for loop will print the numbers 1 and 2, and then exit
when it encounters the number 3. The else clause will not be executed.
The else clause of a for loop can be useful for executing clean-up code or
for handling cases where the loop did not execute at all (e.g., if the iterable
object is empty).
86 Python Programming: A Step-by-Step Guide to Learning the Language
The inner loop (the for loop with the variable j) will be executed completely
for each iteration of the outer loop (the for loop with the variable i).
It is also possible to use a break statement inside a nested loop to exit both the
inner loop and the outer loop, or a continue statement to skip the remainder
of the current iteration of the inner loop and move on to the next one
for i in range(1, 4):
for j in range(1, 4):
if j == 2:
break
print(i, j)
Control Structures 87
loop, the loop is immediately terminated, and the program execution moves
to the next statement after the loop. Here is an example of using a break
statement in a for loop in Python:
Code 4.17 break statement in python
for i in range(10):
if i == 5:
break
print(i)
This for loop will print the numbers 0 through 4, and then exit when i
becomes 5. The output will be:
0
1
2
3
4
It is also possible to use a break statement inside a while loop:
i=0
while True:
print(i)
i += 1
if i == 5:
break
This while loop will print the numbers 0 through 4, and then exit when i
becomes 5. The output will be:
0
1
2
3
4
Control Structures 89
i=0
while i < 10:
i += 1
pass
In both of these examples, the loop will iterate the specified number of times,
but no action will be taken in the loop body.
The pass statement is often used as a placeholder while writing code,
allowing you to get the basic structure of a program in place before adding
more detailed code. It is also used in code blocks where the syntax requires
a statement, but no action is needed.
4.4 Summary
In this chapter, we learned about the control structures available in Python.
These include decision-making statements such as “if,” “if else,” and “elif,”
as well as looping constructs like “while” and “for.” We also covered
features like “while loop with else” and “for loop with else,” as well as
the “range()” function. Additionally, we discussed control statements like
“break,” “continue,” and “pass,” and provided flow diagrams for each control
structure.
Control Structures 91
Review Questions
1. What are control structures in Python and why are they used?
2. Can you explain the syntax and use of the Python if statement?
3. How does the if-else statement work in Python?
4. Can you provide an example of an if-elif-else statement in Python?
5. How does the while loop work in Python?
6. What is the for loop in Python and how is it used?
7. Can you give an example of an infinite loop in Python?
8. What is the purpose of the break statement in Python?
9. Can you explain the continue statement in Python and when to use it?
10. What is the function of the pass statement in Python control structures?
11. Which of the following statements is true about control structures in
Python?
(a) They are used to control the flow of program execution
(b) They are used to define the structure of the program
(c) They are used to declare variables and functions
(d) They are used to print output to the console
12. What is the syntax of the Python if statement?
(a) if condition { statements }
(b) if { condition } ( statements )
(c) if ( condition ) { statements }
(d) if condition : statements
5
Python Native
Data Types
Highlights
l Python native data types
l Number
l List, Tuple, Set, Dictionary
l Strings
In Python, there are several built-in data types that can be used to store
and manipulate data. These native data types include
1. Numbers: Python has two main number types, integers, and floating-
point numbers. Integers are whole numbers, while floating-point
numbers are numbers with decimal points.
2. Strings: Strings are sequences of characters, and they can be defined
using single or double quotes.
3. Lists: Lists are ordered sequences of objects, and they are defined
using square brackets. Lists are mutable, meaning that their elements
can be changed.
4. Tuples: Tuples are similar to lists, but they are immutable, meaning
that their elements cannot be modified once created. Tuples are
defined using parentheses.
5. Dictionaries: Dictionaries are unordered collections of key-value
pairs, and they are defined using curly braces.
94 Python Programming: A Step-by-Step Guide to Learning the Language
6. Sets: Sets are unordered collections of unique elements, and they are
defined using curly braces.
7. Booleans: Booleans are used to represent the values True and False.
In addition to these native data types, Python also has several additional data
types available in its standard library, such as arrays and collections.
5.1 Numbers
In Python, there are several types of numbers that you can use in your code.
These include:
1. int (short for “integer”): These are whole numbers, such as 1, 2, 3, 4,
etc. They can be positive, negative, or zero.
2. float (short for “floating point”): These are numbers with a decimal
point, such as 3.14, 2.71828, etc. They can also be positive, negative, or
zero.
3. complex: These are complex numbers, which are numbers with both a
real and imaginary component. The real component is a float and the
imaginary component is a float multiplied by the imaginary unit j. For
example, the complex number 3 + 2j has a real component of 3 and an
imaginary component of 2.
In addition to these basic number types, Python also has a few additional types
that are used for representing numbers in specific contexts. For example, the
decimal module provides support for arbitrary-precision decimal arithmetic,
and the fractions module provides support for rational number arithmetic.
You can perform various operations on numbers in Python, such as addition,
subtraction, multiplication, division, etc. For example
x = 3 # x is an int
y = 2.5 # y is a float
z = x + y # z is a float
You can also use the built-in abs() function to get the absolute value of a
number, the pow() function to raise a number to a power, and the round()
function to round a number to a specified number of decimal places.
You can convert a number to a complex type by using the complex() function.
You can pass in two arguments to the function, the real part, and the imaginary
part, separated by a + or - sign. For example
x=3
y=4
z = complex(x, y) # z is now a complex number with the value 3+4j
It’s also possible to convert a string representation of a number to a number
type using the int(), float(), and complex() functions. For example
x = “3.14”
y = float(x) # y is now a float with the value 3.14
Function Description
Returns the smallest integer greater than or equal
math.ceil(x)
to x
math.floor(x) Returns the largest integer less than or equal to x
math.exp(x) Returns e raised to the power of x
Returns the logarithm of x to the specified base
math.log(x, base)
(default is e)
math.log2(x) Returns the base-2 logarithm of x
math.log10(x) Returns the base-10 logarithm of x
math.pow(x, y) Returns x raised to the power of y
96 Python Programming: A Step-by-Step Guide to Learning the Language
Function Description
math.sqrt(x) Returns the square root of x
math.acos(x), math.asin(x), math. Returns the arc cosine, arc sine, arc tangent of x,
atan(x) respectively.
math.cos(x), math.sin(x), math.
Returns the cosine, sine, tangent of x, respectively.
tan(x)
math.degrees(x) Converts an angle from radians to degrees
math.radians(x) Converts an angle from degrees to radians
# Built-in functions
print(abs(-5)) # Absolute value
print(pow(2, 3)) # Raise to a power
print(round(3.14159)) # Round to nearest integer
This program starts by importing the math library, which provides additional
mathematical functions not included in the built-in functions. The program
then demonstrates some of the built-in functions, such as abs(), which returns
Python Native Data Types 97
Function Description
math.sin(x) Returns the sine of x radians.
math.cos(x) Returns the cosine of x radians.
math.tan(x) Returns the tangent of x radians.
math.asin(x) Returns the arc sine of x, in radians.
math.acos(x) Returns the arc cosine of x, in radians.
math.atan(x) Returns the arc tangent of x, in radians.
math.atan2(y, x) Returns the arc tangent of y/x, in radians.
math.sinh(x) Returns the hyperbolic sine of x.
math.cosh(x) Returns the hyperbolic cosine of x.
math.tanh(x) Returns the hyperbolic tangent of x.
math.asinh(x) Returns the inverse hyperbolic sine of x.
math.acosh(x) Returns the inverse hyperbolic cosine of x.
math.atanh(x) Returns the inverse hyperbolic tangent of x.
Here is an example of how you can use these functions in a Python script to
compute the sine, cosine, and tangent of 30 degrees:
98 Python Programming: A Step-by-Step Guide to Learning the Language
You can also use trigonometric functions in numpy. Here in code 5.3 is the
example of numpy:
Code 5.3 Illustration of trigonometric functions in numpy
import numpy as np
Function Description
random.random() Returns a random float between 0 and 1.
Returns a random integer between a and b
random.randint(a, b)
(inclusive).
Returns a randomly selected element from
random.randrange(start, stop, step)
range(start, stop, step)
random.uniform(a, b) Returns a random float between a and b.
Return a random float in the range [low, high]
where the mode argument defaults to the
random.triangular(low, high, mode)
midpoint between the bounds, giving a symmetric
distribution.
Selects a random element from a non-empty
random.choice(sequence)
sequence.
Select k random elements from a given
random.choices(population, k=1)
population with replacement
Select k unique random elements from a given
random.sample(population, k)
population without replacement
random.shuffle(sequence) Shuffles elements in a sequence in place.
Here’s an example of how you can use some of these functions to generate
random numbers:
Code 5.4: Illustration to random numbers
import random
# Generate a random float between 0 and 1
print(random.random())
# Generate a random integer between 1 and 10
print(random.randint(1, 10))
# Generate a random float between 2 and 4
print(random.uniform(2, 4))
100 Python Programming: A Step-by-Step Guide to Learning the Language
Constant Value
math.pi The mathematical constant pi (3.14159...)
math.e The mathematical constant e (2.71828...)
math.inf A positive infinity value
math.nan A not-a-number value
math.tau tau (2*pi) constant
Here’s an example of how you can use these constants in a Python script:
Code 5.5: Illustration of python script
import math
# Compute the area of a circle with radius 2
radius = 2
area = math.pi * (radius ** 2)
print(“Area of circle with radius 2:”, area)
# Compute the value of e^2
e_squared = math.e ** 2
print(“e^2:”, e_squared)
# Compute the value of tau
tau_val = math.tau
print(“tau:”,tau_val)
Python Native Data Types 101
1
2
3
4
5
You can also use while loop:
Code 5.7: Program to print element of a list using while loop.
my_list = [1, 2, 3, 4, 5]
i=0
while i < len(my_list):
print(my_list[i])
i += 1
5.2.2.1 Indexing
In Python, indexing is used to access elements of a data structure, such as a
list or string, by specifying a numerical position or index. The first element
in a data structure has an index of 0, the second element has an index of 1,
and so on. For example, to access the first element in a list called “mylist”,
you would use the code 5.9:
mylist[0]
You can also use slicing to access a range of elements in a data structure. The
syntax for slicing is as follows:
mylist[start:end]
This will return a new list containing all elements from the start index
(inclusive) to the end index (exclusive).
Python Native Data Types 103
This will also print the elements of the nested list in order: 1, 2, 3, 4, 5, 6,
7, 8, 9.
Positive Indexing
0 1 2 3 4 5 6 7 8 9
H E L L O W O R L D
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2
Negative Indexing
For example, to access the last element in “mylist”, you would use the code:
mylist[-1]
Here is an example of using negative indexing to access the last element of
a list:
Code 5.11: To access element from a list using negative indexing.
mylist = [1, 2, 3, 4, 5]
print(mylist[-1]) # Output: 5
5.2.2.4 Slicing
In Python, “slicing” is a way to extract a portion of a sequence (e.g. a string,
list, or tuple) by specifying two indices, a start index and an end index,
separated by a colon. The slice will include all elements from the start index
up to, but not including, the end index. For example, if we have a list called
my_list, we can extract the second through fourth elements as shown in code
5.14 :
sub_list = my_list[1:4]
This will create a new list called sub_list that contains the elements at index
1, 2, and 3 of my_list. Negative indexing can also be used.
You can also specify a step with the slicing, like my_list[start:end:step]
Start: by default starts from 0 index.
End: last index of the element in the given range.
Step: to increment or decrement in list by given steps.
Also, you can slice a string using a similar approach.
sub_string = my_string[1:4]
This will create a new string called sub_string that contains the characters at
index 1, 2, and 3 of my_string.
my_list.extend([1, 2, 3])
Using the + operator: This operator can be used to concatenate two or more
lists. For example:
new_list = my_list + [4, 5, 6]
Using the * operator: This operator can be used to duplicate a list a certain
number of times. For example:
new_list = my_list * 3
Note that all of these methods except the assignment operator will modify the
original list, while the assignment operator creates a new list.
Modifies
Method Description Returns
Original List
Adds an element to the end of
append(element) Yes None
the list
Adds all the elements from an
extend(iterable) Yes None
iterable to the end of the list
insert(index, Inserts an element at a specific
Yes None
element) index in the list
Removes the first occurrence
remove(element) of the specified element from Yes None
the list
The
Removes and returns the
pop(index) Yes removed
element at the specified index
element
Returns the index of the first
The index of
index(element) occurrence of the specified No
the element
element in the list
Returns the number of times
The count of
count(element) the specified element appears No
the element
in the list
Sorts the elements of the list in
sort() Yes None
ascending order
Python Native Data Types 107
Modifies
Method Description Returns
Original List
Reverses the order of the
reverse() Yes None
elements in the list
Removes all elements from the
clear() Yes None
list
Returns a shallow copy of the
copy() No A new list
list
deepcopy() Returns a deep copy of the list No A new list
Returns the number of elements The length
len() No
in the list of the list
The
Returns the smallest element in
min() No minimum
the list
element
The
Returns the largest element in
max() No maximum
the list
element
Returns the sum of all elements The sum of
sum() No
in the list the elements
List comprehension can be a useful tool when you need to create a new list
based on some existing data or logic. It allows you to write more readable
and efficient code, as it eliminates the need for explicit loops and temporary
variables.
Note that list comprehension is not always the best choice, if the comprehension
becomes too complex it might be better to use a for loop.
You can also use not in to test if an element is not present in a list:
print(6 not in my_list) # True
You can also use any() function with a generator expression to check if any
of the elements in the list satisfy a certain condition.
numbers = [1,2,3,4,5,6]
result = any(x>4 for x in numbers)
print(result) # True
You can also use all() functions with a generator expression to check if all of
the elements in the list satisfy a certain condition.
result = all(x>0 for x in numbers)
print(result) # True
Keep in mind that the membership test is generally faster for lists than for
other iterable types, like sets or tuples, because lists are ordered and have a
specific index for each element.
Also, if you are trying to find out the existence of elements in a large list,
using sets is more efficient than using lists.
You can also create a tuple without using parentheses by using a trailing
comma. For example:
# Creating a tuple with one element
my_tuple3 = “apple”,
It’s also possible to create a tuple from a list or another iterable using the
tuple() function:
Code.5.20: Illustration of tuple from list
# Creating a tuple from a list
my_list = [1, 2, 3]
my_tuple4 = tuple(my_list)
# Creating a tuple from a string
my_string = “hello”
my_tuple5 = tuple(my_string)
You can also use the * operator to unpack the elements of an iterable into a
new tuple. As shown in Code 5.21 below:
# Unpacking elements of a list into a tuple
my_list = [1, 2, 3]
my_tuple6 = *my_list
Python Native Data Types 111
As you can see, creating a tuple in Python is quite simple and straightforward.
The key thing to remember is that tuples are collections of ordered and
immutable elements, and are defined using parentheses and separated by
commas.
Now the variable a will contain the value 1, b will contain the value 2, and
c will contain the value 3.
You can also use the tuple unpacking feature in a for loop to iterate through
the elements of the tuple:
Code 5.22: Illustration of unpacking tuple
my_tuple = (1, 2, 3)
for element in my_tuple:
print(element)
This will output:
1
2
3
You can also use * operator to unpack remaining items in the tuple:
a, *b = (1, 2, 3, 4, 5)
Now, a=1, b=[2, 3, 4, 5]
my_tuple = (1, 2, 3)
for element in my_tuple:
print(element)
2. Using the tuple() function: The tuple() function allows you to access
the elements of a tuple by index. For example:
my_tuple = (1, 2, 3)
for i in range(len(my_tuple)):
print(my_tuple[i])
3. Using the enumerate() function: The enumerate() function allows you
to access both the index and the value of each element in a tuple. For
example:
my_tuple = (1, 2, 3)
for index, value in enumerate(my_tuple):
print(index, value)
4. Using list comprehension :
my_tuple = (1, 2, 3)
[print(i) for i in my_tuple]
Note that, Tuple are immutable so you can not change any element of tuple,
but you can traverse it.
5.3.3.1 Indexing
In Python, indexing refers to the process of accessing individual elements
of a data structure, such as a list, tuple, or string. These data structures are
indexed using square brackets [], with the index starting at 0 for the first
element. For example, if you have a list of numbers called “numbers” and
you want to access the first element, you would use the following syntax:
numbers[0]
Python Native Data Types 113
It’s important to note that both these methods create a new tuple and reassign
it to the same variable, but the original tuple remains unchanged.
Method Description
count() Returns the number of occurrences of a specific element in the tuple
index() Returns the index of the first occurrence of a specific element in the
tuple
len() Returns the number of elements in the tuple
tuple() Returns a tuple version of an iterable object
Note that this is not an exhaustive list of tuple methods, there are more
methods that can be used with tuples like max(), min(), sorted() etc. You can
check the python documentation for more details.
116 Python Programming: A Step-by-Step Guide to Learning the Language
Function Description
all() Returns True if all elements in the tuple are true, False otherwise
Returns True if at least one element in the tuple is true, False
any()
otherwise
Returns an enumerate object that contains the index and value of
enumerate()
each element in the tuple
Returns an iterator from elements of an iterable for which a function
filter()
returns true
len() Returns the number of elements in the tuple
max() Returns the largest element in the tuple
min() Returns the smallest element in the tuple
sorted() Returns a new sorted list from elements in the tuple
Please note that this is not an exhaustive list of tuple functions, there are
more functions that can be used with tuples like zip(), map(), reduce() etc.
You can check the python documentation for more details.
6. Iterable: Tuples are iterable which means you can iterate over the
elements of a tuple using a for loop.
7. Return multiple values: Tuples can be used to return multiple values
from a function, which is more efficient than using a data structure like
a list or dictionary.
Sets are unordered, which means that the elements in a set have no specific
order. Sets are also mutable, which means that you can add, remove, and
update elements in a set after it is created. For example, you can use the
add() method to add an element to a set, the remove() method to remove an
element from a set, and the update() method to add multiple elements to a
set at once.
Sets also support mathematical set operations like union, intersection and
difference.
Code 5.27: Illustration of union, intersection and difference
# Define two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
# Intersection
print(set1.intersection(set2)) # Output: {3}
# Difference
print(set1.difference(set2)) # Output: {1, 2}
118 Python Programming: A Step-by-Step Guide to Learning the Language
It’s important to note that sets do not allow duplicate values, if you try to add
a duplicate value to a set, it will be ignored.
You can also create a set from a list or other iterable by passing it as an
argument to the set() function as given in code 5.36:
my_list = [1, 2, 3]
my_set = set(my_list)
This will not raise any error, as 4 is not in the set my_set
5. Subset: To check if a set is a subset of another set, you can use the <=
operator or the issubset() method.
5. Superset: To check if a set is a superset of another set, you can use the
>= operator or the issuperset() method.
It’s worth noting that all these set operations return a new set and the original
sets remain unchanged.
Code 5.42:
A = {1, 2, 3}
B = {2, 3, 4}
C = A.difference(B) # C = {1}
D = A - B # D = {1}
Both A.difference(B) and A - B will return a new set that contains the elements
that exist in set A but not in set B.
It’s also worth mentioning Symmetric difference, it can be found using the
symmetric_difference() method or the ^ operator. It returns a set of elements
that is in either of the sets but not in both.
A = {1, 2, 3}
B = {2, 3, 4}
C = A.symmetric_difference(B) # C = {1, 4}
D = A ^ B # D = {1, 4}
Both the symmetric_difference() method and the “^” operator will return a
new set containing the symmetric difference of the two sets.
122 Python Programming: A Step-by-Step Guide to Learning the Language
Additionally, there are some other in-built methods available like len(), min(),
max() etc.
You can use these methods to perform various operations on sets in Python.
It’s also worth noting that python set has also support of set comprehension,
which allows you to create a new set using a single line of code.
Frozen sets are useful in situations where you need a set that can be used as
a key in a dictionary, or as an element in another set, but you don’t want the
set to be modified.
You can also use the get() method to access a value. This method takes a key
as an argument and returns the value for that key if it exists in the dictionary,
otherwise it returns None (or a default value if specified). For example:
my_value = my_dict.get(“name”)
print(my_value) # Output: “John”
If you want to check if a key is present in the dictionary or not, you can use
the in keyword. For example:
if “name” in my_dict:
print(“name key found”)
else:
print(“name key not found”)
my_dict[“address”] = “NYC”
print(my_dict) # Output: {“name”: “Bob”, “age”: 25, “gender”: “male”,
“address”: “NYC”}
It will add the key “address” to the dictionary with value “NYC”
Python Native Data Types 127
Method Description
dict.fromkeys(seq[, Returns a new dictionary with keys from the given sequence and
value]) all values set to the given value (defaults to None).
Returns the value for key if key is in the dictionary, else default. If
dict.get(key[,
default is not given, it defaults to None, so that this method never
default])
raises a KeyError.
Returns a view object that displays a list of dictionary’s (key,
dict.items()
value) tuple pairs.
Returns a view object that displays a list of all the keys in the
dict.keys()
dictionary.
Removes and returns the value for key if key is in the dictionary,
dict.pop(key[,
else default. If default is not given and key is not in the dictionary,
default])
a KeyError is raised.
Remove and return an arbitrary (key, value) item pair from the
dict.popitem() dictionary. If the dictionary is empty, calling popitem() raises a
KeyError.
dict.
If the key is in the dictionary, return its value. If not, insert a key
setdefault(key[,
with a value of default and return default. default defaults to None.
default])
Update the dictionary with the key/value pairs from other,
overwriting existing keys. If other is a dictionary, the key/value
pairs are added to the dictionary. If other is an iterable of key/
dict.update([other])
value pairs, the pairs are added to the dictionary. If other is a
mapping, the mapping’s keys must be new-style strings to be
accepted as keys.
Returns a view object that displays a list of all the values in the
dict.values()
dictionary.
Function Description
Returns an enumerate object. iterable must be a
sequence, an iterator, or objects supporting the
iteration protocol. The start parameter defaults to 0.
enumerate(iterable, start=0)
The enumerate object yields pairs containing a count
(from start which defaults to 0) and a value yielded by
the iterable argument.
Return True if all elements of the iterable are true. If
the iterable is empty, return True. Equivalent to: def
all(iterable)
all(iterable): for element in iterable: if not element:
return False return True
Return True if any element of the iterable is true. If
the iterable is empty, return False. Equivalent to: def
any(iterable)
any(iterable): for element in iterable: if element: return
True return False
Method Description
Returns a copy of the string with its first character
str.capitalize()
capitalized and the rest lowercase.
str.upper() Returns a copy of the string in uppercase.
str.lower() Returns a copy of the string in lowercase.
Returns the number of non-overlapping occurrences of
str.count(sub[, start[,
substring sub in the range [start, end]. Optional arguments
end]])
start and end are interpreted as in slice notation.
Returns the lowest index in the string where substring sub
is found within the slice s[start:end]. Optional arguments
str.find(sub[, start[, end]])
start and end are interpreted as in slice notation. Return -1
if sub is not found.
Returns a copy of the string with all occurrences of substring
str.replace(old, new[,
old replaced by new. If the optional argument count is
count])
given, only the first count occurrences are replaced.
Returns a list of the words in the string, using sep as the
delimiter string. If maxsplit is given, at most maxsplit splits
str.split([sep[, maxsplit]])
are done. If maxsplit is not specified or -1, then there is no
limit on the number of splits.
Python Native Data Types 131
Method Description
Use to concatenate any number of strings. All the strings
str.join(iterable) have to be joined using the string on which this method is
called.
Returns a copy of the string with leading and trailing
str.strip([chars]) characters removed. If chars is not specified, it defaults to
removing whitespace.
Returns a copy of the string with leading characters
str.lstrip([chars]) removed. If chars is not specified, it defaults to removing
whitespace.
Returns a copy of the string with trailing characters
str.rstrip([chars]) removed. If chars is not specified, it defaults to removing
whitespace.
Return true if all characters in the string are alphabetic and
str.isalpha()
there is at least one character, false otherwise.
Return true if all characters in the string are alphanumeric
str.isalnum()
and there is at least one character, false otherwise.
This program creates five strings using different methods, first two by using
single and double quotes, next two by using str() function , one by using
string literals and last two by using bytes and bytes.
# Using slicing
print(s[2:5]) # llo
Python Native Data Types 133
# Repetition
s4 = “Python “
s5 = s4 * 3
print(s5) # “Python Python Python “
# Comparison
s6 = “Python”
s7 = “python”
print(s6 == s7) # False
print(s6 != s7) # True
print(s6 > s7) # True
print(s6 < s7) # False
In the above program the first example shows the concatenation of two strings
using + operator. The second example shows the repetition of a string using
* operator. The third example shows the comparison of two strings using
comparison operators like ==, !=, >, <, >=, and <=. The last example shows
the use of join method to join multiple strings with a specified delimiter. You
can use these string operations to perform various tasks such as formatting
text, generating text output, and manipulating strings in your Python programs.
5.6.4.1 Concatenation
String concatenation is the process of joining two or more strings together to
form a new string. In Python, there are several ways to concatenate strings,
such as using the + operator, the += operator, the join() method or the f-strings.
Here is a single Python program that demonstrates some of these methods:
# Using the + operator
s1 = “Hello”
s2 = “World”
s3 = s1 + “ “ + s2
print(s3) # “Hello World”
# Using f-strings
name = “John”
age = 30
s6 = f”My name is {name} and I am {age} years old”
print(s6) # “My name is John and I am 30 years old”
Python Native Data Types 137
The first method uses the + operator to concatenate two strings. The second
method uses the += operator to concatenate strings. The third method uses
the join() method to join a list of strings with a specified delimiter. The last
method uses f-strings, which were introduced in Python 3.6 and allow you to
embed expressions inside string literals using {}.
The first example uses a for loop to iterate over the characters of a string. The
second example uses a while loop to iterate over the characters of a string,
138 Python Programming: A Step-by-Step Guide to Learning the Language
using the string’s length to determine when to stop the loop. The last example
uses the in and not in operators to check if a specific character is present in
the string. The in operator returns True if the character is found in the string,
False otherwise. The not in operator returns True if the character is not found
in the string and False otherwise.
# Using f-strings
name = “John”
age = 30
s = f”My name is {name} and I am {age} years old”
print(s) # “My name is John and I am 30 years old”
The first method uses the format() method to insert values into a string
by defining placeholders in the string and then providing the values to be
Python Native Data Types 139
inserted. The second method uses f-strings, which were introduced in Python
3.6 and allow you to embed expressions inside string literals using {}. The
last method uses the % operator to perform string interpolation in older
version of python.
5.7 Summary
In this chapter, we covered the various native data types in Python in depth.
These data types include numbers, strings, lists, tuples, sets, and dictionaries,
and they provide different ways to store data in Python. We learned about
the characteristics and uses of each data type, as well as the methods and
functions associated with them. We also provided programming examples to
illustrate the usage of each data type and its related methods and functions.
Overall, this chapter aimed to give a comprehensive understanding of the
different data types available in Python and how they can be used to store
and manipulate data.
Review Questions
1. What are native data types in Python?
2. Can you explain the Python Number data type?
3. What is a List in Python and how is it used?
4. Can you describe the Python Tuple data type and its use?
5. How is a Set used in Python and what are its properties?
6. What is a Dictionary in Python and how is it different from a List or
Tuple?
7. Can you give an example of how to create and use a Python String?
8. How are string operations, such as concatenation and slicing, performed
in Python?
Python Native Data Types 141
9. Can you explain the difference between single and double quotes in
Python String definitions?
10. How can you format a Python String using the format() method?
11. Which of the following is a Python native data type that represents a
sequence of characters?
(a) Number
(b) List
(c) String
(d) Dictionary
12. Which of the following is a Python native data type that represents an
unordered collection of unique elements?
(a) List
(b) Tuple
(c) Set
(d) Dictionary
6
Python Functions
Highlights
l Python functions
l Types of functions
l Advantages of functions
l Python anonymous functions
l Pass by value vs. Pass by reference
l Recursion
input parameters. For example, you can define a function called “greet” that
takes in a parameter called “name” and prints out a greeting message: “Hello,
name!”. Functions can also return a value using the “return” statement, for
example, a function called “add” that takes in two parameters “a” and “b”
and returns their sum. Functions are called by their name, followed by the
parentheses and any necessary input arguments. Functions are useful for
organizing and modularizing your code, making it easier to read, understand,
and maintain. They also allow you to reuse the same code multiple times,
without having to write it over and over again.
Function Description
print() Prints or displays text or data on the screen
input() Gets input from the user
len() Gets the length of a list, string, or other data structure
type() Gets the data type of a variable or expression
int() Converts a value to an integer
float() Converts a value to a floating-point number
str() Converts a value to a string
list() Converts a value to a list
dict() Converts a value to a dictionary
tuple() Converts a value to a tuple
Characteristics Description
Definition User-defined functions are defined using the def keyword, followed
by the function name and a set of parentheses.
Parameters User-defined functions can accept zero or more input parameters,
which are specified within the parentheses.
Return value User-defined functions can return zero or one value using the
return keyword.
Scope User-defined functions have their own scope and do not affect the
global scope or other functions.
Reusability User-defined functions can be called multiple times within a program
or project, making the code more modular and reusable.
Naming User-defined functions should be given a name that describes its
functionality.
Python Functions 147
In this example, the greet() function is defined using the def keyword,
followed by the function name and a set of parentheses containing one
required argument named name. This argument is used to customize the
greeting message that is printed to the console. When the function is called
by using the function name followed by parentheses containing the required
argument, greet(“John”), the function runs and replaces the name placeholder
in the greeting message with the provided value “John” , then it prints “Hello,
John!” as a output.
Hello, John!
def add_numbers(*numbers):
result = 0
for number in numbers:
result += number
return result
result = add_numbers(1,2,3,4,5)
print(result)
In this example, the add_numbers() function is defined using the def keyword,
followed by the function name and a set of parentheses containing *numbers.
The * before the argument name numbers indicates that the function can
accept any number of positional arguments. The function then iterates over
the numbers passed as arguments, adding them together and storing the result
in a variable. Finally, the function returns the result. When the function is
called by using the function name followed by parentheses containing the
arbitrary length arguments, add_numbers(1,2,3,4,5), the function runs and
adds all the numbers passed as arguments, then it prints 15 as a output.
It’s also possible to use **kwargs to accept any number of keyword arguments,
in this case the function would look like this:
def greet(**kwargs):
print(f”Hello, {kwargs[‘name’]}!”)
greet(name=”John”)
In this example, the function is defined to accept any number of keyword
arguments using **kwargs. The function then accesses the value of the “name”
keyword argument and uses it to create a personalized greeting message.
In this example, the greet() function is defined using the def keyword,
followed by the function name and a set of parentheses containing two
arguments name and age.
When the function is called by using the function name followed by parentheses
containing the keyword-based arguments, greet(age=25, name=”John”), the
function runs and replaces the name and age placeholders in the greeting
message with the provided values “John” and 25, respectively, then it prints
“Hello, John. You are 25 years old.” as a output.
It’s also possible to specify some of the arguments as keyword arguments and
others as positional arguments, for example:
greet(“John”, age=25)
This will also run the same way and prints the same output as before.
In this example, the greet() function is defined using the def keyword,
followed by the function name and a set of parentheses containing two
arguments name and age. The age argument has a default value of 25. When
the function is called by using the function name followed by parentheses
Python Functions 153
containing the only required argument, greet(“John”), the function runs and
uses the default value of 25 for the age argument, then it prints “Hello, John.
You are 25 years old.” as a output.
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x**2, numbers)
print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]
the variable within the function will affect the original variable. For example,
if you pass a list to a function and modify the list within the function, the
original list will be modified as well.
However, when a primitive value such as an integer or string is passed to a
function, the function receives a reference to the object containing the value
rather than the value itself. This means that the function can change the
attributes of the object, but the value of the primitive can not be changed.
For example, if you pass an integer toInside the function, x is: 11
Outside the function, x is: 10
a function and change the value of the integer within the function, the
original integer will not be changed.
6.8 Recursion
In computer science, recursion is a method of solving a problem by breaking
it down into smaller, identical problems. A function that calls itself is said to
be recursive. In Python, recursion is a technique where a function calls itself
in order to solve a problem.
Recursion is a powerful problem-solving technique that can be used to solve
many types of problems, such as mathematical problems, tree traversals, and
more. The key to using recursion effectively is to find the base case, which
is the simplest version of the problem that can be solved directly, and the
recursive case, which is the problem broken down into smaller identical parts.
Here’s an example of a simple recursive function in Python:
Python Functions 157
It’s worth noting that recursion has also some drawbacks, like consuming
a lot of memory and the risk of stack overflow errors, and it might not
always be the best solution for a given problem, it’s important to consider
the complexity and performance of the algorithm before choosing recursion
as the solution.
6.10 Summary
In this chapter, we explored the concept of functions in the Python
programming language. We covered both built-in functions and user-defined
functions, providing a comprehensive list of built-in functions and detailing
the various types of user-defined functions with examples. We also delved
into the topic of anonymous functions, which are created using the lambda
function, and discussed the concepts of pass by value and pass by object
reference. Additionally, we covered the topic of recursion, which is a powerful
tool for solving certain types of problems. Finally, we discussed the scope
and lifetime of variables and how they relate to functions.
Review Questions
1. What is a function in Python?
2. How do you define a function in Python?
3. What is the difference between a built-in function and a user-defined
function in Python?
4. What is a return statement in Python functions and why is it important?
5. What is the scope of a variable defined inside a function in Python?
6. What is a default argument in Python functions and how is it used?
7. What is a lambda function in Python?
8. What is recursion in Python and how is it implemented?
9. What is a function decorator in Python?
10. How can you pass a function as an argument to another function in
Python?
160 Python Programming: A Step-by-Step Guide to Learning the Language
Python Modules
Highlights
l Python Modules
l Creating a Module
l Importing Module
l Standard Modules
l Python Packages
It’s worth noting that, python also have a mechanism of package which is a
collection of related modules. With packages, you can organize your modules
into a single namespace, making it easy to keep related modules together and
organized.
class ExampleClass:
pass
example_variable = “This is an example variable.”
You can also use the “as” keyword to give a module a different name when
importing it. For example, to import the “math” module as “m”, you would
use the following command:
import math as m
print(m.sqrt(16)) # Output: 4.0
import sys
print(sys.path)
You can also add new directories to the module search path by modifying the
sys.path variable. For example, to add a directory called my_modules to the
search path, you would use the following command:
import sys
sys.path.append(“my_modules”)
This would allow you to import modules from the my_modules directory as
if they were part of the standard library. It’s also worth noting that you can
use PYTHONPATH environment variable to specify additional directories to
be searched for modules.
It’s important to keep in mind that modifying the module search path can
make your code less portable, as the modules you import may not be available
on other systems or in other environments.
Additionally, it’s not necessary to reload a module when you are developing
and testing your code. Python interpreter automatically reloads the module
when you run the code again.
for additional installation. The Standard Library is organized into several sub-
categories, such as built-in functions, data types, files and directories, internet
and protocols, and many more.
Here is a table that provides a brief introduction to some of the most commonly
used standard modules in Python:
Module Descriptionjson
os Provides a way to interact with the operating system and perform
tasks such as navigating the file system, manipulating files and
directories, and interacting with environment variables.
sys Provides access to interpreter-specific functions and variables, such
as the command-line arguments, the interpreter’s version and build
information, and the current working directory.
math Provides mathematical functions and constants, such as trigonometric
functions, logarithmic functions, and the mathematical constant pi.
random Provides functions to generate pseudo-random numbers and perform
random sampling from different distributions.
time Provides functions to handle time, including the ability to get the current
time, sleep, and convert between different time representations.
re Provides regular expression matching operations, including functions
to search for patterns in strings, split strings based on a pattern, and
replace text based on a pattern.
json Provides functions to encode and decode JSON data.
datetime Provides classes for working with dates and times, including the
ability to perform arithmetic with dates and times, and format dates
and times as strings.
urllib Provides functions to open URLs, including functions to retrieve data
from the web, send data to the web, and handle cookies.
collections Provides alternatives to built-in types that can be more efficient in
certain cases, such as ordered dictionaries and defaultdicts.
There are many more modules available in the Standard Library, and you can
find more information about them in the Python documentation.
To use a package in your Python script, you first need to install it. The most
common way to install a package is using pip, which is a package manager for
Python. To install a package using pip, you can use the following command:
pip install package_name
Once a package is installed, you can import it into your script using the
import statement. Here’s an example of importing the NumPy package:
import numpy as np
In the above example numpy is the package name and np is the alias which
we are giving to the package so that we don’t have to write numpy everytime,
instead we can use np.
Once a package is imported, you can use its functions and methods to perform
various tasks. Here’s an example of using the NumPy package to create an
array:
Code: 7.7: Code:7.5 : Illustrate the concept of packages in python.
import numpy as np
# Create a 1-dimensional array
a = np.array([1, 2, 3, 4, 5])
# Print the array
print(a)
This will create an array with the values 1, 2, 3, 4, and 5, and print it out.
You can also import specific modules or functions from a package using the
from statement, like this:
from numpy import array
a = array([1, 2, 3, 4, 5])
7.12 Summary
In this chapter, we covered the topic of creating modules, which are a type
of user-defined function that can be reused across multiple scripts. We went
over the concept of modules, how they are defined and created, and provided
Python Modules 171
Review Questions
1. What is a module in Python?
2. How do you create a module in Python?
3. What is the syntax for importing a module in Python?
4. What is the difference between the import and from...import statements
in Python?
5. How can you access functions defined in a module in Python?
6. What is the purpose of a name variable in a Python module?
7. What are standard modules in Python and how are they useful?
8. What is a package in Python?
9. How do you create a package in Python?
10. What is the difference between a module and a package in Python?
11. Which of the following statements is true about importing modules in
Python?
(a) You can only import one module at a time using the import statement
(b) You can import multiple modules at once using the from...import
statement
(c) You can import a module and its functions using the as keyword
(d) You can only import built-in modules in Python
12. Which of the following is not a standard module in Python?
(a) os
(b) sys
(c) random
(d) mathplotlib
8
Exception Handling
Highlights
l Python Exception
l Python Built-in Exceptions
l Exception Handling
l Python User-Defined Exceptions
8.1 Exception
In Python, an exception is an event that occurs during the execution
of a program that disrupts the normal flow of instructions. Exceptions
are typically caused by errors in the program, such as division by zero,
174 Python Programming: A Step-by-Step Guide to Learning the Language
Exception Cause
AssertionError Raised when an assert statement fails.
AttributeError Raised when an attribute reference or assignment fails.
EOFError Raised when the input() function hits an end-of-file
condition (EOF) without reading any data.
FileNotFoundError Raised when a file or directory is requested but doesn’t
exist.
FloatingPointError Raised when a floating point operation fails.
ImportError Raised when an import statement fails to find the module
definition or when a from...import statement fails to find a
name that is to be imported.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when a key is not found in a dictionary.
NameError Raised when a variable is not found in the local or global
namespace.
TypeError Raised when an operation or function is applied to an
object of an inappropriate type.
ValueError Raised when a built-in operation or function receives an
argument that has the right type but an inappropriate
value.
ZeroDivisionError Raised when the second operand of a division or modulo
operation is zero.
Exception Handling 175
In this example, the try block contains a division operation that may raise a
ZeroDivisionError exception, and the except block contains a message that
will be printed if the exception is raised.
176 Python Programming: A Step-by-Step Guide to Learning the Language
You can also use the finally block which contains code that will be executed
regardless of whether an exception was raised or not. And else block which
will be executed if no exception is raised in the try block.
It’s also possible to use raise statement to raise an exception.
if x < 0:
raise ValueError(“x should be positive.”)
You can also handle multiple exceptions by using multiple except blocks.If
the type of exception doesn’t match any of the except blocks, it will remain
unhandled and the program will terminate.
For example:
try:
x=10
y=0
print (x/y)
except TypeError:
print(‘Unsupported operation’)
except ZeroDivisionError:
print (‘Cannot divide by zero’)
Exception Handling 177
Result:
Cannot divide by zero
The else block contain the code that will execute when there is no exception
in try block. The except block is executed if the exception occurs inside the
try block, otherwise the else block gets processed if the try block is found to
be exception free.
Code 8.2: Illustrate the use of try except and else.
try:
x=20
y=10
z= x/y
print (z)
except ZeroDivisionError:
print (‘Cannot divide by zero’)
else:
print(‘The result of division of x and y is’,z)
Output:
2.0
The result of division of x and y is 2.0
The finally block contains code that will be executed regardless of whether
an exception was raised or not. The code in this block is guaranteed to be
executed, even if an exception is raised in the try block or not.
Code 8.3: A program to demonstrate the use of finally keyword.
try:
x=1/0
except ZeroDivisionError:
print(“Cannot divide by zero.”)
finally:
print(“This block will always be executed.”)
It’s often used to release resources like file handlers, network connections,
etc.
178 Python Programming: A Step-by-Step Guide to Learning the Language
In summary, the try block contains the code that may raise an exception, the
except block contains the code that will be executed if an exception is raised
and the finally block contains code that will always be executed regardless of
whether an exception was raised or not.
In this example, the try block contains a conversion operation that may raise a
ValueError or TypeError exception, and the except block contains a message
that will be printed if either of those exceptions is raised. You can also use
the as keyword to assign the raised exception to a variable.
try:
x=1/0
except ZeroDivisionError as e:
print(“Cannot divide by zero. Reason: “, e)
8.3.3 try….finally
In Python, the try and finally statements are used to handle exceptions (i.e.
run-time errors) in a controlled way. The try block contains the code that may
raise an exception, and the finally block contains code that will always be
executed, whether an exception is raised or not.
Here’s an example of how to use the try and finally statements in a program:
try:
# code that may raise an exception
x=1/0
except ZeroDivisionError:
# code to handle the exception
print(“Cannot divide by zero!”)
finally:
# code that will always be executed
print(“The ‘try’ block has finished executing.”)
In the above code, the try block contains the code x = 1 / 0, which raises a
ZeroDivisionError exception because it is attempting to divide by zero. The
except block then catches the exception and prints a message to the user.
The finally block then runs and prints another message, indicating that the
try block has finished executing. It is important to note that the finally block
will always be executed, even if there is a return statement or an unhandled
exception in the try block.
Code 8.4: Illustrating the use of raise keyword in user defined exception.
class CustomException(Exception):
def __init__(self, message):
self.message = message
raise CustomException(“This is a custom exception.”)
In the above code, we create a new class called CustomException that inherits
from the built-in Exception class. We also define an __init__ method that
takes a message as an argument, which allows us to specify a custom error
message when we raise the exception.
Here’s an example of how you might use the custom exception in a program:
Code 8.5: A program to validate the age.
class InvalidAgeError(Exception):
pass
def validate_age(age):
if age < 0:
raise InvalidAgeError(“Age cannot be negative.”)
elif age > 150:
raise InvalidAgeError(“Age cannot be greater than 150.”)
else:
print(“Age is valid.”)
try:
validate_age(-5)
except InvalidAgeError as e:
print(e)
8.5 Summary
In this chapter, we covered the topics of interpreting time errors (syntax errors)
and run-time errors, also known as exceptions. Python has a variety of built-
in exceptions that can be used to handle different situations that may arise
during the execution of a program. Additionally, users have the capability
to create their own custom exceptions to handle specific circumstances. We
discussed the use of the try, except, and finally constructs, providing examples
to illustrate their use. Furthermore, we explained how to create user-defined
exceptions and provided an example to demonstrate its usage.
Review Questions
1. What is an exception in Python?
2. How do you handle exceptions in Python?
3. What is the purpose of the try...except statement in Python?
4. What is the syntax for raising an exception in Python?
5. What is a built-in exception in Python and how is it used?
6. What is the difference between an error and an exception in Python?
7. What is a traceback in Python and how can it be used?
8. What is a user-defined exception in Python and how is it created?
8. What is the purpose of the finally clause in a try...except statement in
Python?
9. What is the purpose of the assert statement in Python?
10. Which of the following is not a built-in exception in Python?
(a) ZeroDivisionError
(b) IndexError
(c) UserWarning
(d) ImportError
11. Which of the following is true about exception handling in Python?
(a) The try...except statement can qhandle any type of exception
(b) The finally clause is optional in a try...except statement
(c) User-defined exceptions cannot be raised in Python
(d) The raise statement is used to handle exceptions in Python
9
Highlights
l Operations on Files
l write() and read() Methods
l Python File Methods
l Renaming and Deleting Files
l Directories in Python
Python provides several ways to work with files, including the built-
in open() function, which allows you to read, write and manipulate
files in various modes (e.g. read-only, write-only, and read-write). The
open() function returns a file object, which you can use to perform
various operations on the file, such as reading or writing its contents.
Additionally, the os and shutil modules provide additional functionality
for working with files and directories, such as creating, renaming, and
deleting files and directories, and navigating the file system.
2. Writing to a file: You can use the write() method of a file object to write
a string to a file. If you want to add new content to an existing file, you
can open the file in “append” mode.
3. Updating a file: You can use the seek() method of a file object to move
the file pointer to a specific position in the file, and then use the write()
method to overwrite the contents of the file at that position.
4. Closing a file: Once you have finished working with a file, you should
close it using the close() method of the file object.
5. Renaming and deleting a file: Python provides functions like
os.rename(), os.remove() etc. which can be used to rename and delete
files.
6. File handling can also be done using context manager with the help of
“with” statement, this will automatically close the file when the block of
code is exited.
7. Iterating through the file: The for loop can be used to iterate through
the lines of a file.
8. Copying a file: shutil.copy2() function can be used to copy a file from
one location to another, while preserving the metadata of the original
file.
9. Moving a file: shutil.move() can be used to move a file from one location
to another.
These are just a few examples of the many operations you can perform on
files in Python. The os and shutil modules provide additional functionality for
working with files and directories, such as creating, renaming, and deleting
files and directories, and navigating the file system.
It is important to note that the file you are trying to open should exist in
the directory from where the python script is running otherwise it will raise
FileNotFoundError.
Mode Description
‘r’ Open text file for reading. (default)
‘w’ Open the file for writing. Creates the file if it does not exist or truncates the
file if it exists.
‘x’ Open the file for exclusive creation. If the file already exists, raises a
FileExistsError.
‘a’ Open the file for writing. Creates the file if it does not exist. The pointer is
placed at the end of the file. If the file exists, data is appended.
186 Python Programming: A Step-by-Step Guide to Learning the Language
Mode Description
‘b’ Binary mode
‘t’ Text mode (default)
You can also use these modes in combination, for example ‘rb’ f or reading
a binary file or ‘w+’ for both reading and writing.
If you don’t specify the encoding when opening a file, Python will try to
detect the encoding automatically using a library called chardet. However,
this method may not always be reliable, so it’s a good practice to specify the
encoding explicitly.
You can also use the io module to open a file with a specific encoding.
import io
with io.open(“example.txt”, “r”, encoding=”utf-8”) as f:
content = f.read()
It is important to note that if you are working with non-English text, you
should always specify the encoding of the file to ensure that the text is
displayed correctly.
The file will be closed automatically when the block of code indented under
the with statement is finished executing. It is worth noting that the file
object returned by the open() function also has a __exit__() method which is
called when the block of code indented under the with statement is finished
executing, the __exit__() method will then call the close() method.
188 Python Programming: A Step-by-Step Guide to Learning the Language
When you are done working with a file, it is important to close it using the
file.close() method to free up system resources.
It’s important to note that, python have other library like pandas and numpy
that have their own file read and write functionality. They are more powerful
and flexible than the built-in python file methods
You can use it like this:
import pandas as pd
df = pd.read_csv(‘file.csv’)
df.to_csv(‘newfile.csv’, index=False)
import os
os.rename(“current_file.txt”, “new_file.txt”)
To delete a file, you can use the os.remove() function, which takes the file
name as its argument. For example:
import os
os.remove(“file_to_delete.txt”)
It’s also worth noting that there is also shutil module which also have similar
functionality such as shutil.move(src, dst) and shutil.rmtree(path, ignore_
errors=False, onerror=None) which can be useful in some cases.
For example:
numbers = [1, 2, 3, 4, 5]
numbers.remove(3)
print(numbers) # Output: [1, 2, 4, 5]
In this example, the remove() method is used to remove the value 3 from the
list numbers. After the method is called, the list contains the values 1, 2, 4,
and 5, and the value 3 is no longer present in the list.
The path parameter is required, and it specifies the name of the directory to
be created. The mode parameter is an optional argument that specifies the
permissions mode for the new directory, and the default value is 0o777. The
dir_fd parameter is used to specify a file descriptor for the parent directory.
For example:
import os
os.mkdir(“new_directory”)
This example creates a new directory called “new_directory” in the current
working directory. If the directory already exists, os.mkdir() will raise a
FileExistsError exception.
It’s important to note that the os.mkdir() method creates only one new
directory at a time, If you need to create multiple directories at once you can
use os.makedirs() method.
import os
current_dir = os.getcwd()
print(current_dir)
Method Description
os.mkdir(path) Creates a new directory at the specified path.
os.rmdir(path) Removes the directory at the specified path (the directory
must be empty).
File Management in Python 195
Method Description
os.chdir(path) Changes the current working directory to the specified path.
os.getcwd() Returns a string representing the current working directory.
os.listdir(path) Returns a list of filenames in the specified directory (defaults
to the current working directory if no path is specified).
os.scandir(path) Returns an iterator of DirEntry objects representing entries
in the specified directory (similar to listdir(), but faster and
provides more information about each entry).
os.makedirs(path) Recursively creates directories, including any intermediate
ones that do not exist.
os.removedirs(path) Recursively removes directories, including any intermediate
ones that are now empty.
os.stat(path) Returns information about the specified file or directory as
a stat_result object.
os.path.isdir(path) os.path.isdir(path)
9.8 Summary
In this chapter, we delve into the subject of data files. We cover the various
techniques for handling files and directories in Python, along with the
practical applications of each method. Topics include creating and opening
files, operating in different modes such as reading and writing, as well as
methods for renaming, deleting, creating directories, changing directories,
and removing directories.
Review Questions
1. What is a file in Python?
2. How do you open a file in Python and what modes are available?
3. What is the difference between read and write mode in Python file
handling?
4. How do you read the contents of a file in Python?
5. How do you write data to a file in Python?
6. What is the difference between write and append mode in Python file
handling?
7. How do you close a file in Python?
8. What is the os module in Python and how is it used for file handling?
9. How do you rename a file in Python?
196 Python Programming: A Step-by-Step Guide to Learning the Language
Highlights
l Object-Oriented Programming Methodologies
l Designing Classes
l Creating Objects
l Accessing Attributes
l Built - in Class Attributes
l Garbage Collection
In Python, you can also use inheritance to create subclasses that inherit
attributes and methods from a parent class. This allows you to reuse code
and create hierarchies of classes that share common behavior. OOP in Python
can be used to create complex programs and libraries, as well as to model
real-world objects and systems.
Object-Oriented Programming Methodologies:
• Class: A blueprint or template for creating objects that share similar
attributes and behaviors.
• Object: An instance of a class that has its own set of attributes and
methods.
• Inheritance: A way to create new classes based on existing classes,
inheriting their attributes and methods.
• Polymorphism: The ability of objects to take on different forms or
behave in different ways depending on the context.
• Encapsulation: The practice of hiding the internal details of an object
and exposing only the necessary information through methods.
• Abstraction: The process of reducing complexity by hiding unnecessary
details, allowing you to focus on the essential features of an object or
system.
Classes and objects are the fundamental building blocks of object-oriented
programming (OOP) in Python.
A class is a blueprint or template for creating objects, which can contain data
(attributes) and code (methods) that act on that data. Classes provide a way
to structure the data and behavior of similar objects, making it easier to create
and manage those objects.
An object is an instance of a class, created at runtime, with its own set of
attributes and methods. Objects are used to model real-world entities and
their behavior, making it easier to represent and manipulate complex data
and logic in a program.
In Python, you can define a class using the class keyword, followed by the
name of the class, and then the class definition inside a code block. You can
define the attributes and methods of a class, and when you create an object
from a class, it will inherit all of the attributes and methods defined in that
class.
Classes and Objects 199
def honk(self):
print(“Beep beep!”)
In this example, the Dog class has two attributes name and breed, and one
method bark(). The special method __init__ is a constructor that is called
when a new instance of the class is created. The self parameter refers to the
instance of the class and is used to access attributes and methods.
def bark(self):
print(“Woof!”)
In this example, we define a class called Dog with a constructor __init__ that
takes two parameters name and breed. We then create an instance of the Dog
class by calling Dog(“Rufus”, “Labrador”). This creates a new object dog
and initializes its name and breed attributes.
Code 10.3 access the attributes of an object using dot notation
print(dog.name) # Outputs: “Rufus”
print(dog.breed) # Outputs: “Labrador”
You can also call the methods of an object in the same way:
dog.bark() # Outputs: “Woof!”
This is just a simple example of how you can create objects in Python. You
can define more complex classes with multiple attributes, methods, and
inheritance to model real-world objects and their behavior.
def print_variables(self):
print(f”Instance variable: {self.instance_variable}”)
print(f”Class variable: {MyClass.class_variable}”)
202 Python Programming: A Step-by-Step Guide to Learning the Language
In this example, name and age are instance variables that are initialized with
the values passed in as arguments to the __init__() method. The say_hello()
method uses these instance variables to print out a message.
To create objects from this class and access the instance variables, you would
do the following:
Code 10.6 Illustration of class with instance variables
person1 = Person(“Alice”, 30)
person2 = Person(“Bob”, 25)
person1.say_hello() # Output: Hello, my name is Alice and I’m 30 years
old.
person2.say_hello() # Output: Hello, my name is Bob and I’m 25 years
old.
In this example, person1 and person2 are two different instances of the Person
class, and they each have their own set of instance variables name and age.
The say_hello() method prints out the values of these instance variables for
the given object.
Classes and Objects 203
In this example, obj is an instance of the MyClass class, and we call the
instance_method method on it. We also call the class_method and static_
method methods on the MyClass class itself.
def get_private_member(self):
return self.__private_member
In this example, the Dog class has two attributes name and breed. We create
an instance of the Dog class and store it in the variable dog. To access the
attributes of the dog object, we use dot notation dog.name and dog.breed.
You can also access the attributes of an object dynamically using the getattr
function. The syntax is getattr(object_name, attribute_name). For example:
Code 10.11 accessing attributes using getattr function
name = getattr(dog, “name”)
breed = getattr(dog, “breed”)
print(name) # Outputs: “Rufus”
print(breed) # Outputs: “Labrador”
The getattr function takes two arguments: the object and the name of the
attribute you want to access. If the attribute exists, it returns the value of the
attribute. If the attribute does not exist, it returns an AttributeError. You can
also provide a default value to be returned in case the attribute does not exist,
by passing a third argument to getattr.
In this example, we define a class called Car with a constructor __init__ that
takes three parameters make, model, and year. The constructor sets these
parameters as attributes of the Car class. We also have a method honk that
outputs “Beep Beep!” when called.
We then create an instance of the Car class and store it in the variable car.
To access the attributes and call the methods of the car object, we use dot
notation.
In this example, we use the input function to take user input for the dog’s
name and breed. The user inputs are then passed as arguments to the Dog
class constructor when creating a new instance of the class. The rest of the
program works the same as before, accessing the attributes and calling the
method of the dog object.
You can use this pattern to create class instances with user input in any
Python program. Just make sure to handle any exceptions or errors that might
occur, such as invalid input format, to ensure the stability and reliability of
your program.
208 Python Programming: A Step-by-Step Guide to Learning the Language
In this example, we define a class Circle with a class attribute pi set to 3.14.
The class also has a constructor __init__ that takes a radius argument and
sets it as an attribute of the Circle class. We also have a method area that
calculates and returns the area of the circle using the formula pi * r^2.
We then create an instance of the Circle class and store it in the variable
circle. We use the input function to take user input for the radius of the circle.
The input is then converted to a float and passed as an argument to the Circle
class constructor.
Finally, we call the area method on the circle object to calculate the area of
the circle and print the result.
In Python, you can edit class attributes by directly modifying the attribute
value on an instance of the class. This means that you can change the value of
an attribute for a specific instance of the class, without affecting the value of
that attribute for other instances of the class or for the class definition itself.
Code 10.15 editing class attributes in Python
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(“Woof!”)
dog = Dog(“Buddy”, “Labrador”)
print(dog.name)
print(dog.breed)
dog.name = “Rufus”
dog.breed = “Golden Retriever”
print(dog.name)
print(dog.breed)
In this example, we create an instance of the Dog class and store it in the
dog variable. We then print the original name and breed of the dog, which
are “Buddy” and “Labrador”.
Next, we modify the name and breed attributes of the dog object by directly
assigning new values to them. Finally, we print the updated name and breed
of the dog, which are “Rufus” and “Golden Retriever”.
Note that the changes we make to the attributes of an instance of the class
only affect that particular instance, and do not affect other instances or the
class definition itself. This allows you to have different instances of the same
class with different attribute values.
def bark(self):
print(“Woof!”)
print(dog.__dict__)
print(dog.__doc__)
print(dog.__name__)
print(dog.__module__)
print(dog.__class__)
In this example, we create an instance of the Dog class and store it in the
dog variable. Then, we use the built-in class attributes __dict__, __doc__,
__name__, __module__, and __class__ to access information about the dog
instance.
Classes and Objects 211
The output of this code will be a dictionary that contains the attributes and
values of the dog instance, a string that contains the documentation for the
Dog class (which is empty in this case), a string that contains the name of
the dog instance (which is not defined), a string that contains the name of
the module where the Dog class is defined, and a reference to the Dog class
itself.
10.10 Summary
In this chapter, we covered the basics of designing classes in Python. A class
is a blueprint for creating objects, which can be used to encapsulate data and
behavior. We learned how to create objects from a class by calling the class
212 Python Programming: A Step-by-Step Guide to Learning the Language
Review Questions
1. What is a class in Python?
2. How do you create an object from a class in Python?
3. How do you access the attributes of an object in Python?
4. What are some built-in class attributes in Python?
5. What is the purpose of garbage collection in Python?
6. How does Python handle memory management?
7. Can you explicitly release an object’s memory in Python?
8. What is the difference between a class and an object in Python?
9. How do you access the documentation of a class in Python?
10. What is the purpose of the __dict__ built-in class attribute in Python?
11. What is the purpose of the __init__ method in a Python class?
A. To initialize the class
B. To call other methods within the class
C. To specify the attributes of an object
12. What is the purpose of garbage collection in Python?
A. To free up memory that is no longer being used by the program
B. To increase the speed of the program
C. To reduce the memory usage of the program
11
Inheritance
Highlights
l Python Single Inheritance
l Python Multiple Inheritance
l Python Multilevel Inheritance
l Method Overriding in Python
l Special Functions in Python
Inheritance is a powerful feature of OOP that allows for code reuse and
modularity. It makes it possible to define common functionality once in a
base class, and then reuse that functionality in multiple derived classes.
In this example, the Dog class inherits from the Animal class. This means
that the Dog class has access to all the attributes and methods of the Animal
class, including the name and species attributes and the make_sound method.
The Dog class can also add its own attributes and methods, such as the breed
attribute and its own implementation of the make_sound method.
Inheritance 215
print(teacher.age)
print(teacher.student_id)
print(teacher.teacher_id)
teacher.say_hello()
teacher.enroll()
teacher.teach()
In this example, the Teacher class inherits from both the Person and Student
classes. This means that the Teacher class has access to all the attributes
and methods of both the Person and Student classes, including the name,
age, student_id, and enroll methods. The Teacher class can also add its own
attributes and methods, such as the teacher_id attribute and the teach method.
It’s important to note that when multiple inheritance is used, the order of the
parent classes in the class definition can matter. If there are conflicts between
the parent classes, the first parent class in the list will take precedence. This
is known as the method resolution order (MRO) in Python.
def have_fur(self):
print(f”{self.species} has {self.fur_color} fur”)
class Dog(Mammal):
def __init__(self, breed, fur_color):
Mammal.__init__(self, “Dog”, fur_color)
self.breed = breed
def bark(self):
print(f”{self.breed} barks”)
dog = Dog(“Labrador”, “Golden”)
print(dog.species)
print(dog.fur_color)
print(dog.breed)
dog.make_sound()
dog.have_fur()
dog.bark()
In this example, the Dog class inherits from the Mammal class, which in
turn inherits from the Animal class. This creates a hierarchical inheritance
structure where the Dog class has access to all the attributes and methods
of both the Mammal and Animal classes, including the species, fur_color,
make_sound, and have_fur methods. The Dog class can also add its own
attributes and methods, such as the breed attribute and the bark method.
Multilevel inheritance allows for a more organized and reusable code
structure, as properties and methods can be shared between classes in a
hierarchical manner.
subclass will override the implementation in the parent class for objects of
the subclass.
Code 11.4 method overriding in Python
class Shape:
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
square = Square(5)
print(square.area())
In this example, the Square class inherits from the Shape class. The Shape
class has a area method that does not have an implementation. The Square
class provides its own implementation for the area method by defining the
method with the same name in the class and providing its own implementation.
When the area method is called on a Square object, the implementation in the
Square class is used instead of the one in the Shape class. This is an example
of method overriding.
Method overriding is a powerful feature that allows subclasses to provide
their own implementation for a method while still preserving the same
interface as the parent class. This makes the code more flexible and reusable,
as subclasses can inherit common properties and methods from the parent
class but still have the ability to customize their behavior.
11.6 Summary
Inheritance is a fundamental aspect of object-oriented programming in
Python, which allows you to create new classes that inherit properties and
behaviors from existing classes. The concept of inheritance allows for code
reusability and modularity, making it easier to maintain and extend code
over time. In Python, you can achieve inheritance through single inheritance,
multiple inheritance, and multilevel inheritance. Single inheritance is when
a class inherits properties and behaviors from a single parent class. Multiple
inheritance is when a class inherits properties and behaviors from multiple
parent classes. Multilevel inheritance is when a class inherits properties and
behaviors from a parent class, which in turn inherits from another parent
220 Python Programming: A Step-by-Step Guide to Learning the Language
Review Questions
1. What is the purpose of Multiple Inheritance in Python?
2. Can a class inherit from multiple parent classes in Python?
3. What is the difference between Multiple Inheritance and Multilevel
Inheritance?
4. How does Method Overriding work in Python?
5. Can you provide an example of Method Overriding in Python?
6. What are the Special Functions in Python, and how do they work?
7. Can you provide an example of the init special function in Python?
8. What is the purpose of the str special function in Python?
9. Can you explain the use of the repr special function in Python?
10. What is the role of the super() function in relation to Method Overriding
in Python?
11. What is Multiple Inheritance in Python?
(a) When a class inherits properties and behaviors from a single parent
class
(b) When a class inherits properties and behaviors from multiple parent
classes
(c) When a class inherits properties and behaviors from a parent class,
which in turn inherits from another parent class
12. What is Method Overriding in Python?
(a) The process of providing a new implementation for a method defined
in a parent class
(b) The process of calling a method from a parent class
(c) The process of extending a method defined in a parent class
12
Python Operator
Overloading
Highlights
l Overloading ‘+’ Operator in Python
l Overloading ‘-’ Operator in Python
l Overloading Bitwise Operators
l Overloading Relational Operators
Here’s an example of how you might overload the “+” operator for a custom
class called “Point”:
Code 12.1 Overloading “+” operator
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3.x, p3.y)
In this example, the add method is used to add two Point objects together.
The + operator is applied to two Point instances, p1 and p2, and the result is
a third Point instance, p3, that represents the sum of the two.
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 - p2
print(p3.x, p3.y)
In this example, the sub method is used to subtract two Point objects. The -
operator is applied to two Point instances, p1 and p2, and the result is a third
Point instance, p3, that represents the difference of the two.
b1 = BitwiseOps(5)
b2 = BitwiseOps(3)
print(b1 & b2)
print(b1 | b2)
print(b1 ^ b2)
print(~b1)
print(b1 << 2)
print(b1 >> 1)
In this program, we define a class Rectangle with attributes width and height,
and methods area and __lt__. The area method calculates the area of the
rectangle by multiplying the width and height. The __lt__ method overloads
the ‘<’ operator and compares the areas of two rectangles.
We then create two instances of the Rectangle class and use the ‘<’ operator
to compare them. The output of the program will depend on the dimensions
of the rectangles we create. If rect1 has a smaller area than rect2, the program
will print “Rectangle 1 has a smaller area than Rectangle 2”, otherwise it will
print “Rectangle 1 has a larger area than Rectangle 2”.
12.5 Summary
In Python, we can customize the behavior of operators for our own classes by
overloading them with special methods. We can overload various operators
such as the addition and subtraction operators, bitwise operators, and relational
operators. To overload the addition operator ‘+’, we use the special method
“add”, and for the subtraction operator ‘-’, we use the “sub” method. For the
bitwise operators ‘&’, ‘|’, ‘^’, and ‘~’, we can overload them with the “and”,
“or”, “xor”, and “invert” methods respectively. We can also overload the
relational operators such as ‘<’, ‘>’, ‘<=’, ‘>=’, and ‘==’ by defining the “lt”,
“gt”, “le”, “ge”, and “eq” methods respectively. By overloading operators,
we can define custom behavior for our classes that can simplify the code and
make it more intuitive to use.
Review Questions
1. What is operator overloading in Python?
2. How can we overload the addition operator ‘+’ in Python?
226 Python Programming: A Step-by-Step Guide to Learning the Language
3. What is the special method used to overload the subtraction operator ‘-’
in Python?
4. How can we overload the bitwise operator ‘&’ in Python?
5. What is the special method used to overload the relational operator ‘<’
in Python?
6. Can we overload multiple operators in a single class in Python?
7. What is the benefit of overloading operators in Python?
8. How can we define custom behavior for our classes using operator
overloading in Python?
9. What is the difference between the ‘add’ and ‘radd’ methods in Python?
10. Can we overload operators for built-in classes in Python?
11. Which special method is used to overload the addition operator ‘+’ in
Python?
(a) add
(b) sub
(c) and
(d) or
12. Which operator can we overload using the “eq” method in Python?
(a) +
(b) –
(c) &
(d) ==
Appendix-1
List of Python Standard Modules
Module Name Description
array Efficient arrays of numeric values
atexit Register functions to be called when a program
closes
audioop Manipulate raw audio data
base64 Encode and decode binary data using Base64
representation
bdb Debugger framework
binascii Convert between binary and ASCII representations
bisect Binary search and insertion into sorted lists
builtins Built-in functions, exceptions, and attributes
cmath Complex math functions
collections Container datatypes
contextlib Utilities for with-statement contexts
copy Shallow and deep copy operations
csv CSV file reading and writing
datetime Basic date and time types
difflib Helpers for computing deltas
dis Disassembler for Python bytecode
email Package for handling email messages
encodings Encodings and Unicode handling
enum Enumeration types
fileinput Iterate over lines from multiple input sources
fnmatch Unix-style filename pattern matching
fractions Rational numbers
functools Higher-order functions and operations on callable
objects
gc Garbage collector for Python
getpass Portable password input
228 Python Programming: A Step-by-Step Guide to Learning the Language