Python Core Material
Python Core Material
&
Library
2 Python Language and Library
Copyright
Copyright @ 2023 by Rajesh Godi. All rights reserved.
Although every precaution has been taken in the preparation of this book, the
author assumes no responsibility for errors or omissions. Neither is any liability
assumed for damages resulting from the use of information contained therein.
Python Language and Library 3
About the author
Rajesh Godi is a software trainer with expertise in data analytics and data
engineering. He started data analytics in early 20s and worked with data
engineering and data analytics tools.
He deals with:
Azure Data Factory
Azure DataBricks
Azure DB
Azure Synapse Analytics
Azure Data Lake
SQL server integration services (SSIS)
SQL
Python
Power BI
Power query
Excel
Use picture and text to grasp the concept. Programs are to illustrate how to
implement the concepts. Try the programs given in this material in your
system.
Python Language and Library 5
Table of content
Copyright........................................................................................................................... 2
About the author .............................................................................................................. 3
How to use this material ................................................................................................... 4
Request for feedback ........................................................................................................ 4
Table of content ................................................................................................................ 5
Python language ............................................................................................................. 11
Installation of python...................................................................................................... 12
Using python interpreter - repl ....................................................................................... 15
Interactive mode............................................................................................................. 15
Variables ......................................................................................................................... 16
Rules for identifier .......................................................................................................... 16
Operators ........................................................................................................................ 17
Assignment operator (=) ............................................................................................. 17
Arithmetic operators .................................................................................................. 18
Relational operators ................................................................................................... 19
Logical operators ........................................................................................................ 20
Built-in data types ........................................................................................................... 21
Keywords ........................................................................................................................ 23
Built-in functions............................................................................................................. 24
Function input() .............................................................................................................. 27
Using print() function .................................................................................................. 27
Formatted output ....................................................................................................... 28
The f-string .................................................................................................................. 29
The if statement.............................................................................................................. 30
6 Python Language and Library
Conditional expression ................................................................................................... 31
The while loop................................................................................................................. 32
The range() function ....................................................................................................... 33
The pass statement......................................................................................................... 33
The for statement ........................................................................................................... 34
Break, continue and else ................................................................................................ 35
Strings ............................................................................................................................. 37
The list data structure ..................................................................................................... 42
List comprehension..................................................................................................... 44
The del statement ........................................................................................................... 45
Operations related to sequence types of ....................................................................... 46
The tuple data structure ................................................................................................. 47
Function zip() and enumerate() ...................................................................................... 48
Sorted() and reversed()................................................................................................... 49
The set data structure..................................................................................................... 50
Set comprehension ..................................................................................................... 52
List vs. Set vs. Tuple ........................................................................................................ 52
The dictionary data structure ......................................................................................... 53
Dictionary comprehension.......................................................................................... 55
Structural pattern matching ........................................................................................... 56
Functions......................................................................................................................... 59
Default argument values ................................................................................................ 60
Varying arguments .......................................................................................................... 61
Keyword arguments ........................................................................................................ 62
Keyword-only arguments................................................................................................ 63
Python Language and Library 7
Positional-only arguments .............................................................................................. 64
Passing function as a parameter ..................................................................................... 65
Using filter, sorted and map functions ........................................................................... 66
Filter function ............................................................................................................. 66
Sorted function ........................................................................................................... 67
Map function .............................................................................................................. 68
Lambda expression ......................................................................................................... 69
Passing arguments - pass by value and reference .......................................................... 70
Local functions ................................................................................................................ 72
Variable’s scope .............................................................................................................. 73
Modules .......................................................................................................................... 74
The import statement ..................................................................................................... 75
The dir() function ............................................................................................................ 76
The help() function ......................................................................................................... 76
Module search path ........................................................................................................ 77
Setting python path .................................................................................................... 77
Executing module as script ............................................................................................. 78
Using command line arguments ..................................................................................... 80
Documentation ............................................................................................................... 81
Packages ......................................................................................................................... 82
Importing with * ......................................................................................................... 83
Pip and pypi .................................................................................................................... 84
Classes............................................................................................................................. 85
Init method ......................................................................................................... 85
Private members (name mangling) ............................................................................ 86
8 Python Language and Library
Static methods and variables .......................................................................................... 88
Class methods ................................................................................................................. 89
Comparison of methods ............................................................................................. 89
Built-in functions related to attributes ........................................................................... 90
Built-in class attributes ................................................................................................... 91
Special methods .............................................................................................................. 92
Relational operators ................................................................................................... 92
Unary operators .......................................................................................................... 92
Binary operators ......................................................................................................... 93
Extended assignments ................................................................................................ 94
Properties ....................................................................................................................... 97
Inheritance ...................................................................................................................... 98
Overriding ................................................................................................................. 101
Functions isinstance() and issubclass() ..................................................................... 101
Multiple inheritance ..................................................................................................... 102
Method resolution order (mro) ................................................................................ 104
Abstract class and methods .......................................................................................... 105
Exception handling........................................................................................................ 106
Predefined exceptions .............................................................................................. 111
The raise statement .................................................................................................. 113
User-defined exception and raise statement ........................................................... 113
The iterator ................................................................................................................... 114
The generator ............................................................................................................... 117
Generator expression ............................................................................................... 118
File handling .................................................................................................................. 119
Python Language and Library 9
Function open()......................................................................................................... 119
The with statement (context manager) .................................................................... 120
File object.................................................................................................................. 121
Pickle – python object serialization .............................................................................. 123
Json module .................................................................................................................. 125
The sys module ............................................................................................................. 127
The os module .............................................................................................................. 128
Using re (regular expression) module........................................................................... 130
Match object ............................................................................................................. 134
The datetime module ................................................................................................... 136
The date type ............................................................................................................ 136
The time type ............................................................................................................ 138
The datetime type .................................................................................................... 139
The timedelta type.................................................................................................... 141
Format codes ............................................................................................................ 142
Multithreading .............................................................................................................. 145
Functions in threading module ................................................................................. 146
Thread class .............................................................................................................. 146
Requests module .......................................................................................................... 148
The requests.response object................................................................................... 148
Beautifulsoup module................................................................................................... 150
Tag object ................................................................................................................. 151
Methods find() and find_all() .................................................................................... 152
Database programming ................................................................................................ 153
Sqlite3 database........................................................................................................ 154
10 Python Language and Library
Module sqlite3 .............................................................................................................. 155
Method connect() ..................................................................................................... 155
Connection object ..................................................................................................... 155
Cursor object............................................................................................................. 156
Inserting row into table ............................................................................................ 158
Retrieving rows from table ....................................................................................... 159
Updating row in table ............................................................................................... 160
Deleting row from table............................................................................................ 161
Working with other databases...................................................................................... 162
Python Language and Library 11
Python language
Easy and powerful language.
Supports different programming paradigms like structured programming
And object-oriented programming.
Is an interpreted language.
Ideal for scripting and rapid application development.
Supports high-level data structures like list, set, dictionary and tuple.
Python has a design philosophy that emphasizes code readability, and a
syntax that allows programmers to express concepts in fewer lines of code.
Created by guido van rossum and first released in 1991.
Python features a dynamic type system and automatic memory
management.
Python 2.0 was released on 16th October 2000.
Python 3.0 (initially called python 3000 or py3k) was released on 3rd
December 2008.
Python 3.10 was released in October 2021.
12 Python Language and Library
Installation of python
1. Go to python.org (https://www.python.org/downloads).
2. Click on the downloads menu and select your platform.
3. It will take you to the related downloads page. For example, for
windows ittakes you to
https://www.python.org/downloads/windows/.
4. Select windows x86-64 executable installer and download the installer
(python-3.10.0-amd64.exe).
5. Run installer and opt for custom installation.
6. Change directory into which installer installs python to something like
c:\python.
7. Also make sure you select add python 3.10 to path option in installation
window.
8. Installer installs all required files into selected folder. Installer automatically
sets python installation folder in system path.
Python Language and Library 13
14 Python Language and Library
Python Language and Library 15
Using python interpreter - REPL
Go to command prompt.
Make sure the system path is set to folder where python was installed. If
thatis not the case then you need to be in the folder into which you
installed python (for example, c:\python).
Run python.exe to start interpreter. It is also known as read evaluate print
loop (REPLl).
c:\python>python
Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18)
[MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>>
Use ctrl-z or exit() to end interpreter and come back to command prompt.
The interpreter’s line-editing features include interactive editing, history
substitution and code completion on systems that support reading line.
Interactive mode
When commands are read from keyboard, the interpreter is said to be
in interactive mode.
It prompts for the next command with the primary prompt, usually three
greater-than signs (>>>); for continuation lines it prompts with
The secondary prompt, by default three dots (...).
In the interactive interpreter, the output string is enclosed in quotes and
special characters are escaped with backslashes.
The print() function produces a more readable output, by omitting the
enclosing quotes and by printing escape and special characters.
Two or more string literals (i.e. The ones enclosed between quotes) next
toeach other are automatically concatenated.
16 Python Language and Library
Variables
Python is a dynamic language where variable is created by directly assigning
value to it.
Based on the value assigned to a variable, its datatype is determined.
Built-in function type () can be used to find out the type of a variable.
>>> a = 10
>>> type(a)
<class 'int'>
>>> b = "Python"
>>> type(b)
<class 'str'>
>>>
Note: we can find out data type of any variable using type () built-in function.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
// Integer division
% Modulus
>>> a, b = 10, 4
>>> a / b, a // b
(2.5, 2)
>>> a ** b
10000
>>> a % 4
2
Python Language and Library 19
Relational operators
The following relational operators are available to compare values:
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
>>> a = 10
>>> b = 20
>>> a < b
True
>>> a == b
False
>>> s1 = "Abc"
>>> s2 = "ABC"
>>> s1 > s2
True
>>> s1 == s2
False
20 Python Language and Library
Logical operators
The following are logical operators used to combine conditions:
Operator Meaning
And Anding
Or Oring
Not Negates condition
Note: The Boolean operators and & or are known as short-circuit operators -
their arguments are evaluated from left to right, and evaluation stops as soon
as the outcome is determined.
Python Language and Library 21
Built-in data types
The following are built-in data types in python.
>>> v1 = 10
>>> v2 = 10.50
>>> v3 = "Python"
>>> v4 = True
>>> type(v1)
<class 'int'>
>>> type(v2)
<class 'float'>
>>> type(v3)
<class 'str'>
>>> type(v4)
<class 'bool'>
Keywords
The following are important keywords in python.
Function Meaning
Abs(x) Returns the absolute value of a number.
All(iterable) Returns true if all elements of the iterable are true
(or if the iterable is empty).
Any(iterable) Returns true if any element of the iterable is true. If
The iterable is empty, returns false.
Bin(x) Converts an integer number to a binary string
Prefixed with “0b”.
Chr(i) Returns the string representing a character whose
Unicode code point is the integer i.
Dir([object]) Without arguments, returns the list of names in the
current local scope. With an argument, attempts to
Return a list of valid attributes for that object.
Filter(function, Constructs an iterator from those elements of
Iterable) Iterable for which function returns true.
Format(value[ Converts a value to a “formatted” representation, as
, Controlled by format_spec.
format_spec])
Getattr(object, Returns the value of the named attribute of object.
Name[, default])
Hex(x) Converts an integer number to a lowercase
Hexadecimal string prefixed with “0x”.
Id(object) Returns the “identity” of an object. This is an integer
Which is guaranteed to be unique and constant for
This object during its lifetime.
Len(s) Returns the length (the number of items) of an
Object.
Python Language and Library 25
>>> abs(-10)
10
>>> bin(10)
'0b1010'
>>> chr(65) # char for ascii code
'A'
>>> a = 10
>>> id(a) # Address of the object
140728047310784
>>> max(10, 20, 30)
30
>>> ord('a') # Ordinal value (ascii code)
97
>>> round(10.566)
11
>>> type(True)
<class 'bool'>
>>>
Python Language and Library 27
Function input()
Built-in function input() is used to take input from user.
It always returns a string, so we need to convert it to the required type
usingother built-in functions like int().
>>> print(1, 2, 3)
1 2 3
>>> print(1, 2, 3, sep = '-')
1-2-3
>>> print(1, 2, 3, end = '\n\n')
1 2 3
>>>
28 Python Language and Library
Formatted output
It is possible to print formatted output using % with conversion characters
like %d and %s.
Method format() of string can be used to format output. String on which
this method is called can contain literal text or replacement fields delimited
by braces {}.
Each replacement field contains either the numeric index of a positional
argument, or the name of a keyword argument. Returns a copy of the string
where each replacement field is replaced with the string value of the
corresponding argument.
Str % (values)
Str.format(*args, **kwargs)
Note: in format specifier, 8.2 means; total columns including decimal point is 8and
2 digits after decimal point. Char f means fixed format, otherwise it uses e format.
30 Python Language and Library
The if statement
It is used for conditional execution.
It selects exactly one of the suites by evaluating the expressions one by one
until one is found to be true.
There can be zero or more elif parts, and the else part is optional.
if boolean_expression:
statements
[elif boolean_expression:
statements] ...
[else:
statements]
if a > b:
print(a)
else:
print(b)
if a > 0:
print("Positive")
elif a < 0:
print("Negative")
else:
print("Zero")
Python Language and Library 31
Conditional expression
It returns either true value or false value depending on the condition.
If condition is true, then it returns true value otherwise it returns
False value.
>>> a = 10
>>> b = 20
>>> a if a > b else b
20
32 Python Language and Library
The while loop
The while statement is used for repeated execution as long as the Boolean
expression is true.
while boolean_expression:
statements
[else:
statements]
Note: the else part of while is executed only when loop is terminated
normally, i.e. Without break statement.
If start is not given then 0 is taken, if step is not given then 1 is taken.
When the items are exhausted (which is immediately when the sequence is
empty or an iterator raises a stopiteration exception), the statements in
the else clause, if present, are executed, and the loop terminates.
>>>name="python"
>>>name[0]
'p'
>>>name[-1] # last char
'n'
>>>name[-3:] # take chars from 3rd char from end
'hon'
>>>name[0:2] # take from 0 to 1
'py'
>>>name[4:] # take chars from 4th position
'on'
>>> name[::-1] # take chars in reverse
'nohtyp'
>>> name[-2:-5:-1] # take char from -2 to -5 in reverse
'oht'
Python Language and Library 39
Method Description
Capitalize() Returns a copy of the string with its first
Character capitalized and the rest lowercased.
Count(sub[, Returns the number of non-overlapping
start[,end]]) Occurrences of substring sub in the range
[start,end].
Endswith(suffix[, start[, Returns true if the string ends with the specified
End]]) Suffix, otherwise, returns false.
Find(sub[, start[, end]]) Returns the lowest index in the string where
Substring sub is found within the slice
s[start:end]. Returns -1 if sub is not found.
Format(*args, Performs a string formatting operation.
**kwargs)
Index(sub[, start[, Like find(), but raises valueerror when the
End]]) Substring is not found.
Isalnum() Returns true if all characters in the string are
alphanumeric and there is at least one character,
False otherwise.
Isalpha() Returns true if all characters in the string are
alphabetic and there is at least one character,
False otherwise.
Isdecimal() Returns true if all characters in the string are
Decimal characters and there is at least
onecharacter, false otherwise.
Isdigit() Returns true if all characters in the string are
digits and there is at least one character, false
Otherwise.
Islower() Returns true if all characters in the string are
lowercase and there is at least one cased
Character, false otherwise.
40 Python Language and Library
Method Meaning
Append(x) Adds an item to the end of the list. Equivalent
To a[len(a):] = [x].
Extend(iterable) Extends the list by appending all the items from the
iterable. Equivalent to a[len(a):] = iterable.
Insert(i, x) Inserts an item at a given position. The first argument is
the index of the element before which to insert, so
a.insert(0, x) inserts at the front of the list, and
A.insert(len(a), x) is equivalent to a.append(x).
Remove(x) Removes the first item from the list whose value is x. It is
An error if there is no such item.
Pop([i]) Removes the item at the given position in the list, and
returns it. If no index is specified, a.pop() removes and
returns the last item in the list. The square brackets
around the i in the method signature denote that the
parameter is optional, not that you should type square
Brackets at that position.
Clear() Removes all items from the list. Equivalent to del a[:].
Index(x[, start Returns zero-based index in the list of the first item
[, end]]) whose value is x. Raises a valueerror if there is no such
item. Optional arguments start and end are interpreted
as in the slice notation and are used to limit the search
to a particular subsequence of the list. The returned
index is computed relative to the beginning of the full
Sequence rather than the start argument.
Python Language and Library 43
Del item
Operation Result
X in s True if an item of s is equal to x, else false
X not in s False if an item of s is equal to x, else true
S+t The concatenation of s and t
S * n or n * s Equivalent to adding s to itself n times
S[i] Ith item of s, origin 0
S[i:j] Slice of s from i to j
S[i:j:k] Slice of s from i to j with step k
Len(s) Length of s
Min(s) Smallest item of s
Max(s) Largest item of s
Python Language and Library 47
The tuple data structure
A tuple consists of a number of values separated by commas.
Tuples are immutable, and usually contain a heterogeneous sequence of
elements that are accessed via unpacking or indexing.
It is not possible to assign to the individual items of a tuple, however it is
possible to create tuples which contain mutable objects, such as lists.
Membership operator in and not in can be used to check whether an object
is member of tuple.
A function can return multiple values using a tuple.
Empty tuples are constructed by an empty pair of parentheses; a tuple with
one item is constructed by following a value with a comma (it is not
sufficient to enclose a single value in parentheses).
Enumerate(iterable, start=0)
Output
1 10
2 20
3 30
Zip(*iterables, strict=false)
If strict is true then all iterables must be of same size, otherwise it throws error.
By default, strict is false and it considers the smallest length of the sequences.
Output
10 abc
20 xyz
30 pqr
Python Language and Library 49
Sorted() and reversed()
Function sorted() is used to return a new sorted list of values for the given
iterable.
>>> l = [4, 3, 5, 1, 2]
>>> sorted(l)
[1, 2, 3, 4, 5]
Reversed(iterable)
>>> l = [4, 3, 5, 1, 2]
>>> for n in reversed(l):
... print(n)
...
2
1
5
3
4
50 Python Language and Library
The set data structure
A set is an unordered collection with no duplicate elements.
Set objects also support mathematical operations like union, intersection,
difference, and symmetric difference.
Curly braces or the set() function can be used to create sets.
To create an empty set you have to use set(), not {}; the latter creates an
empty dictionary.
Items cannot be accessed using index, i.e., not subscriptable.
Method Meaning
Isdisjoint(other) Returns true if the set has no elements in common
With other.
Issubset(other) or Tests whether every element in the set is in other.
Set <= other
Set < other Tests whether the set is a proper subset of other,
That is, set <= other and set != other.
Issuperset(other) or Tests whether every element in other is in the set.
Set >= other
Set > other Tests whether the set is a proper superset of other,
That is, set >= other and set != other.
Union(*others) or Returns a new set with elements from the set and
Set | other | ... All others.
Intersection(*others) Returns a new set with elements common to the set
or and all others.
Set & other & ...
Difference(*others) or Returns a new set with elements in the set that are
Set - other - ... Not in the others.
Symmetric_difference Returns a new set with elements in either the set or
(other) or set ^ other Other but not both.
Update(*others) or Updates the set, adding elements from all others.
Set |= other
Python Language and Library 51
>>> st = "abc123acdef456"
>>> {c for c in st if c.isalpha() }
{'c', 'd', 'b', 'f', 'e', 'a'}
Method Meaning
D[key] Returns the item of d with key. Raises a keyerror
If key is not in the map.
D[key] = value Sets d[key] to value.
Del d[key] Removes d[key] from d. Raises a keyerror if key is not
In the map.
Key in d Returns true if d has a key, else false.
Key not in d Equivalent to not key in d.
Iter(d) Returns an iterator over the keys of the dictionary.
This is a shortcut for iter(d.keys()).
Clear() Removes all items from the dictionary.
Copy() Returns a shallow copy of the dictionary.
Get(key[, default]) Returns the value for key if key is in the dictionary,
else default. If default is not given, it defaults to
None, so that this method never raises a keyerror.
Items() Returns a new view of the dictionary’s items ((key,
Value) pairs).
Keys() Returns a new view of the dictionary’s keys.
Pop(key[, default]) If key is in the dictionary, removes it and returns its
Value, else returns default. If default is not given and
key is not in the dictionary, a keyerror is raised.
Setdefault If key is in the dictionary, returns its value. If not,
(key[, default]) inserts key with a value of default and returns
Default. The default defaults to none.
Update([other]) Updates the dictionary with the key/value pairs from
Other, overwriting existing keys. Returns none.
Values() Returns a new view of the dictionary’s values.
Python Language and Library 55
Dictionary comprehension
It is possible to create a dictionary by taking values from an iterable.
match expression:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>
01 Match code:
02 Case 1:
03 Discount = 10
04 Case 2:
05 Discount = 20
06 Case 3:
07 Discount = 25
08 Case _:
09 Discount = 5
Python Language and Library 57
It is possible to capture values into variables while pattern matching.
01 Match month:
02 Case 2:
03 Nodays = 28
04 Case 4 | 6 | 9 | 11:
05 Nodays = 30
06 Case _:
07 Nodays = 31
58 Python Language and Library
When expression is a dictionary, it is possible to match keys and capture values
into variables.
Note: the default value is evaluated only once. This makes a difference when
the default is a mutable object such as a list, dictionary, or instances of most
classes.
Python Language and Library 61
Varying arguments
A function can take any number of arguments by defining formal parameter
with prefix *.
When a function has a varying formal parameter then it can take any
number of actual parameters.
A function can mix varying parameters with normal parameters.
However, normal parameters can be passed values by name, or they
shouldappear before varying argument.
01 Def Show(**kwargs):
02 For k, v in kwargs.items():
03 Print(k, v)
04
05 Def Showall(*args, **kwargs):
06 Print(args)
07 For k, v in kwargs.items():
08 Print(k, v)
09
10 Show(a=10, b=20, c=20, msg="hello")
11 Showall(10, 20, 30, x=1, y=20)
a 10
b 20
c 20
msg Hello
(10, 20, 30)
x 1
y 20
Python Language and Library 63
Keyword-only arguments
It is possible to define parameters as keyword only parameters by giving an
* before them.
All parameters after * must be passed values only by using keywords and
not by position.
When you try to call details("bill") with positional argument, python throws
error as follows:
30
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() got some positional-only arguments passed
as keyword arguments: 'n1, n2'
Python Language and Library 65
Passing function as a parameter
It is possible for a function to receive another function as a parameter.
This is possible because a function is treated as an object in python, so just
like any other object, even a function can be passed as parameter to
another function.
Filter function
Function filter is used to select a set of elements from an iterable for which
function returns true. The given function must take a value and return true or
false. When function returns true, value is selected, otherwise value is ignored.
Filter(function, iterable)
Note: function passed to filter should take a single value and return bool.
The following example selects all even numbers from the given list of numbers.
01 Def iseven(n):
02 Return n % 2 == 0
03
04 nums = [1, 4, 3, 5, 7, 8, 9, 2]
05
06 # filter calls iseven and selects even numbers
07 for n in filter (iseven, nums):
08 print(n)
Note: filter() returns an object of type filter, which is iterable, and not list.
Python Language and Library 67
Sorted function
Sorts the given iterable and returns a list with sorted values.
The following code sorts of names by length of the name and not by characters.
C
C#
Php
SQL
Java
Python
68 Python Language and Library
Map function
Returns an iterator that applies the given function to each element in iterable,
yielding new values.
The following example shows how to use map() function to return next even
number for the given value.
01 Def next_even(n):
02 Return n + 2 if n % 2 == 0 else n + 1
03
04 nums = [10, 11, 15, 20, 25]
05 for n in map(next_even,nums):
06 print(n)
Python Language and Library 69
Lambda expression
Lambda expression refers to an anonymous function.
Where a function is needed, we can use lambda expression.
Keyword lambda is used to create lambda expressions.
Parameters are separated by comma (,) and they represent parameters of the
function in question. Expression given after colon (:) represents the required
action.
The following example shows how we can use lambda in conjunction with
filter() function, which returns a list of values that are selected by the given
function from the given list.
The following example sorts all names by stripping all whitespaces and then
converting them to lowercase (for case insensitivity) using lambda expression
passed to key parameter of sorted () function.
[10, 20]
Python Language and Library 71
Output:
Original Ids : id(a) 503960768 id(b) 503960928
Inside swap() : id(n1) 503960928 id(n2) 503960768
Values : 20 10
Values after swap : 10 20
72 Python Language and Library
Local functions
Functions defined inside another function are called local functions.
Local functions are local to function in which they are defined.
They are defined each time the enclosing function is called.
They are governed by same legb (local, enclosing, global, built-in) rule.
They can access variables that are in enclosing scope.
Cannot be called from outside outer function using notation outerfunction.
Localfunction.
They can contain multiple statements whereas lambdas can have only one
statement.
Local function can be returned from outer function and then can be called
from outside.
Local function can refer to variables in global namespace using global
Keyword and enclosing namespace using nonlocal keyword.
Num_funs.py
01 def Is_even(n):
02 Return n % 2 == 0
03
04 def Is_odd(n):
05 Return n % 2 == 1
06
07 def Is_positive(n):
08 Return n > 0
Use_num_funs.py
01 import num_funs # import module
02
03 print(num_funs. name )
04 print(num_funs.is_even(10))
Python Language and Library 75
The import statement
In order to make use of classes and functions in a module, we must first
import module using import statement.
The system maintains a table of modules that have been initialized, indexed
by module name. This table is accessible as sys.modules.
If no matching file is found, importerror is raised. If a file is found, it is
parsed, yielding an executable code block. If a syntax error
Occurs, syntaxerror is raised.
Whenever module is imported, code in module (not classes and functions)
is executed.
import num_funs
print(dir(num_funs))
Output:
[' builtins ', ' cached ', ' doc ', ' file ',
' loader ', ' name ', ' package ', ' spec ',
'is_even', 'is_odd', 'is_positive']
Note: when dir() and name are used in a module they refer to current
module.
Help([object])
Use space key to go to next page and q to quit the help system.
Python Language and Library 77
Module search path
When a module is imported, the interpreter first searches for a built-in module
with that name. If not found, it then searches for a file named modulename.py
in a list of directories given by the variable sys.path.
The directory containing the input script (or the current directory when no
file is specified).
Pythonpath (a list of directory names, with the same syntax as the shell
variable path).
The installation-dependent default.
Setting pythonpath
The following example sets pythonpath to a few directories so that they areadded
to module search path.
C:\python>set pythonpath=c:\dev\python;c:\dev\projects
Sys.path.append(r'c:\dev\python\projects')
78 Python Language and Library
Executing module as script
A module can contain executable statements as well as function and class
definitions. These statements are intended to initialize the module.
Executable statements in a module are executed whenever you run module
as a script and when you import module into another module using import
statement.
When you run a python module using python filename.py then the code in
the module will be executed, but with the name set to main .
But if we want to execute code only when module is run as script then we
need to check whether name of the module is set to main .
Module1.py
01 # this is simple module
02 def print_info():
03 print("I am in module1.print_info()")
04
05 # code executed when imported or when run as script
06 print("In Module1")
07
08 # code executed only when run as script
09 if name == " main ":
10 print("Running as script")
When you run the above code as script (python.exe module1.py) the following
output is generated:
In Module1
Running as script
But when you import this module into another file as shown below then the
output shown below is generated.
Python Language and Library 79
Use_module1.py
01 import module1
02
03 module1.print_info()
In Module1
I am in module1.print_info()
80 Python Language and Library
Using command line arguments
It is possible to pass command line arguments while invoking a module
from command line.
Command line arguments are placed in argv list, which is present in sys
Module.
First element in sys.argv is always name of the module that is being
executed.
Argv_demo.py
01 import sys
02 print("No. of arguments:", len(sys.argv))
03 print("File: ", sys.argv[0])
04 for v in sys.argv[1:]:
05 print(v)
01 Def add(n1,n2):
02 """adds two numbers and returns the result.
03
04 Args:
05 N1(int) : first number.
06 N2(int) : second number.
07
08 Returns:
09 Int : sum of the given two numbers. 10
"""
11
12 return n1 + n2
13
14 help(add) # prints documentation for add()
15 print(add. Doc ) # prints documentation
82 Python Language and Library
Packages
Package is a collection of modules.
When importing the package, python searches through the directories
on sys.path looking for the package subdirectory.
Generally, init .py file is used to make python treat the directory as
package; this is done to prevent directories with a common name, such
As string, from unintentionally hiding valid modules that occur later on the
module search path. However, init .py is optional.
File init .py can just be an empty file, but it can also execute
initialization code for the package or set the all variable.
Users of the package can import individual modules from the package.
Folder structure
use_st_lib.py
stlib
init .py
str_funs.py
num_funs.py
mis_funs.py
Stlib\str_funs.py
01 def has_upper(st):
02 # code
03 def has_digit(st):
04 # code
Python Language and Library 83
Use_st_lib.py
01 # Import module from package
02 import stlib.str_funs
03
04 # call a function in module
05 print(stlib.str_funs.has_upper("Python"))
06
07 # import a function from a module in a package
08 from stlib.str_funs import has_digit
09
10 # call function after it is imported
11 print(has_digit("Python 3.10"))
Importing with *
In order to import specific modules when * is used for module with
package, we must define variable all in package’s init .py to list
modules that are to be imported.
If variable all is not defined in init .py then python ensures that the
package has been imported (running initialization code in init .py) and
then imports whatever names are defined in the package but no modules
are imported.
The following are some of the important options available with pip:
class className:
definition
Init method
When a class defines an init () method, class instantiation automatically
invokes init () for the newly created class instance.
Arguments given to the class instantiation operator are passed on
to init ().
86 Python Language and Library
01 class Product:
02 def init (self, name, price):
03 # Object attributes
04 self.name = name
05 self.price = price
06
07 def print_details(self):
08 print("Name : ", self.name)
09 print("Price : ", self.price)
10
11 p = Product("Dell XPS Laptop",80000) # create object
12 p.print_details()
01 Class product:
02 Def init (self, name, price):
03 Self. Name = name
04 Self. Price = price
05
06 Def Print_details(self):
07 Print("name : ", self. Name)
08 Print("price : ", self. Price)
As attributes name and price are prefixed with (double underscore) they are
to be treated as private members of the class. Python will prefix classname to
those attributes.
The following code fails to access name attribute because its name is
prefixed with class name due to name mangling.
However, you can access private attributes from outside if you use _classname
as prefix as shown below:
01 class Point:
02 # Static attributes
03 max_x = 100
04 max_y = 50
05 def init (self, x, y):
06 self.x = x
07 self.y = y
08
09 @staticmethod
10 def isvalid(x,y):
11 return x <= Point.max_x and y <= Point.max_y
Print(point.isvalid(10,20))
Python Language and Library 89
Class methods
When a method in the class is decorated with @classmethod, it is called as
a class method.
Class methods are used as factory methods to create and return objects of
class.
They are always passed the class that is invoking them, as first parameter.
01 class Time:
02 @classmethod
03 def create(cls):
04 return cls(0,0,0)
05
06 def init (self,h,m,s):
07 self.h = h
08 self.m = m
09 self.s = s
10
11 # create an object
12 t = Time.create() # Time is passed to create()
Comparison of methods
Here is a table listing different types of methods that can be created in a class
and their characteristics.
Function Meaning
Getattr (object, Returns the value of the named attribute of object if
name[, default]) attribute is found otherwise returns default value, if
given, else raises error.
Hasattr (object, name) Returns true if object has the attribute.
Setattr (object, name, Creates or modifies an attribute with the given
Value) Value.
Delattr (object, name) Deletes the specified attribute from the given
Object.
01 class Product:
02 tax = 10
03 def init (self,name):
04 self.name = name
Attribute Description
Dict Dictionary containing the members.
Doc Class documentation string or none, if undefined.
Name Class name.
Module Module name in which the class is defined. This attribute is
" main " when module is run as a script.
Bases A tuple containing the base classes, in the order of their
occurrence in the base class.
Relational operators
The following special methods represent relational operators. By implementing
these methods, we provide support for those operators in our user-defined
class.
Operator Method
< Object. Lt (self, other)
<= Object. Le (self, other)
== Object. Eq (self, other)
!= Object. Ne (self, other)
>= Object. Ge (self, other)
> Object. Gt (self, other)
Unary operators
The following are special methods for unary operators.
Operator Method
- Object. Neg (self)
+ Object. Pos (self)
Abs() Object. Abs (self)
~ Object. Invert (self)
Complex() Object. Complex (self)
Int() Object. Int (self)
Float() Object. Float (self)
Oct() Object. Oct (self)
Hex() Object. Hex (self
Python Language and Library 93
Binary operators
The following are special methods related to binary operators.
Operator Method
+ Object. Add (self, other)
- Object. Sub (self, other)
* Object. Mul (self, other)
// Object. Floordiv (self, other)
/ Object. Truediv (self, other)
% Object. Mod (self, other)
** Object. Pow (self, other[, modulo])
<< Object. Lshift (self, other)
>> Object. Rshift (self, other)
& Object. And (self, other)
^ Object. Xor (self, other)
| Object. Or (self, other)
94 Python Language and Library
Extended assignments
Here are special methods related to extended operators.
Operator Method
+= Object. Iadd (self, other)
-= Object. Isub (self, other)
*= Object. Imul (self, other)
/= Object. Idiv (self, other)
//= Object. Ifloordiv (self, other)
%= Object. Imod (self, other)
**= Object. Ipow (self, other[, modulo])
<<= Object. Ilshift (self, other)
>>= Object. Irshift (self, other)
&= Object. Iand (self, other)
^= Object. Ixor (self, other)
|= Object. Ior (self, other)
Python Language and Library 95
The following program shows how to implement special methods.
01 Class time:
02 Def init (self, h=0, m=0, s=0):
03 """ initializes hours, mins and seconds """
04 self.h = h
05 Self.m = m
06 Self.s = s
07
08 Def total_seconds(self):
09 """returns total no. Of seconds """
10 return self.h * 3600 + self.m * 60 + self.s
11
12 Def eq (self, other):
13 Return self.total_seconds() == \
14 Other.total_seconds()
15
16 Def str (self):
17 Return f"{self.h:02}:{self.m:02}:{self.s:02}"
18
19
20 Def bool (self):
21 """returns false if hours, mins and seconds
22 Are 0 otherwise true 23
"""
24 Return self.h != 0 or self.m != 0 \
25 Or self.s != 0
26
27 Def gt (self,other):
28 Return self.total_seconds() > \
29 Other.total_seconds()
30
96 Python Language and Library
31 def add (self, other):
32 return Time(self.h + other.h,
33 self.m + other.m, self.s + other.s)
34
35 t1 = Time(1, 20, 30)
36 t2 = Time(10, 20, 30)
37 print(t1)
38 print(t1 == t2)
39
40 t3 = Time() # h,m,s are set to zeros
41 if t3:
42 print("True")
43 else:
44 print("False")
45
46 print (t1 < t2)
47
48 t4 = t1 + t2
49 print(t4)
01:20:30
False
True
11:40:60
Python Language and Library 97
Properties
It is possible to create a property in python using two decorators -
@property and @setter.
A property is used like an attribute, but it is internally implemented by two
methods – one to get value (getter) and one to set value (setter).
Properties provide advantages like validation, abstraction and lazy loading.
01 Class person:
02 Def init (self, first='', last=''):
03 self. First = first
04 self. Last = last
05
06 @property # getter
07 def name(self):
08 return self. First + " " + self. Last
09
10 @name.setter # setter
11 Def name(self, value):
12 Self. First, self. Last = value.split(" ")
13
14
15 P = person("rajesh", "pragada")
16 Print(p.name) # calls @property getter method
17 P.name="pragada rajesh" #calls @name.setter method
98 Python Language and Library
Inheritance
When a new class is created from an existing class, it is called as
inheritance. It enables us to reuse existing classes while creating new
classes.
A new class can be created from one or more existing classes.
If a requested attribute is not found in the class, the search proceeds to
look in the base class. This rule is applied recursively if the base class itself is
derived from some other class.
New class is called subclass and the class being inherited is called
Superclass.
Subclass can override a method of superclass to enhance or change
functionality of superclass method.
Function super() is used to access superclass from subclass.
It is possible to call methods of superclass using super() function –
Super().methodname(arguments).
It is also possible to call superclass method directly -
superclassname.methodname(self, arguments). We must send self as first
argument.
Inheritance is also known as generalization as we start with most generic
class (superclass) and create more specific classes (subclasses) later.
Python Language and Library 99
Note: every class that is not a subclass of another class is implicitly inheriting
Object class.
100 Python Language and Library
01 class Employee:
02 def init (self,name, salary):
03 self. name = name
04 self. salary = salary
05 def print(self):
06 print(self. name)
07 print(self. salary)
08 def get_salary(self):
09 return self. salary
01 Class manager(employee):
02 Def init (self,name, salary, hra):
03 super(). Init (name,salary)
04 Self. Hra = hra
05 Def print(self): # overrides print()
06 super().print()
07 Print(self. Hra)
08 Def get_salary(self): # overrides get_salary()
09 return super().get_salary() + self. Hra
10
11
12 e = employee("scott",100000)
13 m = manager("mike",150000,50000)
14 e.print()
15 print("net salary : ", e.get_salary())
16 m.print()
17 print("net salary : ", m.get_salary())
Python Language and Library 101
Output:
Scott
100000
Net salary : 100000
Mike
150000
50000
Net salary : 200000
Overriding
When a method in subclass is created with same name as a method in
superclass, it is called as overriding.
Subclass method is said to override method in superclass.
Overriding is done to change the behavior of inherited method of
superclass by creating a new version in subclass.
isinstance(object, class)
issubclass(class, class)
e = Employee(…)
print("Employee ?? ", isinstance(e, Employee)) # True
print("Manager subclass of Employee ?? ",
issubclass(Manager, Employee)) # True
102 Python Language and Library
Multiple inheritance
Python supports a form of multiple inheritance as well. A class definition with
multiple super classes is as follows:
class SubclassName(superclass1,superclass2,…):
. . .
01 Class a:
02 Def process(self):
03 Print('a process()')
04
05
06 Class b:
07 Def process(self):
08 Print('b process()')
09
10 Class c(a, b):
11 Pass
12
13 Obj = c()
14 Obj.process() # will call process() Of a
Python Language and Library 103
Python always considers subclass version, if one is present. In the following
example, process() from class c is called because python considers subclass
version ahead of superclass version. So, it will not consider process() method in
a as class a is superclass of c and method is present in class c.
01 class A:
02 def process(self):
03 print('A process()')
04
05
06 class B(A):
07 pass
08
09
10 class C(A):
11 def process(self):
12 print('C process()')
13
14
15 class D(B, C):
16 pass
17
18
19 obj = D()
20 obj.process() # Calls method from class C
104 Python Language and Library
Method resolution order (mro)
Mro is the order in which python searches for a method in the hierarchy of
classes.
For the above example, calling method mro() on class d will return the
following:
try:
Statements
[except (exception [as identifier] [, exception] …)] … :
Statements]
[else:
Statements]
[finally:
Statements]
Clause Meaning
Try Specifies exception handlers and/or cleanup code for a group of
Statements.
Except Specifies one or more exception handlers. It is possible to have
multiple except statements for a single try statement. Each except
Can specify one or more exceptions that it handles.
Else Executed when try exits successfully.
Finally Executed at the end of try whether try succeeds or fails.
Note: after try, one except block or finally block must be given.
Python Language and Library 107
01 a = 10
02 b = 20
03
04 try:
05 c = a / b
06 print(c)
07 except:
08 print("Error")
09 else:
10 print("Job Done!")
11 finally:
12 print("The End!")
Output:
0.5
Job Done!
The End!
108 Python Language and Library
The following example produces a different result as value of b is 0. We are
catching exception and referring to it using ex in except block. As ex contains
error message, printing ex will produce error message. The else block is not
executed as try failed with error.
01 a = 10
02 b = 0
03
04 try:
05 c = a / b
06 print(c)
07 except Exception as ex:
08 print("Error :", ex) 09
else:
10 print("Job Done!")
11 finally:
12 print("The End!")
Output:
Error : division by zero
The End!
Python Language and Library 109
The following program takes numbers from user until 0 is given and then
displays sum of given numbers.
01 total = 0
02 while True:
03 num = int(input("Enter number [0 to stop]: "))
04 if num == 0:
05 break
06
07 total += num
08
09 print(f"Total = {total}")
But the program is fragile as any invalid input will crash the program as shown
in output below:
In order to make program more robust so that it can continue in spite of invalid
input from user, we need to enclose sensitive part of the program in try block
and continue after displaying error message regarding invalid input.
110 Python Language and Library
01 total = 0
02 while True:
03 try:
04 num = int(input("Enter number [0 to stop]: "))
05 if num == 0:
06 break
07 total += num
08 except ValueError:
09 print("Invalid Number!")
10
11 print(f"Total = {total}")
In the output below, whenever invalid input is given, an error is displayed and
program continues till end.
Baseexception
+-- systemexit
+-- keyboardinterrupt
+-- generatorexit
+-- exception
+-- stopiteration
+-- stopasynciteration
+-- arithmeticerror
| +-- floatingpointerror
| +-- overflowerror
| +-- zerodivisionerror
+-- assertionerror
+-- attributeerror
+-- buffererror
+-- eoferror
+-- importerror
| +-- modulenotfounderror
+-- lookuperror
| +-- indexerror
| +-- keyerror
+-- memoryerror
+-- nameerror
| +-- unboundlocalerror
112 Python Language and Library
+-- oserror
| +-- blockingioerror
| +-- childprocesserror
| +-- connectionerror
| | +-- brokenpipeerror
| | +-- connectionabortederror
| | +-- connectionrefusederror
| | +-- connectionreseterror
| +-- fileexistserror
| +-- filenotfounderror
| +-- interruptederror
| +-- isadirectoryerror
| +-- notadirectoryerror
| +-- permissionerror
| +-- processlookuperror
| +-- timeouterror
+-- referenceerror
+-- runtimeerror
| +-- notimplementederror
| +-- recursionerror
+-- syntaxerror
| +-- indentationerror
| +-- taberror
+-- systemerror
+-- typeerror
+-- valueerror
| +-- unicodeerror
| +-- unicodedecodeerror
| +-- unicodeencodeerror
| +-- unicodetranslateerror
Python Language and Library 113
The raise statement
Used to raise an exception.
If no exception is given, it re-raises the exception that is active in the
current scope.
Raise [expression]
01 # user-defined exception
02 Class amounterror(exception):
03 Def init (self, message):
04 self.message = message 05
def str (self):
06 return self.message
01 Try:
02 If amount < 1000:
03 Raise amounterror("minimum amount is 1000")
04 except exception as ex:
05 print("error : ", ex)
114 Python Language and Library
The iterator
An iterator is an object representing a stream of data; this object returns
the data one element at a time.
Several of python’s built-in data types support iteration, the most common
being lists and dictionaries.
An object is called iterable if you can get an iterator for it.
Method iter() of an object returns iterator object that defines next ()
method.
Method next () is used to return next element and raises stopiteration
Exception when there are no more elements to return.
The following example shows how list class provides list_iterator to iterate
over elements of list.
>>> l = [1, 2, 3]
>>> li = iter(l)
>>> type(l), type(li)
(<class 'list'>, <class 'list_iterator'>)
>>> next(li)
1
>>> next(li)
2
>>> next(li)
3
>>> next(li)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
Python Language and Library 115
An iterable class is the one that provides iter () method, which returns an
object iterator class that provides next () method to return one element at
a time.
01 class Marks_Iterator:
02 def init (self, marks):
03 self.marks = marks
04 self.pos = 0
05
06 def next (self):
07 if self.pos == len(self.marks):
08 raise StopIteration
09 else:
10 value = self.marks[self.pos]
11 self.pos += 1 # move to next element
12 return value
13
116 Python Language and Library
14 class Marks:
15 def init (self):
16 self.marks = [20, 30, 40, 25, 66]
17
18 def iter (self):
19 return Marks_Iterator(self.marks)
01 m = Marks()
02 for v in m:
03 print(v)
Python Language and Library 117
The generator
Generator is a simple and powerful tool for creating iterators.
They are written like regular functions but use the yield statement
whenever they want to return data.
Each time next() is called on it, the generator resumes where it left off.
Generator can be thought of as resumable function.
Generator can be used where iterable is needed.
Function open()
Opens the specified file in the given mode and returns file object. If the file
cannot be opened, an oserror is raised.
Open(file, mode='r')
Mode Meaning
'R' Open for reading (default).
'W' Open for writing, truncating the file first.
'X' Open for exclusive creation, failing if the file already exists.
'A' Open for writing, appending to the end of the file if it exists.
'B' Binary mode.
'T' Text mode (default).
'+' Open a disk file for updating (reading and writing).
Note: when a string is prefixed with r, it is called as raw string. In raw string,
even character like \ is treated as simple character and not escape sequence
character.
120 Python Language and Library
01 f = open(r"c:\python\names.txt","wt")
02 names = ["Python", "C#", "Java", "JavaScript", "C++"]
03
04 for name in names:
05 f.write(name + "\n")
06 f.close()
with
( open("a.txt", "r") as file1,
open("b.txt", "r") as file2
):
print("Do something!")
Python Language and Library 121
File object
File object represents an open file. Built-in function open() returns file object
on success.
Attribute Meaning
File.closed Returns true if file is closed, false otherwise.
File.mode Returns access mode with which file was opened.
File.name Returns name of the file.
Method Meaning
Read([count]) Reads everything until end of file unless count is
Specified, otherwise only count number of chars.
Readline() Reads a single line. Returns empty string on eof.
Readlines() Reads all lines and returns a list of lines.
Close() Closes and flushes content to file.
Write(value) Writes the given content to file.
Tell() Returns current position of file.
Seek(offset, base) Takes file pointer to the required location from the given
Base.
The following program displays all lines along with line numbers.
01 with open(r"c:\python\names.txt","r") as f:
02 for idx, name in enumerate(f.readlines(), start = 1):
03 print(f"{idx:03} : {name.strip()}")
122 Python Language and Library
Note: while reading lines from file, readlines() reads line along with new line
(\n) character at the end of the line.
The following program displays all customer names and phone numbers in the
sorted order of customer name by reading data from phones.txt, which is given
below:
Steve,9339933390
Jason,3939101911
Ben,2939991113
George,3939999999
Larry
Ellison,39393999393
01 F = open("phones.txt","rt")
02 Phones = {} # empty dictionary
03 for line in f:
04 # split line into two parts – name and phone
05 parts = line.split(",")
06
07 # ignore line if it doesn’t contain 2 parts
08 if len(parts) != 2:
09 continue
10
11 # add entry to dictionary
12 Phones[parts[0]]= parts[1].strip()
13
14 # sort by names and print along with phone number
15 for name,phone in sorted(phones.items()):
16 print(f"{name:20} - {phone}")
Python Language and Library 123
Pickle – python object serialization
The pickle module is used to serialize and de-serialize python objects.
It provides methods like dump() for pickling and load() for unpickling.
It uses binary protocol.
Function Meaning
Dump(obj, file) Writes a pickled representation of obj to the open file
Object file.
Dumps(obj) Returns the pickled representation of the object as a
Bytes object, instead of writing it to a file.
Load(file) Reads a pickled object representation from the open
File object file and returns the reconstituted
objecthierarchy specified therein.
Loads(bytes_object) Reads a pickled object hierarchy from a bytes object
and returns the reconstituted object hierarchy
Specified therein.
124 Python Language and Library
01 Import pickle
02 Class person:
03 Def init (self, name, email):
04 Self.name = name
05 Self.email = email 06
def str (self):
07 return f"{self.name}-{self.email}"
08
09
10 F = open("person.dat", "wb")
11 P1 = person("rajesh", "rajeshpragada@yahoo.com")
12 Pickle.dump(p1, f) # pickle object
13 Print("dumped object to file!")
14 F.close()
dump(object, file)
dumps(object)
load(file)
loads(str)
01 import json
02
03 class Contact:
04 def init (self, name, phone, email):
05 self.name = name
06 self.phone = phone
07 self.email = email
08
09 c = Contact("Rajesh",
10 "90590500",
11 "contact@rajeshgodi@ymail.com")12
print(json.dumps(c. dict ))
126 Python Language and Library
The above program will generate the following json:
The following code converts each contact object to dict object using map()
function and then converts the list of dict to an array of json objects.
01 contacts = (Contact("A","8888899999","a@gmail.com"),
02 Contact("B","9999988888","b@yahoo.com"))
03 # convert each Contact object to dict using map()
04 clist = list(map(lambda c : c. dict , contacts))
05 print(json.dumps(clist))
Member Meaning
Argv The list of command line arguments passed to a
python script. Argv[0] is the script name.
Exc_info() This function returns a tuple of three values that give
Information about the exception that is currently
being handled.
Exit([arg]) Exits from python.
Getsizeof Returns the size of an object in bytes.
(object [, default])
Modules This is a dictionary that maps module names to
Modules which have already been loaded.
Path A list of strings that specifies the search path for
modules. Initialized from the environment variable
Pythonpath, plus an installation-dependent default.
Platform This string contains a platform identifier.
Stdin, stdout, stderr File objects used by the interpreter for standard
Input, output and errors.
Version A string containing the version number of the python
interpreter plus additional information on the build
Number and compiler used.
128 Python Language and Library
The os module
This module provides a portable way of using operating system dependent
functionality.
All functions in this module raise oserror in case of invalid or inaccessible
file names and paths, or other arguments that have the correct type, but
are not accepted by the operating system.
Function Meaning
Chdir(path) Changes current directory.
Getcwd() Returns current directory.
Getenv(key, Returns the value of the environment variable key if it
default=none) Exists, or default if it doesn’t. Key, default and the result
Are str.
Putenv Sets the environment variable named key to the string
(key, value) value.
Listdir(path='.') Returns a list containing the names of the entries in the
Directory given by path.
Mkdir(path) Creates a directory named path.
Remove(path) Removes (deletes) the file path.
Removedirs(name) Removes directories recursively.
Rename(src, dst) Renames the file or directory src to dst.
Rmdir(path) Removes directory.
Walk(top) Generates the file names in a directory tree by walking
The tree either top-down or bottom-up.
Python Language and Library 129
01 import os
02 # get all files from given folder
03 files = os.listdir(r"c:\python")
04 for file in files:
05 print(file) # print filename
01 import os
02
03 # Get all files and folders from the given path
04 all files = os.walk(r"c:\dev\python")
05
06 for (dirname , directories , files) in allfiles:
07 # print directory name
08 print("Directory : ", dirname)
09 print("=============" + "=" * len(dirname))
10
11 # print files in that directory
12 for file in files:
13 print(file)
130 Python Language and Library
Using re (regular expression) module
Module re provides methods that use regular expressions.
A regular expression (or re) is a string with special characters that specifies
which strings would match it.
Module re provides functions to search for a partial and full match for a
regular expression in the given string. It provides functions to split strings
and extract strings using regular expression.
Character Description
[] A set of characters
\ Signals a special sequence (can also be used to escape special
Characters)
. Any character (except newline character)
^ Starts with
$ Ends with
* Zero or more occurrences
+ One or more occurrences
{} Exactly the specified number of occurrences
| Either or
() Represents a group
Python Language and Library 131
The following are special sequences that have special meaning in a regular
expression.
Character Description
\d Returns a match where the string contains a digit (numbers
From 0-9).
\d Returns a match where the string contains a non-digit.
\s Returns a match where the string contains a whitespace
Character.
\s Returns a match where the string contains a non-whitespace
Character.
\w Returns a match where the string contains any word character
(characters from a to z, digits from 0-9, and the underscore _
character).
\w Returns a match where the string contains a non-word
Character.
132 Python Language and Library
The following are functions provided by re module.
Function Meaning
Compile(pattern Compiles a regular expression pattern into a regular
,flags=0) Expression object, which can be used for matching
using its match(), search() and other methods.
Search(pattern, Scans through string looking for the first location
string,flags=0) where the regular expression pattern produces a
match, and returns a corresponding match object.
Returns none if no position in the string matches the
Pattern.
Match(pattern, If zero or more characters at the beginning
string,flags=0) Of string match the regular expression
pattern,returns a corresponding match object.
Returns none if the string does not match the
Pattern.
Fullmatch(pattern If the whole string matches the regular
,string,flags=0) Expression pattern, returns a corresponding match
object.
Returns none if the string does not match the
pattern.
Split(pattern,string Splits string by the occurrences of pattern. If
,maxsplit=0, capturing parentheses are used in pattern, then the
flags=0) text of all groups in the pattern are also returned as
part of the resulting list. If maxsplit is nonzero, at
most maxsplit splits occur, and the remainder of the
String is returned as the final element of the list.
Findall(pattern Returns all non-overlapping matches of pattern in
,string, string, as a list of strings. The string is scanned left-to-
flags=0) right, and matches are returned in the order found.
Sub(pattern, Replaces string that matches pattern with the given
Replace, string) String.
Python Language and Library 133
>>> import re
>>> st ="abc 123 xyz pqr 456"
>>> re.match(r'\w+', st) # Looks only at start of string
<re.Match object; span=(0, 3), match='abc'>
>>> re.match(r'\d+',st) # Returns None
Function Meaning
Group Returns one or more subgroups of the match. If there is a
([group1, ...]) single argument, the result is a single string; if there are
multiple arguments, the result is a tuple with one item per
argument. Without arguments, group1 defaults to zero (the
whole match is returned). If the regular expression uses the
(?P<name>...) Syntax, the groupn arguments may also be
strings identifying groups by their group name.
Groups() Returns a tuple containing all the subgroups of the match,
from 1 up to however many groups are in the pattern. The
default argument is used for groups that did not participate
In the match; it defaults to none.
Groupdict Returns a dictionary containing all the named subgroups of
(default=none) the match, keyed by the subgroup name.
Start([group]), Returns the indices of the start and end of the substring
End([group]) Matched by group.
Span([group]) For a match m, returns the 2-tuple (m.start(group),
M.end(group)).
Pos Returns the value of pos which was passed to the search()
or match() method of a regex object.
Endpos Returns the value of endpos which was passed to the
Search() or match() method of a regex object.
Lastindex Returns the integer index of the last matched capturing
group, or none if no group was matched at all.
Python Language and Library 135
The following example uses grouping concept to extract name and phone
number from the given string.
All arguments are required. Arguments are integers, in the following ranges:
Class attributes date.min and date.max contain the earliest and latest
representable dates - date(minyear, 1, 1) and date(maxyear, 12, 31).
Python Language and Library 137
Operation Result
Date1 + timedelta Adds timedelta.days to date1.
Date1 - timedelta Subtracts timedelta.days from date1.
Date1 - date2 Subtracts date2 from date1 and returns timedelta to
Represent period between dates.
Date1 < date2 Returns true if date1 is less than date2.
Attribute Meaning
Year Between minyear and maxyear inclusive.
Month Between 1 and 12 inclusive.
Day Between 1 and the number of days in the given month of
the given year.
Attribute Meaning
Hour Hours between 0 to 23
Minute Minutes between 0 to 59
Second Seconds between 0 to 59
Microsecond Microseconds between 0 and 999999
Attribute Meaning
Year Between minyear and maxyear inclusive.
Month Between 1 and 12 inclusive.
Day Between 1 and the number of days in the given month of the
Given year.
Hour In range(24).
Minute In range(60).
Second In range(60).
Microsecond In range(1000000).
140 Python Language and Library
Only days, seconds and microseconds are stored internally. Arguments are
converted to those units:
Attribute Value
Days Between -999999999 and 999999999 inclusive
Seconds Between 0 and 86399 inclusive
Microseconds Between 0 and 999999 inclusive
142 Python Language and Library
Format codes
The following are format codes used in strftime() and strptime() functions.
>>> cd = datetime.now()
>>> cd.strftime("%d-%m-%Y %H:%M:%S")
'29-04-2022 11:03:07'
144 Python Language and Library
The following program takes date of birth from user and displays age in years,
months and days.
Function Meaning
Active_count Returns the number of thread objects currently alive.
Current_thread Returns the current thread object, corresponding to the
Caller’s thread of control.
Main_thread Returns the main thread object. In normal conditions, the
main thread is the thread from which the python
Interpreter was started.
Enumerate Returns a list of all thread objects currently alive.
Thread class
Thread object represents a thread. The following are important methods of
thread class.
Method Meaning
Start() Starts the thread's activity.
Run() Method representing the thread's activity.
Join() Waits until the thread terminates.
Getname() Returns thread's name.
Setname() Sets thread's name.
Is_alive() Returns whether the thread is alive.
Python Language and Library 147
The following program creates a thread to check whether the given number is
prime or not.
01 Def isprime(num):
02 For n in range(2, math.floor(math.sqrt(num)) + 1):
03 If num % n == 0:
04 Print(f"{num} is not a prime number!")
05 Break
06 Else:
07 Print(f"{num} is a prime number!")
08
09 Nums = [393939393, 12121212121, 29292939327,
10 38433828281, 62551414124111]
11
12 For n in nums:
13 T = thread(target=isprime, args=(n,))
14 T.start()
Property Meaning
Content Content of the response, in bytes.
Cookies A cookiejar of cookies the server sent back.
Headers Case-insensitive dictionary of response headers. For
example, headers['content-encoding'] will return the
Value of a 'content-encoding' response header.
Json(**kwargs) Returns the json-encoded content of a response, if any.
Reason Textual reason of responded http status, e.g. "not
Found" or "ok".
Request The preparedrequest object to which this is a response.
Python Language and Library 149
01 import requests
02
03 code = input("enter country code :")
04 resp = requests.get
05 (f"https://restcountries.com/v3.1/alpha/{code}")
06 If resp.status_code == 404:
07 Print("sorry! Country code not found!")
08
09 elif resp.status_code != 200:
10 print("sorry! Could not get country details!")
11 else:
12 # take first elements in the list of dictionaries
13 Details = resp.json()[0]
14 Print("country information");
15 Print("name : " + details["name"]["common"])
16 Print("capital : " + details["capital"][0])
17 Print("population : " +
18 Str(details["population"]))
19 Print("sharing borders with :")
20 For c in details["borders"]:
21 Print(c)
150 Python Language and Library
Beautiful soup library
Beautiful soup is a python package for parsing html and xml documents.
It creates a parse tree for parsed pages that can be used to extract data
from html and xml, which is useful for web scraping.
To process xml document, install lxml package as follows and use xml as the parser.
Beautifulsoup(content, type)
Type of the content specifies what type of content is being parsed and which
parse is to be used. Available options are:
Type Meaning
Html.parser Uses python’s html parser
Lxml Uses lxml’s html parser
Lxml-xml or xml Uses lxml’s xml parser
Python Language and Library 151
Tag object
Tag object corresponds to an xml or html tag in document.
Property Meaning
Name Name of the tag
Text Text of the tag
[attribute] Provides value for the given attribute in []
Contents Provides all children of the tag
Children Allows iteration over tag’s children
Descendants Provides all descendants of the tag
Parent Provides parent tag for the tag
152 Python Language and Library
# a simple string
soup.find_all('b')
# a regular expression
soup.find_all(re.compile("^b"))
Method connect()
It is used to establish a connection to database with given parameters.
Parameter is name of the database to connect to. If database is not present,
it is created.
It returns connection object.
Connect(databasename)
Connection object
Connection object represents a connection to database.
Method Meaning
Close() Closes connection.
Commit() Commits pending changes in transaction to database.
Rollback() Causes the database to roll back to the start of any pending
transaction. Closing a connection without committing the
changes first will cause an implicit rollback to be performed.
Cursor() Returns a cursor object using this connection.
156 Python Language and Library
Cursor object
Cursor represents a database cursor, which is used to manage the context
of a fetch operation.
Cursors created from the same connection are not isolated, i.e., any
changes done to the database by a cursor are immediately visible to other
cursors.
Method Meaning
Close() Closes cursor.
Execute(operation Prepare and execute a database operation.
[, parameters])
Executemany Prepare a database operation (query or
(operation, command) and then execute it against all
seq_of_parameters ) parameter sequences or mappings found in the
Sequence seq_of_parameters.
Fetchone() Fetch the next row of a query result set,
Returning a single sequence, or none when no
more data is available.
Fetchmany Fetch the next set of rows of a query result,
([size=cursor.arraysize]) returning a sequence of sequences (e.g. A list of
tuples). An empty sequence is returned when no
More rows are available.
Fetchall() Fetch all (remaining) rows of a query result,
returning them as a sequence of sequences (e.g.
A list of tuples). Note that the cursor's arraysize
attribute can affect the performance of this
Operation.
Python Language and Library 157
Attribute Meaning
Rowcount This read-only attribute specifies the number of rows that the
Last execute() method retrieved or affected.
Lastrowid Read-only attribute provides the rowid of the last modified
Row.
Arraysize Read/write attribute that controls the number of rows
returned by fetchmany(). The default value is 1, which means
A single row would be fetched per call.
Connection This read-only attribute provides the sqlite
Database connection used by the cursor object.
Note: use sqlite studio, which is a free gui tool, to manage sqlite database.
Download it from https://sqlitestudio.pl/index.rvt
01 import sqlite3
02 con = sqlite3.connect("test.db")
03 print("Connected to test database!")
04 con.close()
01 Import sqlite3
02 Con = sqlite3.connect("test.db")
03 cur = con.cursor()
04
05 # insert a row into expenses table
06 try:
07 # take data from user
08 Des = input("enter description :")
09 amt = input("enter amount :")
10 Row = (des, amt)
11 Cur.execute(
12 "insert into expenses(description,amount)values(?,?)"
13 , row)
14 Con.commit()
15 Print("added successfully!")
16 except exception as ex:
17 print("sorry! Error: ", ex)
18 finally:
19 con.close()
Python Language and Library 159
Retrieving rows from table
The following program shows how to list all rows from expenses table.
01 Import sqlite3
02
03 Con = sqlite3.connect("test.db")
04 Cur = con.cursor()
05
06 # list rows from expenses table
07 Try:
08 Cur.execute("select * from expenses Order by id")
09 For row in cur.fetchall():
10 Print(f"{row[0]:3d} {row[1]:30s} {row[2]:10.2f}")
11
12 Cur.close()
13 Except exception as ex:
14 Print("error : ", ex)
15 Finally:
16 Con.close()
160 Python Language and Library
Updating row in table
The following program updates an existing row in expenses table.
01 import sqlite3
02
03 con = sqlite3.connect(r"c:\dev\python\test.db")
04 cur = con.cursor()
05
06 # update expenses table
07 try:
08 # take data from user
09 Id = input("enter id :")
10 Amount = input("enter amount :")
11 Cur.execute
12 ("update expenses set amount=? Where id = ?",
13 (amount, id))
14 If cur.rowcount == 1:
15 Con.commit()
16 Print("updated successfully!")
17 Else:
18 Print('sorry! Id not found!')
19 except exception as ex:
20 print("sorry! Error: ", ex)
21 finally:
22 con.close()
Python Language and Library 161
Deleting row from table
The following program deletes an existing row in expenses table.
01 import sqlite3
02
03 con = sqlite3.connect("test.db")
04 cur = con.cursor()
05
06 # delete row from expenses table
07 try:
08 # take data from user
09 Id = input("enter id :")
10 Cur.execute
11 ("delete from expenses where id = ?", (id, ))
12 If cur.rowcount == 1:
13 Con.commit()
14 Print("deleted successfully!")
15 Else:
16 Print('sorry! Id not found!')
17 except exception as ex:
18 print("sorry! Error: ", ex)
19 finally:
20 con.close()
162 Python Language and Library
Working with other databases
Here are my blogs about how to access other database systems from python.