| 1
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
| 2
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
| 3
DISCLAIMER
This book is designed to provide information on Python
only. This book does not contain all information available
on the subject. This book has not been created to be
specific to any individual’s or organizations’ situation or
needs. Every effort has been made to make this book as
accurate as possible. However, there may be
typographical and or content errors. Therefore, this book
should serve only as a general guide and not as the
ultimate source of subject information. This book contains
information that might be dated and is intended only to
educate and entertain. The management shall have no
liability or responsibility to any person or entity regarding
any loss or damage incurred, or alleged to have incurred,
directly or indirectly, by the information contained in this
book. You hereby agree to be bound by this disclaimer or
you may return this book within a week of receipt of this
book.
Copyright© 2017-2018, DexLab Solutions Corp
All Rights Reserved.
No part of this book may be reproduced or distributed in any form or by any electronic
or mechanical means including information storage and retrieval systems, without
permission in writing from the management.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
| 4
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
| 5
Contents
Chapters Topic Page
1. Python 9
2. First Python Program 10
3. Python Overview 11
4. Python Features 12
5. Python Environment Set Up 14 – 16
5.1 Windows Platform 14
5.2 Linux Platform 15
5.3 Mac OS 15
6. Setting Up Path 17 – 18
6.1 Setting Path at Unix/Linux 17
6.2 Setting Path at Windows 18
7. Python Environment Variables 19
8. Running Python 20 – 22
8.1 Interactive Interpreter 20
8.2 Script from the Command 21
8.3 Integrated Development Environment 21
9. First Python Program 23 – 25
9.1 Interactive Mode Programming 23
9.2 Script Mode Programming 24
10. Python Identifiers 26
11. Reserved Words 27
12. Lines & Indentations 28 – 29
13. Multi-Line Statements 30
14. Quotation in Python 31
15. Comments in Python 32 – 33
16. Using Blank Lines 34
17. Waiting for the User 35
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
| 6
18. Multiple Statements on a single line 36
19. Multiple Statement groups as Suites 37
20. Command Line Argument 38
21. Python Variable 39 – 40
21.1 Assigning Values to Variable 39
21.2 Multiple Assignment 40
22. Standard Datatypes 41 – 48
22.1 Number 41
22.2 String 43
22.3 List 44
22.4 Tuple 45
22.5 Dictionary 46
22.6 Data Type Conversion 48
23. Python Basic Operators 49 – 63
23.1 Types of Operator 49
23.2 Arithmetic Operator 50
23.3 Comparison Operator 52
23.4 Assignment Operator 55
23.5 Bitwise Operator 57
23.6 Logical Operator 59
23.7 Identity Operator 60
23.8 Python Operator Precedence 61
24. Decision Making 64 – 67
24.1 If 64
24.2 If Else 66
25. Loops 68 – 73
25.1 While Loop 68
25.2 For Loop 70
25.3 Break Statement 72
26. Data Structure 74 – 127
26.1 Python Number, Types & Mathematics 74
26.1.1 Type Conversion 76
26.1.2 Python Decimal 77
26.1.3 Python Fraction 79
26.1.4 Python Mathematics 80
26.2 Python Sets 82
26.3 Python Set Operations 87
26.3.1 Set Union 88
26.3.2 Set Intersection 89
26.3.3 Set Difference 90
26.3.4 Set Symmetric Difference 91
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
| 7
26.3.5 Different Python Set Methods 92
26.3.6 Other Set Operations 93
26.3.6.1 Set Membership Test 93
26.3.6.2 Iterating through a Set 93
26.3.6.3 Built-In Function with Set 94
26.4 Python Frozenset 95
26.5 Dictionary 96
26.5.1 Accessing values in Dictionary 96
26.5.2 Updating Dictionary 97
26.5.3 Deleting Dictionary Elements 98
26.5.4 Properties of Dictionary Keys 99
26.5.5 Built-In Dictionary Functions and methods 100
26.6 String 105
26.6.1 How to create a string 106
26.6.2 How to access characters in a string 107
26.6.3 How to change or delete characters in a string 109
26.6.4 Python String Operations 110
26.6.5 Python String Formatting 112
26.6.6 Common Python String Method 116
26.7 List 117
26.7.1 Accessing value in List 118
26.7.2 Updating List 118
26.7.3 Delete List Element 119
26.7.4 Basic List Operation 120
26.7.5 Indexing, Slicing, Matrices 120
26.7.6 Built-In List Functions & Methods 121
26.8 Tuple 122
26.8.1 Accessing value in Tuple 123
26.8.2 Updating Tuple 123
26.8.3 Delete Tuple Element 124
26.8.4 Basic Tuple Operation 125
26.8.5 Indexing, Slicing, Matrices 126
26.8.6 No Enclosing Delimiters 126
26.8.7 Built-In Tuple Function 127
27 Python Functions 128 – 139
27.1 Function Call 129
27.2 Docstring 129
27.3 The return Statement 130
27.4 How function works in Python 131
27.5 Scope & life time of Variables 132
27.6 Types of functions 133
27.7 Python Programming Built-In Functions 133
27.8 Python User Defined Function 137
28 Python Modules 140 – 147
28.1 How to import Modules in Python 141
28.2 Python Import Statement 142
28.3 Import with Renaming 142
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
| 8
28.4 Python from _import statement 143
28.5 Import all names 143
28.6 Python modules search path: Reloading a module 144
28.7 The dir() built-in Function 146
29 Python File I/O 148 – 156
29.1 Opening a file 149
29.2 Closing a file 150
29.3 Writing a file 151
29.4 Reading from a file 152
29.5 Python file methods 154
30 Python Directories and Files Management 157 – 162
30.1 Get current directory 157
30.2 Changing directory 158
30.3 List directory and files 159
30.4 Making a new directory 160
30.5 Renaming a directory 160
30.6 Removing directory or file 161
31 Python Errors and Built-In Exceptions 163 – 172
31.1 Python built-in exceptions 165
31.2 Python exception handling – try, except and finally 167
31.3 Catching exceptions in Python 168
31.4 Raising exception 171
31.5 Try – Finally 172
32 Python Namespace and Scope 173 – 179
32.1 What is namespace? 175
32.2 Python variable and scope 176
33 Python Objects and Class 180 – 186
33.1 Defining a class in Python 181
33.2 Creating an Object in Python 182
33.3 Constructor in Python 183
33.4 Deleting attributes and objects 185
34 Python Inheritance 187 – 202
34.1 Python Inheritance Syntax 188
34.2 Method Overriding in Python 190
34.3 Python Multiple Inheritance 191
34.4 Multilevel Inheritance in Python 193
34.5 Method Resolution Order in Python 194
34.6 Python Operator Overloading 196
34.7 Overloading the + Operator in Python 198
34.8 Overloading Compassion Operator in Python 200
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 1: PYTHON | 9
CHAPTER
Python
1
What is Python?
Python is a general-purpose interpreted, interactive, object-oriented, and
high-level programming language. It was created by Guido van Rossum
during 1985- 1990. Like Perl, Python source code is also available under the
GNU General Public License (GPL). This tutorial gives enough understanding
on Python programming language.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 2: FIRST PYTHON PROGRAM | 10
CHAPTER
First Python
Program
2
Execute Python Programs
#!/usr/bin/python
print "Hello, Dexlab!"
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 3: PYTHON OVERVIEW | 11
CHAPTER
Python
Overview
3
Python is a high-level, interpreted, interactive and object-oriented scripting
language. Python is designed to be highly readable. It uses English keywords
frequently where as other languages use punctuation, and it has fewer
syntactical constructions than other languages.
Python is Interpreted: Python is processed at runtime by the
interpreter. You do not need to compile your program before executing
it. This is similar to PERL and PHP.
Python is Interactive: You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style
or technique of programming that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for
the beginner-level programmers and supports the development of a
wide range of applications from simple text processing to WWW
browsers to games.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 4: PYTHON FEATURES | 12
CHAPTER
Python
Features
4
Python's features include:
Easy-to-learn: Python has few keywords, simple structure, and a
clearly defined syntax. This allows the student to pick up the language
quickly.
Easy-to-read: Python code is more clearly defined and visible to the
eyes.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
A broad standard library: Python's bulk of the library is very
portable and cross-platform compatible on UNIX, Windows, and
Macintosh.
Interactive Mode: Python has support for an interactive mode which
allows interactive testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and
has the same interface on all platforms.
Extendable: You can add low-level modules to the Python interpreter.
These modules enable programmers to add to or customize their tools to
be more efficient.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 4: PYTHON FEATURES | 13
Databases: Python provides interfaces to all major commercial
databases.
GUI Programming: Python supports GUI applications that can be
created and ported to many system calls, libraries and windows
systems, such as Windows MFC, Macintosh, and the X Window system
of Unix.
Scalable: Python provides a better structure and support for large
programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good
features, few are listed below:
It supports functional and structured programming methods as well as
OOP.
It can be used as a scripting language or can be compiled to byte-code
for building large applications.
It provides very high-level dynamic data types and supports dynamic
type checking.
IT supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and
Java.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 5: PYTHON ENVIRONMENT SETUP | 14
CHAPTER
Python
Environment
5
Setup
5.1 Windows Platform
Following different installation options are available
Windows x86-64 embeddable zip file
Windows x86-64 executable installer
Windows x86-64 web-based installer
Windows x86 embeddable zip file
Windows x86 executable installer
Windows x86 web-based installer
Note: In order to install Python 3.5.1, minimum OS requirements are
Windows 7 with SP1. For versions 3.0 to 3.4.x Windows XP is acceptable.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 5: PYTHON ENVIRONMENT SETUP | 15
5.2 Linux Platform
Different flavours of Linux use different package managers for installation of
new packages.
On Ubuntu Linux Python 3 is installed using following command from
terminal
$sudo apt-get install python3-minimal
Installation from source
Download Gzipped source tarball from Python's download URL :
https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
Extract the tarball
tar xvfz Python-3.5.1.tgz
Configure and Install
cd Python-3.5.1
./configure --prefix=/opt/python3.5.1
make
sudo make install
5.3 Mac OS
Download Mac OS installers from this URL
https://www.python.org/downloads/mac-osx/
Mac OS X 64-bit/32-bit installer : python-3.5.1-macosx10.6.pkg
Mac OS X 32-bit i386/PPC installer : python-3.5.1-
macosx10.5.pkg
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 5: PYTHON ENVIRONMENT SETUP | 16
Double click this package file and follow wizard instructions to install.
The most up-to-date and current source code, binaries, documentation, news,
etc., is available on the official website of Python:
Python Official Website
http://www.python.org/
You can download Python documentation from the following site. The
documentation is available in HTML, PDF and PostScript formats.
Python Documentation Website
www.python.org/doc/
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 6: SETTING UP PATH | 17
CHAPTER
Setting up
PATH
6
Programs and other executable files can be in many directories, so operating
systems provide a search path that lists the directories that the OS searches
for executables.
The path is stored in an environment variable, which is a named string
maintained by the operating system. This variable contains information
available to the command shell and other programs.
The path variable is named as PATH in Unix or Path in Windows (Unix is
case-sensitive; Windows is not).
In Mac OS, the installer handles the path details. To invoke the Python
interpreter from any particular directory, you must add the Python directory
to your path.
6.1 Setting path at Unix/Linux
To add the Python directory to the path for a particular session in Unix:
In the csh shell: Type
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 6: SETTING UP PATH | 18
set env PATH ="$PATH:/usr/local/bin/python3"
and press Enter.
In the bash shell (Linux): type
export PYTHONPATH=/usr/local/bin/python3.4
and press Enter.
In the sh or ksh shell: type
PATH="$PATH:/usr/local/bin/python3"
and press Enter.
Note: /usr/local/bin/python3 is the path of the Python directory
6.2 Setting path at Windows
To add the Python directory to the path for a particular session in Windows:
At the command prompt: type
path %path%;C:\Python
and press Enter.
Note: C:\Python is the path of the Python directory
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 7: PYTHON ENVIRONMENT VARIABLES | 19
CHAPTER
Python
Environment
7
Variables
Here are important environment variables, which can be recognized by
Python:
Variable Description
PYTHONPATH It has a role similar to PATH. This variable tells the Python
interpreter where to locate the module files imported into a
program. It should include the Python source library directory
and the directories containing Python source code.
PYTHONPATH is sometimes preset by the Python installer.
PYTHONSTARTUP It contains the path of an initialization file containing Python
source code. It is executed every time you start the interpreter.
It is named as .pythonrc.py in Unix and it contains commands
that load utilities or modify PYTHONPATH.
PYTHONCASEOK It is used in Windows to instruct Python to find the first case-
insensitive match in an import statement. Set this variable to
any value to activate it.
PYTHONHOME It is an alternative module search path. It is usually embedded in
the PYTHONSTARTUP or PYTHONPATH directories to make
switching module libraries easy.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 8: RUNNING PYTHON | 20
CHAPTER
Running
Python 8
There are three different ways to start Python:
8.1 Interactive Interpreter
You can start Python from Unix, DOS, or any other system that
provides you a command-line interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:>python # Windows/DOS
Here is the list of all the available command line options:
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 8: RUNNING PYTHON | 21
Option Description
-d provide debug output
-O generate optimized bytecode (resulting in .pyo files)
-S do not run import site to look for Python paths on startup
-v verbose output (detailed trace on import statements)
-X disable class-based built-in exceptions (just use strings); obsolete starting with
version 1.6
-c cmd run Python script sent in as cmd string
File run Python script from given file
8.2 Script from the Command-line
A Python script can be executed at command line by invoking the
interpreter on your application, as in the following:
$python script.py # Unix/Linux
or
python% script.py # Unix/Linux
or
C:>python script.py # Windows/DOS
Note: Be sure the file permission mode allows execution.
8.3 Integrated Development
Environment
You can run Python from a Graphical User Interface (GUI) environment as
well, if you have a GUI application on your system that supports Python.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 8: RUNNING PYTHON | 22
Unix: IDLE is the very first Unix IDE for Python.
Windows: PythonWin is the first Windows interface for Python and is
an IDE with a GUI.
Macintosh: The Macintosh version of Python along with the IDLE IDE
is available from the main website, downloadable as either MacBinary
or BinHex'd files.
If you are not able to set up the environment properly, then you can take help
from your system admin. Make sure the Python environment is properly set
up and working perfectly fine.
Note: All the examples given in subsequent chapters are executed with
Python 3.4.1 version available on Windows 7 and Ubuntu Linux
We already have set up Python Programming environment online, so that you
can execute all the available examples online at the same time when you are
learning theory. Feel free to modify any example and execute it online.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 9: FIRST PYTHON PROGRAM | 23
First Python CHAPTER
Program 9
Let us execute programs in different modes of programming.
9.1 Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings
up the following prompt
$ python
Python 3.3.2 (default, Dec 10 2013, 11:35:01)
[GCC 4.6.3] on Linux
Type "help", "copyright", "credits", or "license" for more information.
>>>
On Windows:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 9: FIRST PYTHON PROGRAM | 24
bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
Type the following text at the Python prompt and press the Enter:
>>> print ("Hello, Dexlab!")
If you are running older version of Python (Python 2.x), use of parenthesis as
in print function is optional. This produces the following result:
Hello, Dexlab!
9.2 Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the
script and continues until the script is finished. When the script is finished,
the interpreter is no longer active.
Let us write a simple Python program in a script. Python files have
extension .py. Type the following source code in a test.py file:
print ("Hello, Dexlab!")
We assume that you have Python interpreter set in PATH variable. Now, try
to run this program as follows:
On Linux
$ python test.py
This produces the following result:
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 9: FIRST PYTHON PROGRAM | 25
Hello, Dexlab!
On Windows
C:\Python34>Python test.py
This produces the following result:
Hello, Dexlab!
Let us try another way to execute a Python script in Linux. Here is the
modified test.py file
#!/usr/bin/python3
print ("Hello, Dexlab!")
We assume that you have Python interpreter available in /usr/bin directory.
Now, try to run this program as follows
$ chmod +x test.py # This is to make file executable
$./test.py
This produces the following result
Hello, Dexlab!
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 10: PYTHON IDENTIFIERS | 26
CHAPTER
Python
Identifiers
10
A Python identifier is a name used to identify a variable, function, class,
module or other object. An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores and digits (0 to
9).
Python does not allow punctuation characters such as @, $, and % within
identifiers. Python is a case sensitive programming language.
Thus, Dexlab and dexlab are two different identifiers in Python.
Here are naming conventions for Python identifiers −
Class names start with an uppercase letter. All other identifiers start
with a lowercase letter.
Starting an identifier with a single leading underscore indicates that
the identifier is private.
Starting an identifier with two leading underscores indicates a
strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier
is a language-defined special name.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 11: RESERVED WORDS | 27
CHAPTER
Reserved
Words
11
The following list shows the Python keywords. These are reserved words and
you cannot use them as constant or variable or any other identifier names.
All the Python keywords contain lowercase letters only.
And Exec Not
As Finally Or
Assert For Pass
Break From Print
Class Global Raise
Continue If Return
Def Import Try
Del In While
Elif Is With
Else Lambda Yield
Except
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 12: LINES AND INDENTATION | 28
CHAPTER
Lines and
Indentation
12
Python doesn't use braces ({}) to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation,
which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements
within the block must be indented the same amount. For example
if True:
print ("True")
else:
print ("False")
However, the following block generates an error
if True:
print ("Answer")
print ("True")
else:
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 12: LINES AND INDENTATION | 29
print "(Answer")
print ("False")
Thus, in Python all the continuous lines indented with same number of
spaces would form a block. The following example has various statement
blocks.
Note: Do not try to understand the logic at this point of time. Just make sure
you understood various blocks even if they are without braces.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 13: MULTI-LINE STATEMENTS | 30
CHAPTER
Multi-Line
Statements
13
Statements in Python typically end with a new line. Python does, however,
allow the use of the line continuation character (\) to denote that the line
should continue. For example
total = dexlab_one + \
dexlab_two + \
dexlab_three
Statements contained within the [], {}, or () brackets do not need to use the
line continuation character. For example
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 14: QUOTATION IN PYTHON | 31
CHAPTER
Quotation in
Python
14
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For
example, all the following are legal
word = 'word'
sentence = "This is a Dexlab Corporation."
paragraph = """This is a paragraph. It ismade up of multiple lines and
sentences."""
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 15: COMMENTS IN PYTHON | 32
CHAPTER
Comments
in Python
15
A hash sign (#) that is not inside a string literal begins a comment. All
characters after the # and up to the end of the physical line are part of the
comment and the Python interpreter ignores them.
#!/usr/bin/python3
# First comment
print ("Hello, Dexlab!") # second comment
This produces the following result
Hello, Dexlab!
You can type a comment on the same line after a statement or expression
name = "Dexlab" # This is again comment
Python doesn't have multiple-line commenting feature. You should comment
each line individually as follows
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 15: COMMENTS IN PYTHON | 33
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 16: USING BLANK LINES | 34
CHAPTER
Using Blank
Lines
16
A line containing only whitespace, possibly with a comment, is known as a
blank line and Python totally ignores it.
In an interactive interpreter session, you must enter an empty physical line
to terminate a multiline statement.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 17: WAITING FOR THE USER | 35
CHAPTER
Waiting for
the User
17
The following line of the program displays the prompt, the statement saying
“Press the enter key to exit”, and waits for the user to take action
#!/usr/bin/python3
input("\n\nPress the enter key to exit.")
Here, "\n\n" is used to create two new lines before displaying the actual line.
Once the user presses the key, the program ends. This is a nice trick to keep a
console window open until the user is done with an application.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 18: MULTIPLE STATEMENTS ON A SINGLE LINE | 36
CHAPTER
Multiple
Statements
18
on a Single Line
The semicolon ( ; ) allows multiple statements on the single line given that
neither statement starts a new code block. Here is a sample snip using the
semicolon
import sys; x = 'foo'; sys.stdout.write(x + '\n')
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 19: MULTIPLE STATEMENT GROUPS AS SUITES | 37
CHAPTER
Multiple
Statement
19
Groups as Suites
A group of individual statements, which make a single code block are
called suites in Python. Compound or complex statements, such as if, while,
def, and class require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a
colon ( : ) and are followed by one or more lines which make up the suite. For
example
if expression :
suite
elif expression :
suite
else :
suite
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 21: COMMAND LINE ARGUMENTS | 38
CHAPTER
Command Line
Arguments 20
Many programs can be run to provide you with some basic information about
how they should be run. Python enables you to do this with -h –
$ python –h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]
You can also program your script in such a way that it should accept various
options. Command Line Arguments is an advanced topic and should be
studied a bit later once you have gone through rest of the Python concepts.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 21: PYTHON VARIABLES | 39
CHAPTER
Python
Variables
21
Variables are nothing but reserved memory locations to store values. This
means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, you can store integers, decimals or
characters in these variables.
21.1 Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory space.
The declaration happens automatically when you assign a value to a variable.
The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable. For
example
#!/usr/bin/python3
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 21: PYTHON VARIABLES | 40
total = 100 # An integer assignment
marks = 85.0 # A floating point
name = "Dexlab" # A string
print (total)
print (marks)
print (name)
Here, 100, 85.0 and "Dexlab" are the values assigned to total, marks,
and name variables, respectively. This produces the following result
100
85.0
Dexlab
21.2 Multiple Assignment
Python allows you to assign a single value to several variables
simultaneously. For example
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are
assigned to the same memory location. You can also assign multiple objects to
multiple variables. For example
a, b, c = 1, 2, "Dexlab"
Here, two integer objects with values 1 and 2 are assigned to variables a and
b respectively, and one string object with the value "Dexlab" is assigned to
the variable c.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 22: STANDARD DATA TYPES | 41
CHAPTER
Standard
Data Types
22
The data stored in memory can be of many types. For example, a person's age
is stored as a numeric value and his or her address is stored as alphanumeric
characters. Python has various standard data types that are used to define
the operations possible on them and the storage method for each of them.
Python has five standard data types −
Numbers
String
List
Tuple
Dictionary
22.1 Python Numbers
Number data types store numeric values. Number objects are created when
you assign a value to them. For example
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 22: STANDARD DATA TYPES | 42
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del
statement. The syntax of the del statement is
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement.
For example
del var
del var_a, var_b
Python supports four different numerical types
int (signed integers)
float (floating point real values)
complex (complex numbers)
All integers in Python3 are represented as long integers. Hence there is no
separate number type as long.
Examples
Here are some examples of numbers
Int Float Complex
10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3+e18 .876j
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 22: STANDARD DATA TYPES | 43
-0490 -90. -.6545+0J
-0x260 -32.54e100 3e+26J
0x69 70.2-E12 4.53e-7j
A complex number consists of an ordered pair of real floating-point
numbers denoted by x + yj, where x and y are the real numbers and j
is the imaginary unit.
22.2 Python Strings
Strings in Python are identified as a contiguous set of characters represented
in the quotation marks. Python allows for either pairs of single or double
quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] )
with indexes starting at 0 in the beginning of the string and working their
way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator. For example
#!/usr/bin/python3
str = 'Hello Dexlab!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "Analytics") # Prints concatenated string
This will produce the following result
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 22: STANDARD DATA TYPES | 44
Hello Dexlab!
llo
llo Dexlab!
Hello Dexlab!Hello Dexlab!
Hello Dexlab!Analytics
22.3 Python Lists
Lists are the most versatile of Python's compound data types. A list contains
items separated by commas and enclosed within square brackets ([]). To some
extent, lists are similar to arrays in C. One difference between them is that
all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way
to end -1. The plus (+) sign is the list concatenation operator, and the asterisk
(*) is the repetition operator. For example
#!/usr/bin/python3
list = [ 'abcd', 786 , 2.23, 'Dexlab', 70.2 ]
second_list = [123, 'Analytics']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 22: STANDARD DATA TYPES | 45
print (second_list * 2) # Prints list two times
print (list + second_list) # Prints concatenated lists
This produces the following result
['abcd', 786, 2.23, 'Dexlab', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'Dexlab', 70.200000000000003]
[123, 'Analytics', 123, 'analytics']
['abcd', 786, 2.23, 'Dexlab', 70.200000000000003, 123, 'Analytics']
22.4 Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple
consists of a number of values separated by commas. Unlike lists, however,
tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples are
enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought
of as read-only lists. For example
#!/usr/bin/python3
tuple = ( 'abcd', 786 , 2.23, 'Dexlab', 70.2 )
second_tuple = (123, ‘Analytics’)
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 22: STANDARD DATA TYPES | 46
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple
This produces the following result
('abcd', 786, 2.23, 'Dexlab', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'Dexlab', 70.200000000000003)
(123, ‘Analytics’, 123, ‘Analytics’)
('abcd', 786, 2.23, 'Dexlab', 70.200000000000003, 123, ‘Analytics’)
The following code is invalid with tuple, because we attempted to update a
tuple, which is not allowed. Similar case is possible with lists
#!/usr/bin/python3
tuple = ( 'abcd', 786 , 2.23, 'Dexlab', 70.2 )
list = [ 'abcd', 786 , 2.23, 'Dexlab', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
22.5 Python Dictionary
Python's dictionaries are kind of hash table type. They work like associative
arrays or hashes found in Perl and consist of key-value pairs. A dictionary
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 22: STANDARD DATA TYPES | 47
key can be almost any Python type, but are usually numbers or strings.
Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]). For example
#!/usr/bin/python3
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
second_dict = {'name': 'Dexlab','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (second_dict) # Prints complete dictionary
print (second_dict.keys()) # Prints all the keys
print (second_dict.values()) # Prints all the values
This produces the following result
This is one
This is two
{'code': 6734, 'name': 'Dexlab', 'dept': 'sales'}
dict_keys(['code', 'name', 'dept'])
dict_values([6734, 'Dexlab', 'sales'])
Dictionaries have no concept of order among elements. It is incorrect to say
that the elements are "out of order"; they are simply unordered.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 22: STANDARD DATA TYPES | 48
22.6 Data Type Conversion
Sometimes, you may need to perform conversions between the built-in types.
To convert between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type
to another. These functions return a new object representing the converted
value.
Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x
is a string.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of
(key,value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 49
Python Basic
CHAPTER
Operators
23
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator.
23.1 Types of Operators
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 50
Let us have a look on all operators one by one.
23.2 Arithmetic Operators
Assume variable a holds 10 and variable b holds 21, then
#!/usr/bin/python
a = 100
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c=a-b
print "Line 2 - Value of c is ", c
c=a*b
print "Line 3 - Value of c is ", c
c=a/b
print "Line 4 - Value of c is ", c
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 51
c=a%b
print "Line 5 - Value of c is ", c
a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c
a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c
Operator Description Example
+ Addition Adds values on either side of the a + b = 31
operator.
- Subtraction Subtracts right hand operand from left a – b = -11
hand operand.
* Multiplication Multiplies values on either side of the a * b = 210
operator
/ Division Divides left hand operand by right hand b / a = 2.1
operand
% Modulus Divides left hand operand by right hand b%a=1
operand and returns remainder
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 52
** Exponent Performs exponential (power) calculation a**b =10 to the
on operators power 20
// Floor Division - The division of operands 9//2 = 4 and
where the result is the quotient in which 9.0//2.0 = 4.0, -
the digits after the decimal point are 11//3 = -4, -11.0//3
removed. But if one of the operands is = -4.0
negative, the result is floored, i.e.,
rounded away from zero (towards
negative infinity):
23.3 Comparison Operators
These operators compare the values on either sides of them and decide the
relation among them. They are also called Relational operators.
Assume variable a holds 20 and variable b holds 30, then
#!/usr/bin/python
a = 20
b = 30
c=0
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 53
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"
if ( a <> b ):
print "Line 3 - a is not equal to b"
else:
print "Line 3 - a is equal to b"
if ( a < b ):
print "Line 4 - a is less than b"
else:
print "Line 4 - a is not less than b"
if ( a > b ):
print "Line 5 - a is greater than b"
else:
print "Line 5 - a is not greater than b"
a = 25;
b = 20;
if ( a <= b ):
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 54
print "Line 6 - a is either less than or equal to b"
else:
print "Line 6 - a is neither less than nor equal to b"
if ( b >= a ):
print "Line 7 - b is either greater than or equal to b"
else:
print "Line 7 - b is neither greater than nor equal to b"
Operator Description Example
== If the values of two operands are equal, (a == b) is not true.
then the condition becomes true.
!= If values of two operands are not equal, (a!= b) is true.
then condition becomes true.
> If the value of left operand is greater than (a > b) is not true.
the value of right operand, then condition
becomes true.
< If the value of left operand is less than (a < b) is true.
the value of right operand, then condition
becomes true.
>= If the value of left operand is greater than (a >= b) is not true.
or equal to the value of right operand,
then condition becomes true.
<= If the value of left operand is less than or (a <= b) is true.
equal to the value of right operand, then
condition becomes true.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 55
23.4 Assignment Operators
Assume variable a holds 10 and variable b holds 20, then
#!/usr/bin/python
a = 31
b = 20
c=0
c=a+b
print "Line 1 - Value of c is ", c
c += a
print "Line 2 - Value of c is ", c
c *= a
print "Line 3 - Value of c is ", c
c /= a
print "Line 4 - Value of c is ", c
c =2
c %= a
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 56
print "Line 5 - Value of c is ", c
c **= a
print "Line 6 - Value of c is ", c
c //= a
print "Line 7 - Value of c is ", c
Operator Description Example
= Assigns values from right side operands to left c=a+b
side operand assigns value
of a + b into c
+= Add It adds right operand to the left operand and c += a is
AND assign the result to left operand equivalent to
c=c+a
-= Subtract It subtracts right operand from the left operand c -= a is
AND and assign the result to left operand equivalent to
c=c-a
*= Multiply It multiplies right operand with the left operand c *= a is
AND and assign the result to left operand equivalent to
c=c*a
/= Divide It divides left operand with the right operand and c /= a is
AND assign the result to left operand equivalent to
c = c / ac /= a
is equivalent
to c = c / a
%= It takes modulus using two operands and assign c %= a is
Modulus the result to left operand equivalent to
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 57
AND c=c%a
**= Performs exponential (power) calculation on c **= a is
Exponent operators and assign value to the left operand equivalent to
AND c = c ** a
//= Floor It performs floor division on operators and c //= a is
Division assign value to the left operand equivalent to
c = c // a
23.5 Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if
a = 60; and b = 13; Now in binary format they will be as follows
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Pyhton's built-in function bin() can be used to obtain binary representation
of integer number.
There are following Bitwise operators supported by Python language
#!/usr/bin/python
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 58
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 59
Operator Description Example
& Binary AND Operator copies a bit to the result (a & b) (means 0000
if it exists in both operands 1100)
| Binary OR It copies a bit if it exists in either (a | b) = 61 (means
operand. 0011 1101)
^ Binary XOR It copies the bit if it is set in one (a ^ b) = 49 (means
operand but not both. 0011 0001)
~ Binary Ones It is unary and has the effect of (~a ) = -61 (means
Complement 'flipping' bits. 1100 0011 in 2's
complement form
due to a signed
binary number.
<< Binary Left The left operands value is moved a << = 240 (means
Shift left by the number of bits specified 1111 0000)
by the right operand.
>> Binary Right The left operands value is moved a >> = 15 (means
Shift right by the number of bits 0000 1111)
specified by the right operand.
23.6 Python Logical Operators
There are following logical operators supported by Python language. Assume
variable a holds True and variable b holds False then
Operator Description Example
In Evaluates to true if it finds a variable in the x in y, here in
specified sequence and false otherwise. results in a 1 if x is
a member of
sequence y.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 60
not in Evaluates to true if it does not finds a x not in y, here not
variable in the specified sequence and in results in a 1 if x
false otherwise. is not a member of
sequence y.
23.7 Identity Operators
Identity operators compare the memory locations of two objects. There are
two Identity operators explained below:
#!/usr/bin/python
a = 20
b = 20
if ( a is b ):
print "Line 1 - a and b have same identity"
else:
print "Line 1 - a and b do not have same identity"
if ( id(a) == id(b) ):
print "Line 2 - a and b have same identity"
else:
print "Line 2 - a and b do not have same identity"
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 61
b = 30
if ( a is b ):
print "Line 3 - a and b have same identity"
else:
print "Line 3 - a and b do not have same identity"
if ( a is not b ):
print "Line 4 - a and b do not have same identity"
else:
print "Line 4 - a and b have same identity"
Operator Description Example
Is Evaluates to true if the variables on either x is y,
side of the operator point to the same object here is results in
and false otherwise. 1 if id(x) equals
id(y).
is not Evaluates to false if the variables on either x is not y, here is
side of the operator point to the same object not results in 1 if
and true otherwise. id(x) is not equal
to id(y).
23.8 Python Operators Precedence
The following table lists all operators from highest precedence to lowest.
#!/usr/bin/python
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 62
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e
e = (a + b) * (c / d); # (30) * (15/5)
print "Value of (a + b) * (c / d) is ", e
e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e
Operator Description
** Exponentiation (raise to the power)
~+- Ccomplement, unary plus and minus (method names for the
last two are +@ and -@)
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 23: PYTHON BASIC OPERATORS | 63
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << 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 Logical operators
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 24: DECISION MAKING | 64
Decision CHAPTER
Making 24
24.1 If
The most common developing tool in use for decision making is the if
statement. You may never find a programming languages that don’t support
the if statement. Though its syntax differs from language to another, the
logic is the same in all. The following is the syntax of the if statement in
Python:
Syntax :
if condition:
one-or-more-statements
The syntax consists of:
1. The reserved word if
2. A condition followed by a colon (:). The condition could be any
expression that evaluates to True of False; i.e. it could be a simple
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 24: DECISION MAKING | 65
comparison, a composite expression using logical operators, or even the
Boolean values True or False themselves.
3. One or more statements, to be executed if the condition is met. These
statements must be indented (shifted) to the right an equal amount of
spaces. (You remember when I told you that Python cares about
leading white spaces; I think you got the reason now).
Flow Diagram
Figure 1: Flowchart of If condithion
Example :
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 24: DECISION MAKING | 66
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
24.2 If else
The else statement is an optional statement and there could be at most only
one else statement following if .
Syntax
The syntax of the if...else statement is
if expression:
statement(s)
else:
statement(s)
Flow Diagram
Figure 2: Flowchart of If Else condition
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 24: DECISION MAKING | 67
Example
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
print "Good bye!"
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 68
CHAPTER
Loops
25
25.1 While loop
A while loop statement in Python programming language repeatedly
executes a target statement as long as a given condition is true.
Syntax
The syntax of a while loop in Python programming language is
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value. The
loop iterates while the condition is true.
When the condition becomes false, program control passes to the line
immediately following the loop.
In Python, all the statements indented by the same number of character
spaces after a programming construct are considered to be part of a single
block of code. Python uses indentation as its method of grouping statements.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 69
Flow Diagram
Here, key point of the while loop is that the loop
might not ever run. When the condition is tested
and the result is false, the loop body will be
skipped and the first statement after the while
loop will be executed.
Figure 3: Flowchart of while loop
Example
#!/usr/bin/python
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 70
25.2 for Loop
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first
item in the sequence is assigned to the iterating variable iterating_var. Next,
the statements block is executed. Each item in the list is assigned
to iterating_var, and the statement(s) block is executed until the entire
sequence is exhausted.
Flow Diagram
Figure 4: Flowchart of for loop
Example
#!/usr/bin/python
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 71
for letter in 'Dexlab': # First Example
print 'Current Letter :', letter
Mobiles = ['oppo', 'apple', 'samsung']
for Mobile in mobiles: # Second Example
print 'Current mobile :', mobile
print "Good bye!"
When the above code is executed, it produces the following result
Current Letter : D
Current Letter : e
Current Letter : x
Current Letter : l
Current Letter : a
Current Letter : b
Current mobile : oppo
Current mobile : apple
Current mobile : samsung
Good bye!
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 72
25.3 Break Statement
Syntax
The syntax for a break statement in Python is as follows
Break
Flow Diagram
Figure 5: Flowchart of break statement
Example
# Prints out 0,1,2,3,4
count = 0
while True:
print(count)
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 73
count += 1
if count >= 5:
break
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)
Output:
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 74
CHAPTER
Data
Structure
26
26.1 Python Numbers, Type Conversion
and Mathematics
In this topic, you'll learn about the different numbers used in Python, how to
convert from one data type to the other, and the mathematical operations
supported in Python.
Python supports integers, floating point numbers and complex numbers.
They are defined as int, float and complex class in Python.
Integers and floating points are separated by the presence or absence of a
decimal point. 5 is integer whereas 5.0 is a floating point number.
Complex numbers are written in the form, x + yj, where x is the real part
and y is the imaginary part.
We can use the type() function to know which class a variable or a value
belongs to and isinstance() function to check if it belongs to a particular class.
a=5
# Output: <class 'int'>
print(type(a))
# Output: <class 'float'>
print(type(5.0))
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 75
# Output: (8+3j)
c = 5 + 3j
print(c + 3)
# Output: True
print(isinstance(c, complex))
While integers can be of any length, a floating point number is accurate only
up to 15 decimal places (the 16th place is inaccurate).
Numbers we deal with everyday are decimal (base 10) number system. But
computer programmers (generally embedded programmer) need to work with
binary (base 2), hexadecimal (base 16) and octal (base 8) number systems.
In Python, we can represent these numbers by appropriately placing a prefix
before that number. Following table lists these prefix.
Number system prefix for Python numbers
Number System Prefix
Binary '0b' or '0B'
Octal '0o' or '0O'
Hexadecimal '0x' or '0X'
Here are some examples
# Output: 107
print(0b1101011)
# Output: 253 (251 + 2)
print(0xFB + 0b10)
# Output: 13
print(0o15)
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 76
When you run the program, the output will be:
107
253
13
26.1.1 Type Conversion
We can convert one type of number into another. This is also known as
coercion.
Operations like addition, subtraction coerce integer to float implicitly
(automatically), if one of the operand is float.
>>> 1 + 2.0
3.0
We can see above that 1 (integer) is coerced into 1.0 (float) for addition and
the result is also a floating point number.
We can also use built-in functions like int(), float() and complex() to
convert between types explicitly. These functions can even convert
from strings.
>>> int(2.3)
>>> int(-2.8)
-2
>>> float(5)
5.0
>>> complex('3+5j')
(3+5j)
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 77
When converting from float to integer, the number gets truncated (integer
that is closer to zero).
26.1.2 Python Decimal
Python built-in class float performs some calculations that might amaze us.
We all know that the sum of 1.1 and 2.2 is 3.3, but Python seems to disagree.
>>> (1.1 + 2.2) == 3.3
False
What is going on?
It turns out that floating-point numbers are implemented in computer
hardware as binary fractions, as computer only understands binary (0 and 1).
Due to this reason, most of the decimal fractions we know, cannot be
accurately stored in our computer.
Let's take an example. We cannot represent the fraction 1/3 as a decimal
number. This will give 0.33333333... which is infinitely long, and we can only
approximate it.
Turns out decimal fraction 0.1 will result into an infinitely long binary
fraction of 0.000110011001100110011... and our computer only stores a finite
number of it.
This will only approximate 0.1 but never be equal. Hence, it is the limitation
of our computer hardware and not an error in Python.
>>> 1.1 + 2.2
3.3000000000000003
To overcome this issue, we can use decimal module that comes with Python.
While floating point numbers have precision up to 15 decimal places, the
decimal module has user settable precision.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 78
import decimal
# Output: 0.1
print(0.1)
# Output:
Decimal('0.100000000000000005551115123125782702118158340454101562
5')
print(decimal.Decimal(0.1))
This module is used when we want to carry out decimal calculations like we
learned in school.
It also preserves significance. We know 25.50 kg is more accurate than 25.5
kg as it has two significant decimal places compared to one.
from decimal import Decimal as D
# Output: Decimal('3.3')
print(D('1.1') + D('2.2'))
# Output: Decimal('3.000')
print(D('1.2') * D('2.50'))
Notice the trailing zeroes in the above example.
We might ask, why not implement Decimal every time, instead of float? The
main reason is efficiency. Floating point operations are carried out must
faster than Decimal operations.
When to use Decimal instead of float?
We generally use Decimal in the following cases.
When we are making financial applications that need exact decimal
representation.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 79
When we want to control the level of precision required.
When we want to implement the notion of significant decimal places.
When we want the operations to be carried out like we did at school
26.1.3 Python Fractions
Python provides operations involving fractional numbers through
its fractions module.
A fraction has a numerator and a denominator, both of which are integers.
This module has support for rational number arithmetic.
We can create Fraction objects in various ways.
import fractions
# Output: 3/2
print(fractions.Fraction(1.5))
# Output: 5
print(fractions.Fraction(5))
# Output: 1/3
print(fractions.Fraction(1,3))
While creating Fraction from float, we might get some unusual results. This
is due to the imperfect binary floating point number representation as
discussed in the previous section.
Fortunately, Fraction allows us to instantiate with string as well. This is the
preferred options when using decimal numbers.
import fractions
# As float
# Output: 2476979795053773/2251799813685248
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 80
print(fractions.Fraction(1.1))
# As string
# Output: 11/10
print(fractions.Fraction('1.1'))
This datatype supports all basic operations. Here are few examples.
from fractions import Fraction as F
# Output: 2/3
print(F(1,3) + F(1,3))
# Output: 6/5
print(1 / F(5,6))
# Output: False
print(F(-3,10) > 0)
# Output: True
print(F(-3,10) < 0)
26.1.4 Python Mathematics
Python offers modules like math and random to carry out different
mathematics like trigonometry, logarithms, probability and statistics, etc.
import math
# Output: 3.141592653589793
print(math.pi)
# Output: -1.0
print(math.cos(math.pi))
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 81
# Output: 22026.465794806718
print(math.exp(10))
# Output: 3.0
print(math.log10(1000))
# Output: 1.1752011936438014
print(math.sinh(1))
# Output: 720
print(math.factorial(6))
Here is the full list functions and attributes available in Python math
module.
import random
# Output: 16
print(random.randrange(10,20))
x = ['a', 'b', 'c', 'd', 'e']
# Get random choice
print(random.choice(x))
# Shuffle x
random.shuffle(x)
# Print the shuffled x
print(x)
# Print random element
print(random.random())
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 82
26.2 Python Sets
In this topic, you'll learn everything about Python sets; how they are created,
adding or removing elements from them, and all operations performed on sets
in Python.
A set is an unordered collection of items. Every element is unique (no
duplicates) and must be immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical
set operations like union, intersection,
symmetric difference etc.
Figure 6: Python Sets
How to create a set?
A set is created by placing all the items (elements) inside curly braces {},
separated by comma or by using the built-in function set().
It can have any number of items and they may be of different types (integer,
float, tuple, string etc.). But a set cannot have a mutable element, like list,
set or dictionary, as its element.
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
Try the following examples as well.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 83
# set do not have duplicates
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)
# set cannot have mutable items
# here [3, 4] is a mutable list
# If you uncomment line #12,
# this will cause an error.
# TypeError: unhashable type: 'list'
#my_set = {1, 2, [3, 4]}
# we can make set from a list
# Output: {1, 2, 3}
my_set = set([1,2,3,2])
print(my_set)
Creating an empty set is a bit tricky.
Empty curly braces {} will make an empty dictionary in Python. To make a
set without any elements we use the set() function without any argument.
# initialize a with {}
a = {}
# check data type of a
# Output: <class 'dict'>
print(type(a))
# initialize a with set()
a = set()
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 84
# check data type of a
# Output: <class 'set'>
print(type(a))
How to change a set in Python?
Sets are mutable. But since they are unordered, indexing have no meaning.
We cannot access or change an element of set using indexing or slicing. Set
does not support it.
We can add single element using the add() method and multiple elements
using the update() method.
The update() method can take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.
# initialize my_set
my_set = {1,3}
print(my_set)
# if you uncomment line 9,
# you will get an error
# TypeError: 'set' object does not support indexing
#my_set[0]
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# add multiple elements
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 85
# Output: {1, 2, 3, 4}
my_set.update([2,3,4])
print(my_set)
# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4,5], {1,6,8})
print(my_set)
When you run the program, the output will be:
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
How to remove elements from a set?
A particular item can be removed from set using methods, discard() and
remove().
The only difference between the two is that, while using discard() if the item
does not exist in the set, it remains unchanged. But remove() will raise an
error in such condition.
The following example will illustrate this.
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 86
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# If you uncomment line 27,
# you will get an error.
# Output: KeyError: 2
#my_set.remove(2)
Similarly, we can remove and return an item using the pop() method.
Set being unordered, there is no way of determining which item will be
popped. It is completely arbitrary.
We can also remove all items from a set using clear().
# initialize my_set
# Output: set of unique elements
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 87
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# pop another element
# Output: random element
my_set.pop()
print(my_set)
# clear my_set
#Output: set()
my_set.clear()
print(my_set)
26.3 Python Set Operations
Sets can be used to carry out mathematical set operations like union,
intersection, difference and symmetric difference. We can do this with
operators or methods.
Let us consider the following two sets for the following operations.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 88
26.3.1 Set Union
Union of A and B is a set of all
elements from both sets.
Union is performed using | operator.
Same can be accomplished using the
method union().
[Figure 7: Python Set Union
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
Try the following examples on Python shell.
# use union function
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}
# use union function on B
>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 89
26.3.2 Set Intersection
Intersection of A and B is a set of
elements that are common in both sets.
Intersection is performed
using & operator. Same can be
accomplished using the
method intersection().
[Figure 8: Python Set Intersection
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
# Output: {4, 5}
print(A & B)
Try the following examples on Python shell.
# use intersection function on A
>>> A.intersection(B)
{4, 5}
# use intersection function on B
>>> B.intersection(A)
{4, 5}
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 90
26.3.3 Set Difference
Difference of A and B (A - B) is a set of
elements that are only in A but not in B.
Similarly, B - A is a set of element
in B but not in A.
Difference is performed using - operator.
Same can be accomplished using the
method difference(). Figure 9: Python Set Difference
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
Try the following examples on Python shell
# use difference function on A
>>> A.difference(B)
{1, 2, 3}
# use - operator on B
>>> B - A
{8, 6, 7}
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 91
# use difference function on B
>>> B.difference(A)
{8, 6, 7}
26.3.4 Set Symmetric Difference
Symmetric Difference of A and B is a
set of elements in both A and B except
those that are common in both.
Symmetric difference is performed
using ^ operator. Same can be
accomplished using the method
symmetric_difference(). [Figure 10: Python Set Symmetric Difference
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Try the following examples on Python shell.
# use symmetric_difference function on A
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
# use symmetric_difference function on B
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 92
26.3.5 Different Python Set Methods
There are many set methods, some of which we have already used above.
Here is a list of all the methods that are available with set objects.
Python Set Methods
Method Description
add() Add an element to a set
clear() Remove all elements form a set
copy() Return a shallow copy of a set
difference() Return the difference of two or more sets as a
new set
difference_update() Remove all elements of another set from this
set
discard() Remove an element from set if it is a member.
(Do nothing if the element is not in set)
intersection() Return the intersection of two sets as a new set
intersection_update() Update the set with the intersection of itself and
another
isdisjoint() Return True if two sets have a null intersection
issubset() Return True if another set contains this set
issuperset() Return True if this set contains another set
pop() Remove and return an arbitary set element.
Raise KeyError if the set is empty
remove() Remove an element from a set. If the element
is not a member, raise a KeyError
symmetric_difference() Return the symmetric difference of two sets as
a new set
symmetric_difference_update() Update a set with the symmetric difference of
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 93
itself and another
union() Return the union of sets in a new set
update() Update a set with the union of itself and others
26.3.6 Other Set Operations
26.3.6.1 Set Membership Test
We can test if an item exists in a set or not, using the keyword in.
# initialize my_set
my_set = set("apple")
# check if 'a' is present
# Output: True
print('a' in my_set)
# check if 'p' is present
# Output: False
print('p' not in my_set)
26.3.6.2 Iterating Through a Set
Using a for loop, we can iterate though each item in a set
>>> for letter in set("apple"):
... print(letter)
...
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 94
l
.
26.3.6.3 Built-in Functions with Set
Built-in functions like all(), any(), enumerate(), len(), max(), min(),
sorted(), sum() etc. are commonly used with set to perform different tasks.
Built-in Functions with Set
Function Description
all() Return True if all elements of the set are true (or if the set is
empty).
any() Return True if any element of the set is true. If the set is empty,
return False.
enumerate() Return an enumerate object. It contains the index and value of all
the items of set as a pair.
len() Return the length (the number of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
sorted() Return a new sorted list from elements in the set (does not sort
the set itself).
sum() Retrun the sum of all elements in the set.
26.4 Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements
cannot be changed once assigned. While tuples are immutable lists,
frozensets are immutable sets.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 95
Sets being mutable are unhashable, so they can't be used as dictionary keys.
On the other hand, frozensets are hashable and can be used as keys to a
dictionary.
Frozensets can be created using the function frozenset().
This datatype supports methods like copy(), difference(), intersection(),
isdisjoint(), issubset(), issuperset(), symmetric_difference() and union
(). Being immutable it does not have method that add or remove elements.
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
Try these examples on Python shell
>>> A.isdisjoint(B)
False
>>> A.difference(B)
frozenset({1, 2})
>>> A | B
frozenset({1, 2, 3, 4, 5, 6})
>>> A.add(3)
...
AttributeError: 'frozenset' object has no attribute 'add'
26.5 Dictionary
Each key is separated from its value by a colon (:), the items are separated
by commas, and the whole thing is enclosed in curly braces. An empty
dictionary without any items is written with just two curly braces, like this:
{}.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 96
Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data
type such as strings, numbers, or tuples.
26.5.1 Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets
along with the key to obtain its value. Following is a simple example
#!/usr/bin/python
dict = {‘Name’: ‘Dexlab’, ‘Age’: 12, ‘Class’: ‘Fifth’}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result
dict['Name']: Dexlab
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the
dictionary, we get an error as follows
#!/usr/bin/python
dict = {‘Name’: ‘Dexlab’, ‘Age’: 12, ‘Class’: ‘Fifth’}
print "dict['Alice']: ", dict['Alice']
When the above code is executed, it produces the following result
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 97
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
26.5.2 Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry as shown below in
the simple example
#!/usr/bin/python
dict = {‘Name’: ‘Dexlab’, ‘Age’: 12, ‘Class’: ‘Fifth’}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
When the above code is executed, it produces the following result
dict['Age']: 8
dict['School']: DPS School
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 98
26.5.3 Delete Dictionary Elements
You can either remove individual dictionary elements or clear the entire
contents of a dictionary. You can also delete entire dictionary in a single
operation.
To explicitly remove an entire dictionary, just use the del statement.
Following is a simple example
#!/usr/bin/python
dict = {‘Name’: ‘Dexlab’, ‘Age’: 12, ‘Class’: ‘Fifth’}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
This produces the following result. Note that an exception is raised because
after del dict dictionary does not exist any more
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note: del() method is discussed in subsequent section.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 99
26.5.4 Properties of Dictionary Keys
Dictionary values have no restrictions. They can be any arbitrary Python
object, either standard objects or user-defined objects. However, same is not
true for the keys.
There are two important points to remember about dictionary keys
1. More than one entry per key not allowed. Which means no duplicate
key is allowed. When duplicate keys encountered during assignment,
the last assignment wins. For example
#!/usr/bin/python
dict = {'Name': 'abc', 'Age': 7, 'Name': 'dex'}
print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following result
dict['Name']: dex
2. Keys must be immutable. Which means you can use strings, numbers
or tuples as dictionary keys but something like ['key'] is not allowed.
Following is a simple example
#!/usr/bin/python
dict = {['Name']: 'Dexlab', 'Age': 7}
print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following result
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 100
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Dexlab', 'Age': 7};
TypeError: list objects are unhashable
26.5.5 Built-in Dictionary Functions & Methods
Python includes the following dictionary functions
SN Function with Description
1 cmp(dict1, dict2)
Compares elements of both dict.
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.
Python includes following dictionary methods
SN Methods with Description
1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy()
Returns a shallow copy of dictionary dict
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 101
4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
5 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise
6 dict.items()
Returns a list of dict's (key, value) tuple pairs
7 dict.keys()
Returns list of dictionary dict's keys
8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict
9 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict
10 dict.values()
Returns list of dictionary dict's values
Dictionary function with example
1. cmp
Description
The method cmp() compares two dictionaries based on key and values.
Syntax
Following is the syntax for cmp() method
cmp(dict1, dict2)
Parameters
dict1 -- This is the first dictionary to be compared with dict2.
dict2 -- This is the second dictionary to be compared with dict1.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 102
Return Value
This method returns 0 if both dictionaries are equal, -1 if dict1 < dict2 and 1
if dict1 > dic2.
Example
The following example shows the usage of cmp() method.
#!/usr/bin/python
dict1 = {'Name': 'Dexlab', 'Age': 7};
dict2 = {'Name': ‘Milne’, 'Age': 27};
dict3 = {'Name': 'Vikas', 'Age': 27};
dict4 = {'Name': 'Dexlab', 'Age': 7};
print "Return Value : %d" % cmp (dict1, dict2)
print "Return Value : %d" % cmp (dict2, dict3)
print "Return Value : %d" % cmp (dict1, dict4)
When we run above program, it produces following result
Return Value : -1
Return Value : 1
Return Value : 0
2. len
Description
The method len() gives the total length of the dictionary. This would be
equal to the number of items in the dictionary.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 103
Syntax
Following is the syntax for len() method –
len(dict)
Parameters
dict -- This is the dictionary, whose length needs to be calculated.
Return Value
This method returns the length.
Example
The following example shows the usage of len() method.
#!/usr/bin/python
dict = {'Name': 'Dexlab', 'Age': 7};
print "Length : %d" % len (dict)
When we run above program, it produces following result
Length : 2
3. str
Description
The method str() produces a printable string representation of a dictionary.
Syntax
Following is the syntax for str() method
str(dict)
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 104
Parameters
dict -- This is the dictionary.
Return Value
This method returns string representation.
Example
The following example shows the usage of str() method.
#!/usr/bin/python
dict = {'Name': 'Dexlab', 'Age': 7};
print "Equivalent String : %s" % str (dict)
When we run above program, it produces following result
Equivalent String : {'Age': 7, 'Name': 'Dexlab'}
4. type
Description
The method type() returns the type of the passed variable. If passed variable
is dictionary then it would return a dictionary type.
Syntax
Following is the syntax for type() method
type(dict)
Parameters
dict -- This is the dictionary.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 105
Return Value
This method returns the type of the passed variable.
Example
The following example shows the usage of type() method.
#!/usr/bin/python
dict = {'Name': 'Dexlab', 'Age': 7};
print "Variable Type : %s" % type (dict)
When we run above program, it produces following result
Variable Type : <type 'dict'>
26.6 Python Strings
A string is a sequence of characters.
A character is simply a symbol. For example, the English language has 26
characters.
Computers do not deal with characters, they deal with numbers (binary).
Even though you may see characters on your screen, internally it is stored
and manipulated as a combination of 0's and 1's.
This conversion of character to a number is called encoding, and the reverse
process is decoding. ASCII and Unicode are some of the popular encoding
used.
In Python, string is a sequence of Unicode character. Unicode was introduced
to include every character in all languages and bring uniformity in encoding.
You can learn more about Unicode from here.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 106
26.6.1 How to create a string?
Strings can be created by enclosing characters inside a single quote or double
quotes. Even triple quotes can be used in Python but generally used to
represent multiline strings and docstrings.
# all of the following are equivalent
my_string = 'Dexlab'
print(my_string)
my_string = "Dexlab"
print(my_string)
my_string = '''Dexlab'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Dexlab, welcome to
the world of Python"""
print(my_string)
When you run the program, the output will be:
Dexlab
Dexlab
Dexlab
Dexlab, welcome to
the world of Python
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 107
26.6.2 How to access characters in a string?
We can access individual characters using indexing and a range of characters
using slicing. Index starts from 0. Trying to access a character out of index
range will raise an Index Error. The index must be an integer. We can't use
float or other types, this will result into Type Error.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We
can access a range of items in a string by using the slicing operator (colon).
str = 'Dexlab'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])
#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])
If we try to access index out of the range or use decimal number, we will get
errors.
# index must be in range
>>> my_string[15]
...
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 108
Index Error: string index out of range
# Index must be an integer
>>> my_string[1.5]
...
TypeError: string indices must be integers
Slicing can be best visualized by considering the index to be between the
elements as shown below. If we want to access a range, we need the index that
will slice the portion from the string.
D E X L A B
0 1 2 3 4 5
-5 -4 -3 -2 -1 0
26.6.3 How to change or delete characters in a
string?
Strings are immutable. This means that elements of a string cannot be
changed once it has been assigned. We can simply reassign different strings
to the same name.
>>> my_string = 'Dexlab'
>>> my_string[5] = 'a'
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 109
...
TypeError: 'str' object does not support item assignment
>>> my_string = 'Python'
>>> my_string
'Python'
We cannot delete or remove characters from a string. But deleting the string
entirely is possible using the keyword del.
>>> del my_string[1]
...
TypeError: 'str' object doesn't support item deletion
>>> del my_string
>>> my_string
...
NameError: name 'my_string' is not defined
26.6.4 Python String Operations
There are many operations that can be performed with string which makes it
one of the most used data types in Python.
Concatenation of Two or More Strings
Joining of two or more strings into a single one is called concatenation.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 110
The + operator does this in Python. Simply writing two string literals
together also concatenates them.
The * operator can be used to repeat the string for a given number of times.
str1 = 'Dexlab'
str2 ='World!'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
Writing two string literals together also concatenates them like + operator.
If we want to concatenate strings in different lines, we can use parentheses.
>>> # two string literals together
>>> 'Dexlab ''World!'
'Dexlab World!'
>>> # using parentheses
>>> s = ('Dexlab '
... 'World')
>>> s
'Dexlab World'
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 111
Iterating Through String
Using for loop we can iterate through a string. Here is an example to count
the number of 'l' in a string.
count = 0
for letter in 'Dexlab World':
if(letter == 'l'):
count += 1
print(count,'letters found')
String Membership Test
We can test if a sub string exists within a string or not, using the keyword in.
>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False
Built-in functions to Work with Python
Various built-in functions that work with sequence, works with string as
well.
Some of the commonly used ones are enumerate () and len().
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 112
The enumerate() function returns an enumerate object. It contains the
index and value of all the items in the string as pairs. This can be useful for
iteration.
Similarly, len() returns the length (number of characters) of the string.
str = 'cold'
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
26.6.5 Python String Formatting
Escape Sequence
If we want to print a text like -He said, "What's there?"- we can neither use
single quote or double quotes. This will result into SyntaxError as the text
itself contains both single and double quotes.
>>> print("He said, "What's there?"")
...
SyntaxError: invalid syntax
>>> print('He said, "What's there?"')
...
SyntaxError: invalid syntax
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 113
One way to get around this problem is to use triple quotes. Alternatively, we
can use escape sequences.
An escape sequence starts with a backslash and is interpreted differently. If
we use single quote to represent a string, all the single quotes inside the
string must be escaped. Similar is the case with double quotes. Here is how it
can be done to represent the above text.
# using triple quotes
print('''He said, "What's there?"''')
# escaping single quotes
print('He said, "What\'s there?"')
# escaping double quotes
print("He said, \"What's there?\"")
Here is a list of all the escape sequence supported by Python.
Escape Sequence in Python
Escape Sequence Description
\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quote
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 114
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\Xhh Character with hexadecimal value HH
Here are some examples
>>> print("C:\\Python32\\Lib")
C:\Python32\Lib
>>> print("This is printed\nin two lines")
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 115
This is printed
in two lines
>>> print("This is \x48\x45\x58 representation")
This is HEX representation
Raw String to ignore escape sequence
Sometimes we may wish to ignore the escape sequences inside a string. To do
this we can place r or R in front of the string. This will imply that it is a raw
string and any escape sequence inside it will be ignored.
>>> print("This is \x61 \ngood example")
This is a
good example
>>> print(r"This is \x61 \ngood example")
This is \x61 \ngood example
Old Style formatting
We can even format strings like the old sprintf() style used in C
programming language. We use the % operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 116
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
26.6.6 Common Python String Methods
There are numerous methods available with the string object. The format()
method that we mentioned above is one of them. Some of the commonly used
methods are: lower(), upper(), join(), split(), find(), replace(), etc. Here
is a complete list of all the built-in methods to work with strings in Python.
>>> "Dexlab".lower()
'Dexlab'
>>> "Dexlab".upper()
'DEXLAB'
>>> "This will split all words into a list".split()
['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
>>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
'This will join all words into a string'
>>> 'Happy New Year'.find('ew')
>>> 'Happy New Year'.replace('Happy','Brilliant')
'Brilliant New Year'
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 117
26.7 Python Lists
The most basic data structure in Python is the sequence. Each element of a
sequence is assigned a number - its position or index. The first index is zero,
the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are
lists and tuples, which we would see in this tutorial.
There are certain things you can do with all sequence types. These operations
include indexing, slicing, adding, multiplying, and checking for membership.
In addition, Python has built-in functions for finding the length of a sequence
and for finding its largest and smallest elements.
The list is a most versatile datatype available in Python which can be written
as a list of comma-separated values (items) between square brackets.
Important thing about a list is that items in a list need not be of the same
type.
Creating a list is as simple as putting different comma-separated values
between square brackets. For example
list1 = ['hadoop', 'tableau', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be sliced,
concatenated and so on.
26.7.1 Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the
index or indices to obtain value available at that index. For example
#!/usr/bin/python
list1 = ['hadoop', 'tableau', 1997, 2000];
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 118
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
When the above code is executed, it produces the following result −
list1[0]: hadoop
list2[1:5]: [2, 3, 4, 5]
26.7.2 Updating Lists
You can update single or multiple elements of lists by giving the slice on the
left-hand side of the assignment operator, and you can add to elements in a
list with the append() method. For example
#!/usr/bin/python
list = ['hadoop', 'tableau', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
Note: append() method is discussed in subsequent section.
When the above code is executed, it produces the following result
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 119
Value available at index 2 :
1997
New value available at index 2 :
2001
26.7.3 Delete List Elements
To remove a list element, you can use either the del statement if you know
exactly which element(s) you are deleting or the remove() method if you do
not know. For example
#!/usr/bin/python
list1 = ['hadoop', 'tableau', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
When the above code is executed, it produces following result
['hadoop', 'tableau', 1997, 2000]
After deleting value at index 2 :
['hadoop', 'tableau', 2000]
Note: remove() method is discussed in subsequent section.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 120
26.7.4 Basic List Operations
Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new list, not
a string.
In fact, lists respond to all of the general sequence operations we used on
strings in the prior chapter.
Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 123 Iteration
26.7.5 Indexing, Slicing, and Matrixes
Because lists are sequences, indexing and slicing work the same way for lists
as they do for strings.
Assuming following input
L = ['dexlab', 'Dexlab', 'DEXLAB!']
Python Expression Results Description
L[2] 'DEXLAB!' Offsets start at zero
L[-2] 'Dexlab' Negative: count from the
right
L[1:] ['Dexlab', 'DEXLAB!'] Slicing fetches sections
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 121
26.7.6 Built-in List Functions & Methods
Python includes the following list functions
SN Function with Description
1 cmp(list1, list2)
Compares elements of both lists.
2 len(list)
Gives the total length of the list.
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.
Python includes following list methods
SN Methods with Description
1 list.append(obj)
Appends object obj to list
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 122
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of list, use compare func if given
26.8 Tuple
A tuple is a sequence of immutable Python objects. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples cannot
be changed unlike lists and tuples use parentheses, whereas lists use square
brackets.
Creating a tuple is as simple as putting different comma-separated values.
Optionally you can put these comma-separated values between parentheses
also. For example
tup1 = ('hadoop', 'tableau', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing
tup1 = ();
To write a tuple containing a single value you have to include a comma, even
though there is only one value
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 123
26.8.1 Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with the
index or indices to obtain value available at that index. For example
#!/usr/bin/python
tup1 = ('hadoop', 'tableau', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]
When the above code is executed, it produces the following result
tup1[0]: hadoop
tup2[1:5]: [2, 3, 4, 5]
26.8.2 Updating Tuples
Tuples are immutable which means you cannot update or change the values
of tuple elements. You are able to take portions of existing tuples to create
new tuples as the following example demonstrates
#!/usr/bin/python
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 124
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3
When the above code is executed, it produces the following result
(12, 34.56, 'abc', 'xyz')
26.8.3 Delete Tuple Elements
Removing individual tuple elements is not possible. There is, of course,
nothing wrong with putting together another tuple with the undesired
elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example:
#!/usr/bin/python
tup = ('hadoop', 'tableau', 1997, 2000);
print tup
del tup;
print "After deleting tup : "
print tup
This produces the following result. Note an exception raised, this is because
after del tup tuple does not exist any more
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 125
('hadoop', 'tableau', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
26.8.4 Basic Tuples Operations
Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new tuple,
not a string.
In fact, tuples respond to all of the general sequence operations we used on
strings in the prior chapter
Python Expression Results Description
len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1, 2, 3) True Membership
for x in (1, 2, 3): print x, 123 Iteration
26.8.5 Indexing, Slicing, and Matrixes
Because tuples are sequences, indexing and slicing work the same way for
tuples as they do for strings. Assuming following input
L = ('dexlab', 'Dexlab', 'DEXLAB!')
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 126
Python Expression Results Description
L[2] 'DEXLAB!' Offsets start at zero
L[-2] 'Dexlab' Negative: count from the
right
L[1:] ['Dexlab', 'DEXLAB!'] Slicing fetches sections
26.8.6 No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying
symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples,
as indicated in these short examples
#!/usr/bin/python
print 'abc', -4.24e93, 18+6.6j, 'xyz'
x, y = 1, 2;
print "Value of x , y : ", x,y
When the above code is executed, it produces the following result
abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2
26.8.7 Built-in Tuple Functions
Python includes the following tuple functions
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 26: DATA STRUCTURE | 127
SN Function with Description
1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 27: PYTHON FUNCTIONS | 128
Python CHAPTER
Functions 27
In Python, function is a group of related statements that perform a specific
task.
Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
Furthermore, it avoids repetition and makes code reusable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition which consists of following components.
1. Keyword def marks the start of function header.
2. A function name to uniquely identify it. Function naming follows the
same rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function.
They are optional.
4. A colon (:) to mark the end of function header.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 27: PYTHON FUNCTIONS | 129
5. Optional documentation string (docstring) to describe what the
function does.
6. One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
Example of a function
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
27.1 Function Call
Once we have defined a function, we can call it from another function,
program or even the Python prompt. To call a function we simply type the
function name with appropriate parameters.
>>> greet('Paul')
Hello, Paul. Good morning!
Note: Try running the above code into the Python shell to see the output.
27.2 Docstring
The first string after the function header is called the docstring and is short
for documentation string. It is used to explain in brief, what a function does.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 27: PYTHON FUNCTIONS | 130
Although optional, documentation is a good programming practice. Unless
you can remember what you had for dinner last week, always document your
code.
In the above example, we have a docstring immediately below the function
header. We generally use triple quotes so that docstring can extend up to
multiple lines. This string is available to us as __doc__ attribute of the
function.
For example
Try running the following into the Python shell to see the output.
>>> print(greet.__doc__)
This function greets to
the person passed into the
name parameter
27.3 The return statement
The return statement is used to exit a function and go back to the place from
where it was called.
Syntax of return:
return [expression_list]
This statement can contain expression which gets evaluated and the value is
returned. If there is no expression in the statement or the return statement
itself is not present inside a function, then the function will return
the None object.
For example:
>>> print(greet("May"))
Hello, May. Good morning!
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 27: PYTHON FUNCTIONS | 131
None
Here, None is the returned value.
Example:
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
# Output: 2
print(absolute_value(2))
# Output: 4
print(absolute_value(-4))
27.4 How Function works in Python?
Figure 11: Flow of control for a Function
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 27: PYTHON FUNCTIONS | 132
27.5 Scope and lifetime of variables
Scope of a variable is the portion of a program where the variable is
recognized. Parameters and variables defined inside a function is not visible
from outside. Hence, they have a local scope.
Lifetime of a variable is the period throughout which the variable exits in the
memory. The lifetime of variables inside a function is as long as the function
executes.
They are destroyed once we return from the function. Hence, a function does
not remember the value of a variable from its previous calls.
Here is an example to illustrate the scope of a variable inside a function.
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output
Value inside function: 10
Value outside function: 20
Here, we can see that the value of x is 20 initially. Even though the
function my_func() changed the value of x to 10, it did not effect the value
outside the function.
This is because the variable x inside the function is different (local to the
function) from the one outside. Although they have same names, they are two
different variables with different scope.
On the other hand, variables outside of the function are visible from inside.
They have a global scope.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 27: PYTHON FUNCTIONS | 133
We can read these values from inside the function but cannot change (write)
them. In order to modify the value of variables outside the function, they
must be declared as global variables using the keyword global.
27.6 Types of Functions
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.
27.7 Python Programming Built-in
Functions
There are a number of functions that are always available to use. These
functions are known as built-in functions in Python.
Figure 12: Python function types
A function is a group of statements that perform a specific task. They can
either be user-defined or already built into Python interpreter.
Functions that come built into the Python language itself are called built-in
functions and are readily available to us.
Functions like print(), input(), eval() etc. that we have been using, are some
examples of the built-in function. There are 68 built-in functions defined in
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 27: PYTHON FUNCTIONS | 134
Python 3.5.2. They are listed below alphabetically along with a brief
description.
Python built-in Functions
Built-in
Description
Function
abs() Return the absolute value of a number.
all() Return True if all elements of the iterable are true (or if the
iterable is empty).
any() Return True if any element of the iterable is true. If the iterable is
empty, return False.
ascii() Return a string containing a printable representation of an object,
but escape the non-ASCII characters.
bin() Convert an integer number to a binary string.
bool() Convert a value to a Boolean.
bytearray() Return a new array of bytes.
bytes() Return a new "bytes" object.
callable() Return True if the object argument appears callable, False if not.
chr() Return the string representing a character.
classmethod() Return a class method for the function.
compile() Compile the source into a code or AST object.
complex() Create a complex number or convert a string or number to a
complex number.
delattr() Deletes the named attribute of an object.
dict() Create a new dictionary.
dir() Return the list of names in the current local scope.
divmod() Return a pair of numbers consisting of quotient and remainder
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 27: PYTHON FUNCTIONS | 135
when using integer division.
enumerate() Return an enumerate object.
eval() The argument is parsed and evaluated as a Python expression.
exec() Dynamic execution of Python code.
filter() Construct an iterator from elements of iterable for which function
returns true.
float() Convert a string or a number to floating point.
format() Convert a value to a "formatted" representation.
frozenset() Return a new frozenset object.
getattr() Return the value of the named attribute of an object.
globals() Return a dictionary representing the current global symbol table.
hasattr() Return True if the name is one of the object's attributes.
hash() Return the hash value of the object.
help() Invoke the built-in help system.
hex() Convert an integer number to a hexadecimal string.
id() Return the "identity" of an object.
input() Reads a line from input, converts it to a string (stripping a trailing
newline), and returns that.
int() Convert a number or string to an integer.
isinstance() Return True if the object argument is an instance.
issubclass() Return True if class is a subclass.
iter() Return an iterator object.
len() Return the length (the number of items) of an object.
list() Return a list.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 27: PYTHON FUNCTIONS | 136
locals() Update and return a dictionary representing the current local
symbol table.
map() Return an iterator that applies function to every item of iterable,
yielding the results.
max() Return the largest item in an iterable.
memoryview() Return a "memory view" object created from the given argument.
min() Return the smallest item in an iterable.
next() Retrieve the next item from the iterator.
object() Return a new featureless object.
oct() Convert an integer number to an octal string.
open() Open file and return a corresponding file object.
ord() Return an integer representing the Unicode.
pow() Return power raised to a number.
print() Print objects to the stream.
property() Return a property attribute.
range() Return an iterable sequence.
repr() Return a string containing a printable representation of an object.
reversed() Return a reverse iterator.
round() Return the rounded floating point value.
set() Return a new set object.
setattr() Assigns the value to the attribute.
slice() Return a slice object.
sorted() Return a new sorted list.
staticmethod() Return a static method for function.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 27: PYTHON FUNCTIONS | 137
str() Return a str version of object.
sum() Sums the items of an iterable from left to right and returns the
total.
super() Return a proxy object that delegates method calls to a parent or
sibling class.
tuple() Return a tuple
type() Return the type of an object.
vars() Return the __dict__ attribute for a module, class, instance, or
any other object.
zip() Make an iterator that aggregates elements from each of the
iterables.
__import__() This function is invoked by the import statement.
27.8 Python User-defined Functions
In this tutorial, you will find the advantages of using user-defined functions
and best practices to follow.
Functions that we define ourselves to do certain specific task are referred as
user-defined functions. The way in which we define and call functions in
Python are already discussed.
Functions that readily come with Python are called built-in functions. If we
use functions written by others in the form of library, it can be termed as
library functions.
All the other functions that we write on our own fall under user-defined
functions. So, our user-defined function could be a library function to
someone else.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 27: PYTHON FUNCTIONS | 138
Advantages of user-defined functions
1. User-defined functions help to decompose a large program into small
segments which makes program easy to understand, maintain and
debug.
2. If repeated code occurs in a program. Function can be used to include
those codes and execute when needed by calling that function.
3. Programmars working on large project can divide the workload by
making different functions.
Example of a user-defined function
# Program to illustrate
# the use of user-defined functions
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
print("The sum is", add_numbers(num1, num2))
Output
Enter a number: 2.4
Enter another number: 6.5
The sum is 8.9
Here, we have defined the function my_addition() which adds two numbers
and returns the result.
This is our user-defined function. We could have multiplied the two numbers
inside our function (it's all up to us). But this operation would not be
consistent with the name of the function. It would create ambiguity.
It is always a good idea to name functions according to the task they perform.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 27: PYTHON FUNCTIONS | 139
In the above example, input(), print() and float() are built-in functions of
the Python programming language.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 28: PYTHON MODULES | 140
CHAPTER
Python
Modules
28
In this topic, you will learn to create and import custom modules in Python.
Also, you will find different techniques to import and use custom and built-in
modules in Python.
Figure 13: Python Module
Modules refer to a file containing Python statements and definitions.
A file containing Python code, for e.g.: example.py, is called a module and its
module name would be example.
We use modules to break down large programs into small manageable and
organized files. Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of
copying their definitions into different programs.
Let us create a module. Type the following and save it as example.py.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 28: PYTHON MODULES | 141
# Python Module example
def add(a, b):
"""This program adds two
numbers and return the result"""
result = a + b
return result
Here, we have defined a function add() inside a module named example.
The function takes in two numbers and returns their sum.
28.1 How to import modules in Python?
We can import the definitions inside a module to another module or the
interactive interpreter in Python.
We use the import keyword to do this. To import our previously defined
module example we type the following in the Python prompt.
>>> import example
This does not enter the names of the functions defined in example directly in
the current symbol table. It only enters the module name example there.
Using the module name we can access the function using dot (.) operation.
For example:
>>> example.add(4,5.5)
9.5
Python has a ton of standard modules available.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 28: PYTHON MODULES | 142
You can check out the full list of Python standard modules and what they are
for. These files are in the Lib directory inside the location where you installed
Python.
Standard modules can be imported the same way as we import our user-
defined modules.
There are various ways to import modules. They are listed as follows.
28.2 Python import statement
We can import a module using import statement and access the definitions
inside it using the dot operator as described above. Here is an example.
# import statement example
# to import standard module math
import math
print("The value of pi is", math.pi)
When you run the program, the output will be:
The value of pi is 3.141592653589793
28.3 Import with renaming
We can import a module by renaming it as follows.
# import module by renaming it
import math as m
print("The value of pi is", m.pi)
We have renamed the math module as m. This can save us typing time in
some cases.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 28: PYTHON MODULES | 143
Note that the name math is not recognized in our scope. Hence, math.pi is
invalid, m.pi is the correct implementation.
28.4 Python from...import statement
We can import specific names form a module without importing the module
as a whole. Here is an example.
# import only pi from math module
from math import pi
print("The value of pi is", pi)
We imported only the attribute pi form the module.
In such case we don't use the dot operator. We could have imported multiple
attributes as follows.
>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045
28.5 Import all names
We can import all names (definitions) form a module using the following
construct.
# import all names form
# the standard module math
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 28: PYTHON MODULES | 144
from math import *
print("The value of pi is", pi)
We imported all the definitions from the math module. This makes all names
except those beginnig with an underscore, visible in our scope.
Importing everything with the asterisk (*) symbol is not a good programming
practice. This can lead to duplicate definitions for an identifier. It also
hampers the readability of our code.
28.6 Python Module Search Path
While importing a module, Python looks at several places. Interpreter first
looks for a built-in module then (if not found) into a list of directories defined
in sys.path. The search is in this order.
The current directory.
PYTHONPATH (an environment variable with a list of directory).
The installation-dependent default directory.
>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
We can add modify this list to add our own path.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 28: PYTHON MODULES | 145
Reloading a module
The Python interpreter imports a module only once during a session. This
makes things more efficient. Here is an example to show how this works.
Suppose we have the following code in a module named my_module.
# This module shows the effect of
# multiple imports and reload
print("This code got executed")
Now we see the effect of multiple imports.
>>> import my_module
This code got executed
>>> import my_module
>>> import my_module
We can see that our code got executed only once. This goes to say that our
module was imported only once.
Now if our module changed during the course of the program, we would have
to reload it. One way to do this is to restart the interpreter. But this does not
help much.
Python provides a neat way of doing this. We can use the reload() function
inside the imp module to reload a module. This is how its done.
>>> import imp
>>> import my_module
This code got executed
>>> import my_module
>>> imp.reload(my_module)
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 28: PYTHON MODULES | 146
This code got executed
<module 'my_module' from '.\\my_module.py'>
28.7 The dir() built-in function
We can use the dir() function to find out names that are defined inside a
module.
For example, we have defined a function add() in the module example that
we had in the beginning.
>>> dir(example)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__initializing__',
'__loader__',
'__name__',
'__package__',
'add']
Here, we can see a sorted list of names (along with add). All other names that
begin with an underscore are default Python attributes associated with the
module (we did not define them ourself).
For example, the __name__ attribute contains the name of the module.
>>> import example
>>> example.__name__
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 28: PYTHON MODULES | 147
'example'
All the names defined in our current namespace can be found out using
the dir() function without any arguments.
>>> a = 1
>>> b = "hello"
>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'math', 'pyscripter']
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 29: PYTHON FILE I/O | 148
Python
CHAPTER
File I/O 29
In this topic, you'll learn about Python file operations. More specifically,
opening a file, reading from it, writing into it, closing it and various file
methods you should be aware of.
File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when
computer is turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When
we are done, it needs to be closed, so that resources that are tied with the file
are freed.
Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 29: PYTHON FILE I/O | 149
29.1 Opening a file
Python has a built-in function open() to open a file. This function returns a
file object, also called a handle, as it is used to read or modify the file
accordingly.
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/Python33/README.txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we
want to read 'r', write 'w' or append 'a' to the file. We also specify if we want
to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when
reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used
when dealing with non-text files like image or exe files.
Python File Modes
Mode Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or
truncates the file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the
operation fails.
'a' Open for appending at the end of the file without truncating it.
Creates a new file if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 29: PYTHON FILE I/O | 150
f = open("test.txt") # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
Unlike other languages, the character 'a' does not imply the number 97 until
it is encoded using ASCII (or other equivalent encodings).
Moreover, the default encoding is platform dependent. In windows, it is
'cp1252' but 'utf-8' in Linux.
So, we must not also rely on the default encoding or else our code will behave
differently in different platforms.
Hence, when working with files in text mode, it is highly recommended to
specify the encoding type.
f = open("test.txt",mode = 'r',encoding = 'utf-8')
29.2 Closing a File
When we are done with operations to the file, we need to properly close it.
Closing a file will free up the resources that were tied with the file and is
done using the close() method.
Python has a garbage collector to clean up unreferenced objects but, we must
not rely on it to close the file.
f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
This method is not entirely safe. If an exception occurs when we are
performing some operation with the file, the code exits without closing the
file.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 29: PYTHON FILE I/O | 151
A safer way is to use a try...finally block.
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
This way, we are guaranteed that the file is properly closed even if an
exception is raised, causing program flow to stop.
The best way to do this is using the with statement. This ensures that the
file is closed when the block inside with is exited.
We don't need to explicitly call the close() method. It is done internally.
with open("test.txt",encoding = 'utf-8') as f:
# perform file operations
29.3 Writing to a File
In order to write into a file we need to open it in write 'w', append 'a' or
exclusive creation 'x' mode.
We need to be careful with the 'w' mode as it will overwrite into the file if it
already exists. All previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write()
method. This method returns the number of characters written to the file.
with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my first file\n")
f.write("This file\n\n")
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 29: PYTHON FILE I/O | 152
f.write("contains three lines\n")
This program will create a new file named 'test.txt' if it does not exist. If it
does exist, it is overwritten.
We must include the newline characters ourselves to distinguish different
lines.
29.4 Reading from a File
To read the content of a file, we must open the file in reading mode.
There are various methods available for this purpose. We can use the
read(size) method to read in size number of data. If size parameter is not
specified, it reads and returns up to the end of the file.
>>> f = open("test.txt",'r',encoding = 'utf-8')
>>> f.read(4) # read the first 4 data
'This'
>>> f.read(4) # read the next 4 data
' is '
>>> f.read() # read in the rest till end of file
'my first file\nThis file\ncontains three lines\n'
>>> f.read() # further reading returns empty sting
''
We can see, that read() method returns newline as '\n'. Once the end of file is
reached, we get empty string on further reading.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 29: PYTHON FILE I/O | 153
We can change our current file cursor (position) using the seek() method.
Similarly, the tell() method returns our current position (in number of bytes).
>>> f.tell() # get the current file position
56
>>> f.seek(0) # bring file cursor to initial position
>>> print(f.read()) # read the entire file
This is my first file
This file
contains three lines
We can read a file line-by-line using a for loop. This is both efficient and fast.
>>> for line in f:
... print(line, end = '')
...
This is my first file
This file
contains three lines
The lines in file itself has a newline character '\n'.
Moreover,the print() end parameter to avoid two newlines when printing.
Alternately, we can use readline() method to read individual lines of a file.
This method reads a file till the newline, including the newline character.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 29: PYTHON FILE I/O | 154
>>> f.readline()
'This is my first file\n'
>>> f.readline()
'This file\n'
>>> f.readline()
'contains three lines\n'
>>> f.readline()
''
Lastly, the readlines() method returns a list of remaining lines of the entire
file. All these reading method return empty values when end of file (EOF) is
reached.
>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']
29.5 Python File Methods
There are various methods available with the file object. Some of them have
been used in above examples.
Here is the complete list of methods in text mode with a brief description.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 29: PYTHON FILE I/O | 155
Python File Methods
Method Description
close() Close an open file. It has no effect if the file is
already closed.
detach() Separate the underlying binary buffer from
the TextIOBase and return it.
fileno() Return an integer number (file descriptor) of the
file.
flush() Flush the write buffer of the file stream.
isatty() Return True if the file stream is interactive.
read(n) Read atmost n characters form the file. Reads till
end of file if it is negative or None.
readable() Returns True if the file stream can be read from.
readline(n=-1) Read and return one line from the file. Reads in
at most n bytes if specified.
readlines(n=-1) Read and return a list of lines from the file.
Reads in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Change the file position to offset bytes, in
reference to from (start, current, end).
seekable() Returns True if the file stream supports random
access.
tell() Returns the current file location.
truncate(size=None) Resize the file stream to size bytes. If size is not
specified, resize to current location.
writable() Returns True if the file stream can be written to.
write(s) Write string s to the file and return the number of
characters written.
writelines(lines) Write a list of lines to the file.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 29: PYTHON FILE I/O | 156
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 30: PYTHON DIRECTORY AND FILE MANAGEMENT | 157
CHAPTER
Python
Directory
30
and File Management
In this topic, you'll learn about file and directory management in Python, i.e.
creating a directory, renaming it, listing all directories and working with
them.
If there are a large number of files to handle in your Python program, you can
arrange your code within different directories to make things more
manageable.
A directory or folder is a collection of files and sub directories. Python has
the os module, which provides us with many useful methods to work with
directories (and files as well).
30.1 Get Current Directory
We can get the present working directory using the getcwd() method.
This method returns the current working directory in the form of a string. We
can also use the getcwdb() method to get it as bytes object.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 30: PYTHON DIRECTORY AND FILE MANAGEMENT | 158
>>> import os
>>> os.getcwd()
'C:\\Program Files\\PyScripter'
>>> os.getcwdb()
b'C:\\Program Files\\PyScripter'
The extra backslash implies escape sequence. The print() function will
render this properly.
>>> print(os.getcwd())
C:\Program Files\PyScripter
30.2 Changing Directory
We can change the current working directory using the chdir() method.
The new path that we want to change to must be supplied as a string to this
method. We can use both forward slash (/) or the backward slash (\) to
separate path elements.
It is safer to use escape sequence when using the backward slash.
>>> os.chdir('C:\\Python33')
>>> print(os.getcwd())
C:\Python33
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 30: PYTHON DIRECTORY AND FILE MANAGEMENT | 159
30.3 List Directories and Files
All files and sub directories inside a directory can be known using the
listdir() method.
This method takes in a path and returns a list of sub directories and files in
that path. If no path is specified, it returns from the current working
directory.
>>> print(os.getcwd())
C:\Python33
>>> os.listdir()
['DLLs',
'Doc',
'include',
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']
>>> os.listdir('G:\\')
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 30: PYTHON DIRECTORY AND FILE MANAGEMENT | 160
['$RECYCLE.BIN',
'Movies',
'Music',
'Photos',
'Series',
'System Volume Information']
30.4 Making a New Directory
We can make a new directory using the mkdir() method.
This method takes in the path of the new directory. If the full path is not
specified, the new directory is created in the current working directory.
>>> os.mkdir('test')
>>> os.listdir()
['test']
30.5 Renaming a Directory or a File
The rename() method can rename a directory or a file.
The first argument is the old name and the new name must be supplies as
the second argument.
>>> os.listdir()
['test']
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 30: PYTHON DIRECTORY AND FILE MANAGEMENT | 161
>>> os.rename('test','new_one')
>>> os.listdir()
['new_one']
30.6 Removing Directory or File
A file can be removed (deleted) using the remove() method.
Similarly, the rmdir() method removes an empty directory.
>>> os.listdir()
['new_one', 'old.txt']
>>> os.remove('old.txt')
>>> os.listdir()
['new_one']
>>> os.rmdir('new_one')
>>> os.listdir()
[]
However, note that rmdir() method can only remove empty directories.
In order to remove a non-empty directory we can use the rmtree() method
inside the shutil module.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 30: PYTHON DIRECTORY AND FILE MANAGEMENT | 162
>>> os.listdir()
['test']
>>> os.rmdir('test')
Traceback (most recent call last):
...
OSError: [WinError 145] The directory is not empty: 'test'
>>> import shutil
>>> shutil.rmtree('test')
>>> os.listdir()
[]
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 31: PYTHON ERRORS AND BUILT-IN EXCEPTIONS | 163
Python Errors CHAPTER
and Built-in 31
Exceptions
Python (interpreter) raises exceptions when it encounter errors. For example:
divided by zero. In this topic, you will learn about different exceptions that
are built-in in Python.
When writing a program, we, more often than not, will encounter errors.
Error caused by not following the proper structure (syntax) of the language is
called syntax error or parsing error.
>>> if a < 3
File "<interactive input>", line 1
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 31: PYTHON ERRORS AND BUILT-IN EXCEPTIONS | 164
if a < 3
SyntaxError: invalid syntax
We can notice here that a colon is missing in the if statement.
Errors can also occur at runtime and these are called exceptions. They occur,
for example, when a file we try to open does not exist (FileNotFoundError),
dividing a number by zero (ZeroDivisionError), module we try to import is not
found (ImportError) etc.
Whenever these type of runtime error occur, Python creates an exception
object. If not handled properly, it prints a traceback to that error along with
some details about why that error occurred.
>>> 1 / 0
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero
>>> open("imaginary.txt")
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 31: PYTHON ERRORS AND BUILT-IN EXCEPTIONS | 165
31.1 Python Built-in Exceptions
Illegal operations can raise exceptions. There are plenty of built-in exceptions
in Python that are raised when corresponding errors occur. We can view all
the built-in exceptions using the local() built-in functions as follows.
>>> locals()['__builtins__']
This will return us a dictionary of built-in exceptions, functions and
attributes.
Some of the common built-in exceptions in Python programming along with
the error that cause then are tabulated below.
Python Built-in Exceptions
Exception Cause of Error
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() functions hits end-of-file
condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator's close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or
delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or global
scope.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 31: PYTHON ERRORS AND BUILT-IN EXCEPTIONS | 166
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related
error.
OverflowError Raised when result of an arithmetic operation is too
large to be represented.
ReferenceError Raised when a weak reference proxy is used to access
a garbage collected referent.
RuntimeError Raised when an error does not fall under any other
category.
StopIteration Raised by next() function to indicate that there is no
further item to be returned by iterator.
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs
and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied to an
object of incorrect type.
UnboundLocalError Raised when a reference is made to a local variable in a
function or method, but no value has been bound to that
variable.
UnicodeError Raised when a Unicode-related encoding or decoding
error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during
encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during
decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 31: PYTHON ERRORS AND BUILT-IN EXCEPTIONS | 167
translating.
ValueError Raised when a function gets argument of correct type
but improper value.
ZeroDivisionError Raised when second operand of division or modulo
operation is zero.
We can also define our own exception in Python (if required). Visit this page
to learn more about user-defined exceptions.
We can handle these built-in and user-defined exceptions in Python using try,
except and finally statements.
31.2 Python Exception Handling –
Try, Except and Finally
In this topic, you'll learn how to handle exceptions in your Python program
using try, except and finally statements. This will motivate you to write
clean, readable and efficient code in Python.
Figure 13: Python exception handling
Python has many built-in exceptions which forces your program to output an
error when something in it goes wrong.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 31: PYTHON ERRORS AND BUILT-IN EXCEPTIONS | 168
When these exceptions occur, it causes the current process to stop and passes
it to the calling process until it is handled. If not handled, our program will
crash.
For example, if function A calls function B which in turn calls function C and
an exception occurs in function C. If it is not handled in C, the exception
passes to B and then to A.
If never handled, an error message is spit out and our program come to a
sudden, unexpected halt.
31.3 Catching Exceptions in Python
In Python, exceptions can be handled using a try statement.
A critical operation which can raise exception is placed inside the try clause
and the code that handles exception is written in except clause.
It is up to us, what operations we perform once we have caught the exception.
Here is a simple example.
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 31: PYTHON ERRORS AND BUILT-IN EXCEPTIONS | 169
print()
print("The reciprocal of",entry,"is",r)
Output
The entry is a
Oops! <class 'ValueError'> occured.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError' > occured.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5
In this program, we loop until the user enters an integer that has a valid
reciprocal. The portion that can cause exception is placed inside try block.
If no exception occurs, except block is skipped and normal flow continues. But
if any exception occurs, it is caught by the except block.
Here, we print the name of the exception using ex_info() function
inside sys module and ask the user to try again. We can see that the values
'a' and '1.3' causes ValueError and '0' causes ZeroDivisionError.
Catching Specific Exceptions in Python
In the above example, we did not mention any exception in the except clause.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 31: PYTHON ERRORS AND BUILT-IN EXCEPTIONS | 170
This is not a good programming practice as it will catch all exceptions and
handle every case in the same way. We can specify which exceptions an
except clause will catch.
A try clause can have any number of except clause to handle them differently
but only one will be executed in case an exception occurs.
We can use a tuple of values to specify multiple exceptions in an except
clause. Here is an example pseudo code.
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
Pass
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 31: PYTHON ERRORS AND BUILT-IN EXCEPTIONS | 171
31.4 Raising Exceptions
In Python programming, exceptions are raised when corresponding errors
occur at run time, but we can forcefully raise it using the keyword raise.
We can also optionally pass in value to the exception to clarify why that
exception was raised.
>>> raise KeyboardInterrupt
Traceback (most recent call last):
...
KeyboardInterrupt
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument
>>> try:
... a = int(input("Enter a positive integer: "))
... if a <= 0:
... raise ValueError("That is not a positive number!")
... except ValueError as ve:
... print(ve)
...
Enter a positive integer: -2
That is not a positive number!
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 31: PYTHON ERRORS AND BUILT-IN EXCEPTIONS | 172
31.5 try...finally
The try statement in Python can have an optional finally clause. This clause
is executed no matter what, and is generally used to release external
resources.
For example, we may be connected to a remote data center through the
network or working with a file or working with a Graphical User Interface
(GUI).
In all these circumstances, we must clean up the resource once used, whether
it was successful or not. These actions (closing a file, GUI or disconnecting
from network) are performed in the finally clause to guarantee execution.
Here is an example of file operations to illustrate this.
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
This type of construct makes sure the file is closed even if an exception
occurs.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 32: PYTHON NAMESPACE AND SCOPE | 173
CHAPTER
Python
Namespace
32
and Scope
In this topic, you will learn about namespace; mapping from names to objects
and, scope of a variable.
If you have ever read 'The Zen of Python' (type "import this" in Python
interpreter), the last line states, Namespaces are one honking great idea
-- let's do more of those! So what are these mysterious namespaces? Let us
first look at what name is.
Name (also called identifier) is simply a name given to objects. Everything in
Python is an object. Name is a way to access the underlying object.
For example, when we do the assignment a = 2, here 2 is an object stored in
memory and a is the name we associate it with. We can get the address (in
RAM) of some object through the built-in function, id(). Let's check it.
# Note: You may get different value of id
a=2
# Output: id(2)= 10919424
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 32: PYTHON NAMESPACE AND SCOPE | 174
print('id(2) =', id(2))
# Output: id(a) = 10919424
print('id(a) =', id(a))
Here, both refer to the same object. Let's make things a little more
interesting.
# Note: You may get different value of id
a=2
# Output: id(a) = 10919424
print('id(a) =', id(a))
a = a+1
# Output: id(a) = 10919456
print('id(a) =', id(a))
# Output: id(3) = 10919456
print('id(3) =', id(3))
b=2
# Output: id(2)= 10919424
print('id(2) =', id(2))
What is happening in the above sequence of steps? A diagram will help us
explain this.
Initially, an object 2 is created and the name a is associated with it, when we
do a = a+1, a new object 3 is created and now a associates with this object.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 32: PYTHON NAMESPACE AND SCOPE | 175
Note that id(a) and id(3) have same values.
Furthermore, when we do b = 2, the new name b gets associated with the
previous object 2.
This is efficient as Python doesn't have to create a new duplicate object. This
dynamic nature of name binding makes Python powerful; a name could refer
to any type of object.
>>> a = 5
>>> a = 'Hello World!'
>>> a = [1,2,3]
All these are valid and a will refer to three different types of object at
different instances. Functions are objects too, so a name can refer to them as
well.
def printHello():
print("Hello")
a = printHello()
# Output: Hello
Our same name a can refer to a function and we can call the function through
it, pretty neat.
32.1 What is a namespace?
So now that we understand what names are, we can move on to the concept of
namespaces.
To simply put it, namespace is a collection of names.
In Python, you can imagine a namespace as a mapping of every name, you
have defined, to corresponding objects.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 32: PYTHON NAMESPACE AND SCOPE | 176
Different namespaces can co-exist at a given time but are completely isolated.
A namespace containing all the built-
in names is created when we start the
Python interpreter and exists as long
we don't exit.
This is the reason that built-in
functions like id(), print() etc. are
always available to us from any part of
the program. Each module creates its
own global namespace.
These different namespaces are
isolated. Hence, the same name that
may exist in different modules do not
collide.
Modules can have various functions
Figure 14: Python Namespace
and classes. A local namespace is
created when a function is called,
which has all the names defined in it.
Similar, is the case with class.
Following diagram may help to clarify
this concept.
32.2 Python Variable Scope
Although there are various unique namespaces defined, we may not be able
to access all of them from every part of the program. The concept of scope
comes into play.
Scope is the portion of the program from where a namespace can be accessed
directly without any prefix.
At any given moment, there are at least three nested scopes.
1. Scope of the current function which has local names
2. Scope of the module which has global names
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 32: PYTHON NAMESPACE AND SCOPE | 177
3. Outermost scope which has built-in names
When a reference is made inside a function, the name is searched in the local
namespace, then in the global namespace and finally in the built-in
namespace.
If there is a function inside another function, a new scope is nested inside the
local scope.
Example of Scope and Namespace in Python
def outer_function():
b = 20
def inner_func():
c = 30
a = 10
Here, the variable a is in the global namespace. Variable b is in the local
namespace of outer_function() and c is in the nested local namespace
of inner_function().
When we are in inner_function(), c is local to us, b is nonlocal and a is global.
We can read as well as assign new values to c but can only
read b and c from inner_function().
If we try to assign as a value to b, a new variable b is created in the local
namespace which is different than the nonlocal b. Same thing happens when
we assign a value to a.
However, if we declare a as global, all the reference and assignment go to the
global a. Similarly, if we want to rebind the variable b, it must be declared as
nonlocal. The following example will further clarify this.
def outer_function():
a = 20
def inner_function():
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 32: PYTHON NAMESPACE AND SCOPE | 178
a = 30
print('a =',a)
inner_function()
print('a =',a)
a = 10
outer_function()
print('a =',a)
As you can see, the output of this program is
a = 30
a = 20
a = 10
In this program, three different variables a are defined in separate
namespaces and accessed accordingly. While in the following program,
def outer_function():
global a
a = 20
def inner_function():
global a
a = 30
print('a =',a)
inner_function()
print('a =',a)
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 32: PYTHON NAMESPACE AND SCOPE | 179
a = 10
outer_function()
print('a =',a)
The output of the program is.
a = 30
a = 30
a = 30
Here, all reference and assignment are to the global a due to the use of
keyword global.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 33: PYTHON OBJECTS AND CLASSES | 180
CHAPTER
Python
Objects
33
and Classes
In this topic, you'll learn about the core functionality of Python, Python
objects and classes. You'll learn what a class is, how to create it and use it in
your program.
Python is an object oriented programming language. Unlike procedure
oriented programming, where the main emphasis is on functions, object
oriented programming stress on objects.
Object is simply a collection of data (variables) and methods (functions) that
act on those data. And, class is a blueprint for the object.
We can think of class as a sketch (prototype) of a house. It contains all the
details about the floors, doors, windows etc. Based on these descriptions we
build the house. House is the object.
As, many houses can be made from a description, we can create many objects
from a class. An object is also called an instance of a class and the process of
creating this object is called instantiation.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 33: PYTHON OBJECTS AND CLASSES | 181
33.1 Defining a Class in Python
Like function definitions begin with the keyword def, in Python, we define a
class using the keyword class.
The first string is called docstring and has a brief description about the
class. Although not mandatory, this is recommended.
Here is a simple class definition.
class MyNewClass:
'''This is a docstring. I have created a new class'''
Pass
A class creates a new local namespace where all its attributes are defined.
Attributes may be data or functions.
There are also special attributes in it that begins with double underscores
(__). For example, __doc__ gives us the docstring of that class.
As soon as we define a class, a new class object is created with the same
name. This class object allows us to access the different attributes as well as
to instantiate new objects of that class.
class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello')
# Output: 10
print(MyClass.a)
# Output: <function MyClass.func at 0x0000000003079BF8>
print(MyClass.func)
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 33: PYTHON OBJECTS AND CLASSES | 182
# Output: 'This is my second class'
print(MyClass.__doc__)
When you run the program, the output will be:
10
<function 0x7feaa932eae8="" at="" myclass.func="">
This is my second class
33.2 Creating an Object in Python
We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class.
The procedure to create an object is similar to a function call.
>>> ob = MyClass()
This will create a new instance object named ob. We can access attributes of
objects using the object name prefix.
Attributes may be data or method. Method of an object are corresponding
functions of that class. Any function object that is a class attribute defines a
method for objects of that class.
This means to say, since MyClass.func is a function object (attribute of
class), ob.func will be a method object.
class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello')
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 33: PYTHON OBJECTS AND CLASSES | 183
# create a new MyClass
ob = MyClass()
# Output: <function MyClass.func at 0x000000000335B0D0>
print(MyClass.func)
# Output: <bound method MyClass.func of <__main__.MyClass object at
0x000000000332DEF0>>
print(ob.func)
# Calling function func()
# Output: Hello
ob.func()
You may have noticed the self parameter in function definition inside the
class but, we called the method simply as ob.func() without any arguments.
It still worked.
This is because, whenever an object calls its method, the object itself is
passed as the first argument. So, ob.func() translates into
MyClass.func(ob).
In general, calling a method with a list of n arguments is equivalent to calling
the corresponding function with an argument list that is created by inserting
the method's object before the first argument.
For these reasons, the first argument of the function in class must be the
object itself. This is conventionally called self. It can be named otherwise but
we highly recommend to follow the convention.
Now you must be familiar with class object, instance object, function object,
method object and their differences.
33.3 Constructors in Python
Class functions that begins with double underscore (__) are called special
functions as they have special meaning.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 33: PYTHON OBJECTS AND CLASSES | 184
Of one particular interest is the __init__() function. This special function gets
called whenever a new object of that class is instantiated.
This type of function is also called constructors in Object Oriented
Programming (OOP). We normally use it to initialize all the variables.
class ComplexNumber:
def __init__(self,r = 0,i = 0):
self.real = r
self.imag = i
def getData(self):
print("{0}+{1}j".format(self.real,self.imag))
# Create a new ComplexNumber object
c1 = ComplexNumber(2,3)
# Call getData() function
# Output: 2+3j
c1.getData()
# Create another ComplexNumber object
# and create a new attribute 'attr'
c2 = ComplexNumber(5)
c2.attr = 10
# Output: (5, 0, 10)
print((c2.real, c2.imag, c2.attr))
# but c1 object doesn't have attribute 'attr'
# AttributeError: 'ComplexNumber' object has no attribute 'attr'
c1.attr
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 33: PYTHON OBJECTS AND CLASSES | 185
In the above example, we define a new class to represent complex numbers. It
has two functions, __init__() to initialize the variables (defaults to zero)
and getData() to display the number properly.
An interesting thing to note in the above step is that attributes of an object
can be created on the fly. We created a new attribute attr for object c2 and
we read it as well. But this did not create that attribute for object c1.
33.4 Deleting Attributes and Objects
Any attribute of an object can be deleted anytime, using the del statement.
Try the following on the Python shell to see the output.
>>> c1 = ComplexNumber(2,3)
>>> del c1.imag
>>> c1.getData()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'imag'
>>> del ComplexNumber.getData
>>> c1.getData()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'getData'
We can even delete the object itself, using the del statement.
>>> c1 = ComplexNumber(1,3)
>>> del c1
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 33: PYTHON OBJECTS AND CLASSES | 186
>>> c1
Traceback (most recent call last):
...
NameError: name 'c1' is not defined
Actually, it is more complicated than that. When we do c1 =
ComplexNumber(1,3), a new instance object is created in memory and the
name c1 binds with it.
On the command del c1, this binding is removed and the name c1 is deleted
from the corresponding namespace. The object however continues to exist in
memory and if no other name is bound to it, it is later automatically
destroyed.
This automatic destruction of unreferenced objects in Python is also called
garbage collection.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 187
Python CHAPTER
Inheritance 34
Inheritance enable us to define a class that takes all the functionality from
parent class and allows us to add more. In this topic, you will learn to use
inheritance in Python.
Figure 15: Python Inheritance
Inheritance is a powerful feature in object oriented programming.
It refers to defining a new class with little or no modification to an existing
class. The new class is called derived (or child) class and the one from which
it inherits is called the base (or parent) class.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 188
34.1 Python Inheritance Syntax
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Derived class inherits features from the base class, adding new features to it.
This results into re-usability of code.
Example of Inheritance in Python
To demonstrate the use of inheritance, let us take an example.
A polygon is a closed figure with 3 or more sides. Say, we have a class called
Polygon defined as follows.
class Polygon:
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]
def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]
def dispSides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])
This class has data attributes to store the number of sides, n and magnitude
of each side as a list, sides.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 189
Method inputSides() takes in magnitude of each side and similarly,
dispSides() will display these properly.
A triangle is a polygon with 3 sides. So, we can create a class
called Triangle which inherits from Polygon. This makes all the attributes
available in class Polygon readily available in Triangle. We don't need to
define them again (code re-usability). Triangle is defined as follows.
class Triangle(Polygon):
def __init__(self):
Polygon.__init__(self,3)
def findArea(self):
a, b, c = self.sides
# calculate the semi-perimeter
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
However, class Triangle has a new method findArea() to find and print the
area of the triangle. Here is a sample run.
>>> t = Triangle()
>>> t.inputSides()
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4
>>> t.dispSides()
Side 1 is 3.0
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 190
Side 2 is 5.0
Side 3 is 4.0
>>> t.findArea()
The area of the triangle is 6.00
We can see that, even though we did not define methods
like inputSides() or dispSides() for class Triangle, we were able to use them.
If an attribute is not found in the class, search continues to the base class.
This repeats recursively, if the base class is itself derived from other classes.
34.2 Method Overriding in Python
In the above example, notice that __init__() method was defined in both
classes, Triangle as well Polygon. When this happens, the method in the
derived class overrides that in the base class. This is to say, __init__()
in Triangle gets preference over the same in Polygon.
Generally when overriding a base method, we tend to extend the definition
rather than simply replace it. The same is being done by calling the method
in base class from the one in derived class (calling Polygon.__init__() from
__init__() in Triangle).
A better option would be to use the built-in function super(). So,
super().__init(3) is equivalent to Polygon.__init__(self,3) and is preferred.
You can learn more about the super() function in Python.
Two built-in functions isinstance() and issubclass() are used to check
inheritances. Function isinstance() returns True if the object is an instance
of the class or other classes derived from it. Each and every class in Python
inherits from the base class object.
>>> isinstance(t,Triangle)
True
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 191
>>> isinstance(t,Polygon)
True
>>> isinstance(t,int)
False
>>> isinstance(t,object)
True
Similarly, issubclass() is used to check for class inheritance.
>>> issubclass(Polygon,Triangle)
False
>>> issubclass(Triangle,Polygon)
True
>>> issubclass(bool,int)
True
34.3 Python Multiple Inheritance
In this topic, you'll learn what multiple inheritance in Python is and how to
use it in your program. You'll also learn about multilevel inheritance and the
method resolution order.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 192
Figure 16: Python multiple inheritance
Like C++, a class can be derived from more than one base classes in Python.
This is called multiple inheritance.
In multiple inheritance, the features of all the base classes are inherited into
the derived class. The syntax for multiple inheritance is similar to
single inheritance.
Python Multiple Inheritance Example
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
Here, MultiDerived is derived from classes Base1 and Base2.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 193
The class MultiDerived inherits from both Base1 and Base2.
34.4 Multilevel Inheritance in Python
On the other hand, we can also inherit form a derived class. This is called
multilevel inheritance. It can be of any depth in Python.
In multilevel inheritance, features of the base class and the derived class is
inherited into the new derived class.
An example with corresponding visualization is given below.
class Base:
pass
class Derived1(Base):
pass
class Derived2(Derived1):
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 194
pass
Here, Derived1 is derived from Base, and Derived2 is derived from Derived1.
34.5 Method Resolution Order in
Python
Every class in Python is derived from the class object. It is the most base type
in Python.
So technically, all other class, either built-in or user-defines, are derived
classes and all objects are instances of object class.
# Output: True
print(issubclass(list,object))
# Output: True
print(isinstance(5.5,object))
# Output: True
print(isinstance("Hello",object))
In the multiple inheritance scenario, any specified attribute is
searched first in the current class. If not found, the search
continues into parent classes in depth-first, left-right fashion
without searching same class twice.
So, in the above example of MultiDerived class the search
order is [MultiDerived, Base1, Base2, object]. This order is also
called linearization of MultiDerived class and the set of rules
used to find this order is called Method Resolution Order
(MRO).
MRO must prevent local precedence ordering and also provide
monotonicity. It ensures that a class always appears before its
parents and in case of multiple parents, the order is same as
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 195
tuple of base classes.
MRO of a class can be viewed as the __mro__ attribute or mro() method. The
former returns a tuple while latter returns a list.
>>> MultiDerived.__mro__
(<class '__main__.MultiDerived'>,
<class '__main__.Base1'>,
<class '__main__.Base2'>,
<class 'object'>)
>>> MultiDerived.mro()
[<class '__main__.MultiDerived'>,
<class '__main__.Base1'>,
<class '__main__.Base2'>,
<class 'object'>]
Here is a little more complex multiple inheritance
example and its visualization along with the MRO.
class X: pass
class Y: pass
class Z: pass
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 196
class A(X,Y): pass
class B(Y,Z): pass
class M(B,A,Z): pass
# Output:
# [<class '__main__.M'>, <class '__main__.B'>,
# <class '__main__.A'>, <class '__main__.X'>,
# <class '__main__.Y'>, <class '__main__.Z'>,
# <class 'object'>]
print(M.mro())
34.6 Python Operator Overloading
You can change the meaning of an operator in Python depending upon the
operands used. This practice is known as operating overloading.
Python operators work for built-in classes. But same operator behaves
differently with different types. For example, the + operator will, perform
arithmetic addition on two numbers, merge two lists and concatenate two
strings.
This feature in Python, that allows same operator to have different meaning
according to the context is called operator overloading.
So what happens when we use them with objects of a user-defined class? Let
us consider the following class, which tries to simulate a point in 2-D
coordinate system.
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
Now, run the code and try to add two points in Python shell.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 197
>>> p1 = Point(2,3)
>>> p2 = Point(-1,2)
>>> p1 + p2
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'Point' and 'Point'
Whoa! That's a lot of complains. TypeError was raised since Python didn't
know how to add two Point objects together.
However, the good news is that we can teach this to Python through operator
overloading. But first, let's get a notion about special functions.
Special Functions in Python
Class functions that begins with double underscore __ are called special
functions in Python. This is because, well, they are not ordinary.
The __init__() function we defined above, is one of them. It gets called every
time we create a new object of that class. There are a ton of special functions
in Python.
Using special functions, we can make our class compatible with built-in
functions.
>>> p1 = Point(2,3)
>>> print(p1)
<__main__.Point object at 0x00000000031F8CC0>
That did not print well. But if we define __str__() method in our class, we can
control how it gets printed. So, let's add this to our class.
class Point:
def __init__(self, x = 0, y = 0):
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 198
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x,self.y)
Now let's try the print() function again.
>>> p1 = Point(2,3)
>>> print(p1)
(2,3)
That's better. Turns out, that this same method is invoked when we use the
built-in function str() or format().
>>> str(p1)
'(2,3)'
>>> format(p1)
'(2,3)'
So, when you do str(p1) or format(p1), Python is internally doing p1.__str__().
Hence the name, special functions.
Ok, now back to operator overloading.
34.7 Overloading the + Operator in
Python
To overload the + sign, we will need to implement __add__() function in the
class. With great power comes great responsibility. We can do whatever we
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 199
like, inside this function. But it is sensible to return a Point object of the
coordinate sum.
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x,self.y)
def __add__(self,other):
x = self.x + other.x
y = self.y + other.y
return Point(x,y)
Now let's try that addition again.
>>> p1 = Point(2,3)
>>> p2 = Point(-1,2)
>>> print(p1 + p2)
(1,5)
What actually happens is that, when you do p1 + p2, Python will
call p1.__add__(p2) which in turn is Point.__add__(p1,p2). Similarly, we can
overload other operators as well. The special function that we need to
implement is tabulated below.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 200
Operator Overloading Special Functions in Python
Operator Expression Internally
Addition p1 + p2 p1.__add__(p2)
Subtraction p1 - p2 p1.__sub__(p2)
Multiplication p1 * p2 p1.__mul__(p2)
Power p1 ** p2 p1.__pow__(p2)
Division p1 / p2 p1.__truediv__(p2)
Floor Division p1 // p2 p1.__floordiv__(p2)
Remainder (modulo) p1 % p2 p1.__mod__(p2)
Bitwise Left Shift p1 << p2 p1.__lshift__(p2)
Bitwise Right Shift p1 >> p2 p1.__rshift__(p2)
Bitwise AND p1 & p2 p1.__and__(p2)
Bitwise OR p1 | p2 p1.__or__(p2)
Bitwise XOR p1 ^ p2 p1.__xor__(p2)
Bitwise NOT ~p1 p1.__invert__()
34.8 Overloading Comparison
Operators in Python
Python does not limit operator overloading to arithmetic operators only. We
can overload comparison operators as well.
Suppose, we wanted to implement the less than symbol < symbol in
our Point class.
Let us compare the magnitude of these points from the origin and return the
result for this purpose. It can be implemented as follows.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 201
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x,self.y)
def __lt__(self,other):
self_mag = (self.x ** 2) + (self.y ** 2)
other_mag = (other.x ** 2) + (other.y ** 2)
return self_mag < other_mag
Try these sample runs in Python shell.
>>> Point(1,1) < Point(-2,-3)
True
>>> Point(1,1) < Point(0.5,-0.2)
False
>>> Point(1,1) < Point(1,1)
False
Similarly, the special functions that we need to implement, to overload other
comparison operators are tabulated below.
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 202
Comparison Operator Overloading in Python
Operator Expression Internally
Less than p1 < p2 p1.__lt__(p2)
Less than or equal to p1 <= p2 p1.__le__(p2)
Equal to p1 == p2 p1.__eq__(p2)
Not equal to p1 != p2 p1.__ne__(p2)
Greater than p1 > p2 p1.__gt__(p2)
Greater than or equal to p1 >= p2 p1.__ge__(p2)
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved
CHAPTER 34: PYTHON INHERITANCE | 203
Copyright © 2017-2018 DexLab Solutions Corp All Rights Reserved