Python_ arrays
Python_ arrays
&
Library
By
Srikanth Pragada
COPYRIGHT
Copyright @ 2020 by Srikanth Technologies. 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.
Srikanth Technologies
Python Language and Library 3
When he is not teaching or learning, he would like to visit new places, read
books, play sports and listen to music.
Srikanth Technologies
4 Python Language and Library
You are suggested to read relevant content before and after attending the
class.
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.
TABLE OF CONTENT
Copyright.........................................................................................................................2
About the Author............................................................................................................3
How to use this material................................................................................................4
Request for Feedback.....................................................................................................4
Srikanth Technologies
Python Language and Library 5
Table of Content.............................................................................................................5
Python Language..........................................................................................................11
Installation of python...................................................................................................12
Using Python Interpreter - REPL...................................................................................14
Interactive Mode..........................................................................................................14
Variables.......................................................................................................................15
Rules for Identifier........................................................................................................15
Operators.....................................................................................................................16
Assignment operator (=)...........................................................................................16
Arithmetic Operators................................................................................................17
Relational Operators.................................................................................................18
Logical Operators......................................................................................................18
Built-in Data Types.......................................................................................................19
Keywords......................................................................................................................21
Built-in Functions..........................................................................................................22
function input()............................................................................................................25
Using print() function................................................................................................25
Formatted output......................................................................................................26
The f-string................................................................................................................27
The if statement............................................................................................................28
Conditional Expression..................................................................................................29
The while loop...............................................................................................................30
The range() function......................................................................................................31
The pass Statement......................................................................................................31
Srikanth Technologies
6 Python Language and Library
The for statement.........................................................................................................32
break, CONTINUE and else...........................................................................................33
Strings...........................................................................................................................35
The List Data Structure.................................................................................................40
List Comprehension..................................................................................................42
The del statement........................................................................................................43
Looping sequence.........................................................................................................46
Srikanth Technologies
Python Language and Library 7
Srikanth Technologies
8 Python Language and Library
Srikanth Technologies
Python Language and Library 9
Srikanth Technologies
10 Python Language and Library
Classes .............................................................................................................................
79
__init__ method .........................................................................................................
79 Private members (Name
Mangling) ............................................................................ 80
Static methods and variables ..........................................................................................
82
Class Methods .................................................................................................................
83 Comparison of
methods .............................................................................................83
Built-in methods related to Attributes ...........................................................................
84
Built-In Class Attributes ..................................................................................................
85
Special Methods .............................................................................................................
86
Relational operators ...................................................................................................
86
Unary operators ..........................................................................................................
86
Binary operators .........................................................................................................
89
Srikanth Technologies
Python Language and Library 11
Srikanth Technologies
12 Python Language and Library
Srikanth Technologies
Python Language and Library 13
Srikanth Technologies
14 Python Language and Library
Srikanth Technologies
Python Language and Library 15
Srikanth Technologies
16 Python Language and Library
PYTHON LANGUAGE
INSTALLATION OF PYTHON
1. Go to python.org (https://www.python.org/downloads).
2. Click on Downloads menu and select your platform.
3. It will take you to related downloads page. For example, for Windows it
takes you to https://www.python.org/downloads/windows/
Srikanth Technologies
Python Language and Library 17
Srikanth Technologies
18 Python Language and Library
Srikanth Technologies
Python Language and Library 19
❑ Go to command prompt.
❑ Make sure system PATH is set to folder where Python was installed. If that
is 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 (REPL).
Srikanth Technologies
20 Python Language and Library
c:\classroom>python
Python 3.8.2 (tags/v3.8.2:6f8c832, May 13 2020,
22:37:02)
[MSC v.1924 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
Srikanth Technologies
Python Language and Library 21
❑ Two or more string literals (i.e. the ones enclosed between quotes) next to
each other are automatically concatenated.
Srikanth Technologies
22 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.
While creating names for variables, function and other identifiers, we need to
follow the rules given below:
Srikanth Technologies
Python Language and Library 23
OPERATORS
The following are different types of operators available in Python.
Arithmetic Operators
The following are available arithmetic operators:
Srikanth Technologies
24 Python Language and Library
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
Relational Operators
The following relational operators are available:
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Srikanth Technologies
Python Language and Library 25
Logical Operators
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.
DataType Meaning
Srikanth Technologies
26 Python Language and Library
Srikanth Technologies
Python Language and Library 27
>>> v1 = 10
>>> v2 = 10.50
>>> v3 = "Python"
>>> v4 = True
Srikanth Technologies
28 Python Language and Library
>>> type(v1)
<class 'int'>
>>> type(v2)
<class 'float'>
>>> type(v3)
<class 'str'>
>>> type(v4)
<class 'bool'>
KEYWORDS
BUILT-IN FUNCTIONS
Function Meaning
abs(x) Returns the absolute value of a number.
all(iterable) Returns True if all elements of the iterable are true
Srikanth Technologies
Python Language and Library 29
Srikanth Technologies
30 Python Language and Library
>>> abs(-10)
10
Srikanth Technologies
Python Language and Library 31
>>> bin(10)
'0b1010'
>>> chr(65)
'A'
>>> a = 10
>>> id(a)
140728047310784
>>> max(10, 20, 30)
30
>>> ord('a')
97
>>> round(10.566)
11
>>> type(True)
<class 'bool'> >>>
Srikanth Technologies
32 Python Language and Library
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 required type using
other 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
>>> print("Python", 3.8, sep= " - ", end = "\n\n")
Python - 3.8
>>>
Formatted output
❑ It is possible to print formatted output using % with conversion characters
like %d and %s.
Srikanth Technologies
Python Language and Library 33
❑ 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)
The f-string
❑ F-string is a string prefixed with f and inserts values of variables when
variables are enclosed in {} inside the string.
Srikanth Technologies
34 Python Language and Library
❑ New feature of Python 3.6.
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 > 0:
print("Positive") elif a < 0: print("Negative")
else:
print("Zero")
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
Srikanth Technologies
36 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.
Srikanth Technologies
Python Language and Library 37
If start is not given then 0 is taken, if step is not given then 1 is taken.
The pass statement does nothing. It can be used when a statement is required
syntactically but the program requires no action.
Srikanth Technologies
38 Python Language and Library
THE FOR STATEMENT
Executes given statements until list is exhausted.
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.
Srikanth Technologies
Python Language and Library 39
Srikanth Technologies
40 Python Language and Library
STRINGS
Srikanth Technologies
Python Language and Library 41
❑ There is no separate character type; a character is simply a string of size
one.
❑ Indices may also be negative numbers, to start counting from the right.
❑ In addition to indexing, slicing is also supported. While indexing is used to
obtain individual characters, slicing allows you to obtain substring.
❑ Slice indices have useful defaults; an omitted first index defaults to zero, an
omitted second index defaults to the size of the string being sliced.
Method Description
capitalize() Returns a copy of the string with its first
character capitalized and the rest lowercased.
count(sub[, start[, Returns the number of non-overlapping
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.
Srikanth Technologies
42 Python Language and Library
>>>name="Python"
>>>name[0]
'P'
>>>name[-1] # Last char
'n'
>>> name[-3:] # Take chars from 3rd char from end
Srikanth Technologies
44 Python Language and Library
'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'
Srikanth Technologies
Python Language and Library 45
Srikanth Technologies
46 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.
Srikanth Technologies
Python Language and Library 47
List Comprehension
Srikanth Technologies
48 Python Language and Library
Srikanth Technologies
Python Language and Library 49
THE DEL STATEMENT
Removes one or more items from the list.
del item
>>> a = [10,20,30,40,50]
>>> del a[0]
>>> a
[20, 30, 40, 50]
>>> del a[1:3]
>>> a
[20, 50]
>>> del a[:]
>>> a
[]
>>> del a
>>> a # Throws error
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
Srikanth Technologies
50 Python Language and Library
Srikanth Technologies
Python Language and Library 51
THE TUPLE DATA STRUCTURE
❑ A tuple consists of a number of values separated by commas.
❑ 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.
❑ Tuples are immutable, and usually contain a heterogeneous sequence of
elements that are accessed via unpacking or indexing.
❑ 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).
Srikanth Technologies
52 Python Language and Library
>>> print(n,t,y)
Python Language 1991
>>>
Srikanth Technologies
53 Python Language and Library
LOOPING SEQUENCE
❑ When looping through a sequence, the position index and corresponding
value can be retrieved at the same time using the enumerate() function.
❑ To loop over two or more sequences at the same time, the entries can be
paired with the zip() function.
❑ To loop over a sequence in sorted order, use the sorted() function which
returns a new sorted list while leaving the source unaltered.
01 l1 = [10,20,30,40]
02 l2 = [100,200,300]
03
04 for i, n in enumerate(l1):
05 print(i, n)
06
07 for n in zip(l1, l2):
08 print(n)
Output
0 10
1 20
2 30
3 40
(10, 100)
(20, 200)
(30, 300)
Srikanth Technologies
54 Python Language and Library
❑ 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 set Tests whether every element in the set is in other.
<= 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 set Returns a new set with elements from the set and all
| other | ... others.
intersection(*others) Returns a new set with elements common to the set
or set & other and all others.
& ...
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 set Updates the set, adding elements from all others.
|= other
Srikanth Technologies
Python Language and Library 55
Srikanth Technologies
56 Python Language and Library
Set Comprehension
It is used to create a set from the given iterable, optionally based on condition.
❑ Dictionaries are indexed by keys, which can be any immutable type; strings
and numbers can always be keys.
Srikanth Technologies
Python Language and Library 57
❑ It is best to think of a dictionary as an unordered set of key: value pairs,
with the requirement that the keys are unique (within one dictionary).
❑ Placing a comma-separated list of key:value pairs within the braces adds
initial key:value pairs to the dictionary.
❑ It is an error to extract a value using a non-existent key.
❑ The dict() constructor builds dictionaries directly from sequences of
keyvalue pairs.
❑ When looping through dictionaries, the key and corresponding value can
be retrieved at the same time using the items() method.
Srikanth Technologies
58 Python Language and Library
Method Meaning
d[key] Returns the item of d with key 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 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. default defaults to None.
update([other]) Updates the dictionary with the key/value pairs from
Srikanth Technologies
Python Language and Library 59
Srikanth Technologies
60 Python Language and Library
Dictionary Comprehension
It is possible to create a dictionary by taking values from an iterable.
Srikanth Technologies
Python Language and Library 61
Srikanth Technologies
62 Python Language and Library
FUNCTIONS
❑ The keyword def introduces a function definition. It must be followed by
the function name and the parenthesized list of formal parameters. The
statements that form the body of the function start at the next line, and
must be indented.
❑ The first statement of the function body can optionally be a string literal;
this string literal is the function’s documentation string, or docstring.
❑ Variable references first look in the local symbol table, then in the local
symbol tables of enclosing functions, then in the global symbol table, and
finally in the table of built-in names.
❑ Arguments are passed using call by value (where the value is always an
object reference, not the value of the object).
❑ In fact, even functions without a return statement do return a value – None.
Srikanth Technologies
Python Language and Library 63
01 # Function to return factorial of the given
number 02 def factorial(num):
03 fact=1
04 for i in range(1,num + 1):
05 fact *= i
06
07 return fact
Srikanth Technologies
64 Python Language and Library
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.
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 should
appear before varying argument.
Srikanth Technologies
Python Language and Library 65
07 print_message("Steve","Jeff",message="Good
Morning")
KEYWORD ARGUMENTS
❑ A function can be defined to take arbitrary sequence of keyword arguments
by defining a parameter with ** as prefix.
❑ Function treats this parameter as a dictionary and provides all keyword
arguments as keys in dictionary.
❑ A function can be called with keyword arguments using kwarg=value,
where kwarg is keyword and value is value.
❑ In a function call, keyword arguments must follow positional arguments, if
any are present.
name Srikanth
email [email protected]
Srikanth Technologies
66 Python Language and Library
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 arguments, Python throws
error as follows:
Srikanth Technologies
Python Language and Library 67
POSITIONAL-ONLY ARGUMENTS
❑ Starting from Python 3.8, it is possible to create a function that takes
parameters only by position and not by keywords.
❑ Give a / (slash) after all parameters that are to be positional only.
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'
Srikanth Technologies
Python Language and Library 68
PASSING FUNCTION AS A PARAMETER
Srikanth Technologies
Python Language and Library 69
The following examples show how to use a function as a parameter with
builtin functions filter, sorted and map.
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)
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)
Srikanth Technologies
70 Python Language and Library
Sorted function
Sorts the given iterable and returns a list with sorted values.
The following code sorts names by length of the name and not by characters.
01 names =
["Php","Java","C","Python","JavaScript","C#"] 02
for n in sorted(names, key=len): 03 print(n)
C
C#
Php
Java
Python
JavaScript
Srikanth Technologies
Python Language and Library 71
Srikanth Technologies
72 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)
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.
Srikanth Technologies
Python Language and Library 73
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.
01 nums = [10,11,33,45,44]
02
03 # with lambda, get all odd numbers
04 for n in filter (lambda v: v % 2 == 1, nums):
05 print(n)
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.
Srikanth Technologies
74 Python Language and Library
❑ Some objects are mutable, some are immutable.
❑ All objects are passed by reference to a function. That means we pass
reference of the object and not the object itself.
❑ But whether the function can modify the value of the object depends on
the mutability of the object.
❑ So, if you pass a string, it behaves like pass by value as we can’t change
actual parameter with formal parameter.
❑ If you pass a list (mutable object) then it behaves like pass by reference as
we can use formal parameter to change actual parameter.
[10, 20]
Srikanth Technologies
Python Language and Library 75
Output:
Original Ids : id(n1) 503960768 id(n2) 503960928
Inside swap() : id(n1) 503960928 id(n2) 503960768
Values : 20 10
Values after swap : 10 20
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.
Srikanth Technologies
76 Python Language and Library
❑ 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.
VARIABLE’S SCOPE
❑ Variables that are defined outside all functions in a module are called global
variables and can be accessed from anywhere in the module.
❑ Variables created inside a function can be used only inside the function.
Srikanth Technologies
Python Language and Library 77
❑ Keyword global is used to access a global variable from a function so that
Python doesn’t create a local variable with the same name when you assign
a value to a variable.
❑ Python looks in the order – local, enclosing, global and built-in (LEGB)
variables.
MODULES
❑ A module is a file containing Python definitions (functions and classes) and
statements.
Srikanth Technologies
78 Python Language and Library
❑ It can be used in a script (another module) or in an interactive instance of
the interpreter.
❑ A module can be imported into other modules or run as a script.
❑ The file name is the module name with the suffix .py appended. Within a
module, the module’s name (as a string) is available as the value of the
global variable __name__.
❑ A module can contain executable statements as well as function and class
definitions. These statements are intended to initialize the module. They
are executed only the first time the module name is encountered in an
import statement.
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))
Srikanth Technologies
Python Language and Library 79
❑ 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.
Srikanth Technologies
80 Python Language and Library
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.
Srikanth Technologies
Python Language and Library 81
help([object])
Use SPACE key to go to next page and Q to quit the help
system.
❑ 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 are
added to module search path.
c:\python>set PYTHONPATH=c:\dev\python;c:\dev\projects
Srikanth Technologies
82 Python Language and Library
sys.path.append(r'c:\dev\python\projects')
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 and when run as
script
06 print("Code in Module1")
07
08 # code executed only when run as
script 09 if __name__ == "__main__":
Srikanth Technologies
Python Language and Library 83
10 print("Running as script")
When you run the above code as script (python.exe module1.py) the following
output is generated:
Code in Module1
Running as script
But when you import this module into another file as shown below then the
output shown below is generated.
Srikanth Technologies
84 Python Language and Library
use_module1.py
01 import module1
02
03 module1.print_info()
Code in Module1
I am in module1.print_info()
Srikanth Technologies
Python Language and Library 85
USING COMMAND LINE ARGUMENTS
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)
DOCUMENTATION
Srikanth Technologies
86 Python Language and Library
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
PACKAGES
Folder Structure
use_st_lib.py
stlib
__init__.py
str_funs.py
stlib\str_funs.py
01 def has_upper(st):
02 # code
03 def has_digit(st):
04 # code
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.8"))
Importing with *
Srikanth Technologies
88 Python Language and Library
❑ 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.
stlib\__init__.py
__all__ = ["num_funs", "str_funs"]
The following are some of the important options available with PIP:
Srikanth Technologies
Python Language and Library 89
CLASSES
class className:
definition
__init__ method
Srikanth Technologies
90 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("iPhone 11",80000) # create object
12 p.print_details()
Srikanth Technologies
Python Language and Library 91
❑ However, a convention followed by most Python programmers is, an
attribute prefixed with an underscore (e.g. _salary) should be treated as
non-public part of the API.
❑ Any identifier of the form __salary (two leading underscores) is textually
replaced with _classname__salary, where classname is the current class
name with leading underscore(s) stripped. This process is called as name
mangling.
❑ It still is possible to access or modify a variable that is considered private
from outside the class.
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.
Srikanth Technologies
92 Python Language and Library
The following code fails to access __name attribute because due to name
mangling its name is prefixed with class name.
However, you can access private attributes from outside if you use _classname
as prefix as shown below:
Srikanth Technologies
Python Language and Library 93
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))
CLASS METHODS
Srikanth Technologies
94 Python Language and Library
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, name [, Returns the value of the named attribute of
default]) object If 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.
>>> Product.__module__
'__main__'
>>> Product.__bases__
(<class 'object'>,)
>>> Product.__dict__
mappingproxy({'__module__': '__main__', 'tax': 10,
'__init__': <function Product.__init__ at
0x00000269FF186280>, '__dict__': <attribute '__dict__'
of 'Product' objects>, '__weakref__': <attribute
'__weakref__' of 'Product' objects>, '__doc__': None})
SPECIAL METHODS
Relational operators
Srikanth Technologies
Python Language and Library 97
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
Operator Method
- object.__neg__(self)
+ object.__pos__(self)
abs() object.__abs__(self)
~ object.__invert__(self)
complex() object.__complex__(self)
int() object.__int__(self)
long() object.__long__(self)
float() object.__float__(self)
oct() object.__oct__(self)
hex() object.__hex__(self
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 """
Srikanth Technologies
Python Language and Library 99
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
01:20:30
False
False
True
11:40:60
Srikanth Technologies
Python Language and Library 101
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)
Extended assignments
Here are special methods related to extended operators.
Operator Method
+= object.__iadd__(self, other)
-= object.__isub__(self, other)
Srikanth Technologies
102 Python Language and Library
*= 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)
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 and one to set value.
❑ Properties provide advantages like validation, abstraction and lazy loading.
Srikanth Technologies
Python Language and Library 103
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("Srikanth", "Pragada")
16 print(p.name) # Calls @property getter method
17 p.name="Pragada Srikanth" #Calls @name.setter
method
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.
Srikanth Technologies
104 Python Language and Library
❑ 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.
Srikanth Technologies
Python Language and Library 105
Note: Every class that is not a subclass of another class is implicitly inheriting
object class.
Srikanth Technologies
106 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())
Srikanth Technologies
Python Language and Library 107
Output:
Scott
100000
Net Salary : 100000
Mike
150000
50000
Net Salary : 200000
Overriding
isinstance(object, class)
issubclass(class, class)
Srikanth Technologies
108 Python Language and Library
e = Employee(…)
print("Employee ?? ", isinstance(e, Employee)) # True
print("Manager subclass of Employee ?? ",
issubclass(Manager, Employee)) # True
Srikanth Technologies
Python Language and Library 109
MULTIPLE INHERITANCE
Python supports a form of multiple inheritance as well. A class definition with
multiple super classes looks like this:
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
Srikanth Technologies
110 Python Language and Library
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
Method mro()
Method mro() returns method resolution order, which is the order of the
classes that Python searches for a method.
For the above example, calling method mro() on class D will return the
following:
Srikanth Technologies
Python Language and Library 111
Srikanth Technologies
112 Python Language and Library
ABSTRACT CLASS AND METHODS
Srikanth Technologies
Python Language and Library 113
EXCEPTION HANDLING
❑ Errors detected during execution are called exceptions.
❑ Exceptions come in different types, and the type is printed as part of the
message: the types are ZeroDivisionError, KeyError and AttributeError.
❑ BaseException is base class for all built-in exceptions.
❑ Exception is base class for all built-in, non-system-exiting exceptions. All
user-defined exceptions should also be derived from this class.
❑ After try block, at least one except block or finally block must be given.
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.
Srikanth Technologies
114 Python Language and Library
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!
Srikanth Technologies
Python Language and Library 115
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!
The following program takes numbers from user until 0 is given and then
displays sum of given numbers.
Srikanth Technologies
116 Python Language and Library
01 sum = 0 02
while True:
03 num = int(input("Enter number [0 to
stop] :")) 04 if num == 0:
05 break
06
07 sum += num
08
09 print(f"Sum = {sum}")
But the program is fragile as any invalid input will crash programs 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.
Srikanth Technologies
Python Language and Library 117
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:
09 print("Invalid Number!")
10
11 print(f"Sum = {total}")
In the output below, whenever invalid input is given an error is displayed and
program continues till end.
BaseException
+-- SystemExit
Srikanth Technologies
118 Python Language and Library
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
Srikanth Technologies
Python Language and Library 119
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
raise [expression]
Srikanth Technologies
120 Python Language and Library
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("Invalid Amount!") #Raise Ex
04 except Exception as ex:
05 print("Error : ", ex)
THE ITERATOR
Srikanth Technologies
Python Language and Library 121
❑ 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
>>>
Srikanth Technologies
122 Python Language and Library
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
14 class Marks:
Srikanth Technologies
Python Language and Library 123
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)
Srikanth Technologies
124 Python Language and Library
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 functions.
Srikanth Technologies
Python Language and Library 125
Generator Expression
Generator expression creates a generator object that returns a value at a time.
Srikanth Technologies
126 Python Language and Library
FILE HANDLING
The following are important functions related to file handling.
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).
Srikanth Technologies
Python Language and Library 127
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.
Srikanth Technologies
128 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()
It is a good practice to use the with keyword when dealing with file objects. The
advantage is that the file is properly closed after its suite finishes, even if an
exception is raised at some point.
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.
Srikanth Technologies
Python Language and Library 129
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()}")
Note: While reading lines from file, readlines() reads line along with new line (\
n) character at the end of the line.
Srikanth Technologies
130 Python Language and Library
The following program displays all customer names and phone numbers in the
sorted order of customer name.
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}")
Srikanth Technologies
Python Language and Library 131
PICKLE – PYTHON OBJECT SERIALIZATION
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 object
hierarchy specified therein.
loads(bytes_object) Reads a pickled object hierarchy from a bytes object
and returns the reconstituted object hierarchy specified
Srikanth Technologies
132 Python Language and Library
therein.
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("Srikanth","[email protected]")
12 pickle.dump(p1,f) #pickle object
13 print("Dumped object to file!")
14 f.close()
JSON MODULE
Srikanth Technologies
Python Language and Library 133
❑ JSON stands for JavaScript Object Notation.
❑ It converts a dict in Python to JSON object.
❑ It converts a JSON object back to dict object in Python.
❑ JSON array is converted to Python list.
❑ Any Python iterable is converted to JSON array.
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("Srikanth",
10 "9059057000",
11 "[email protected]")
12 print(json.dumps(c.__dict__))
Srikanth Technologies
134 Python Language and Library
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","[email protected]
"),
02 Contact("B","9999988888","[email protected]"
))
03 # convert each Contact object to dict
using map()
04 clist = list(map(lambda c :
c.__dict__, contacts)) 05
print(json.dumps(clist))
SYS MODULE
Member Meaning
Srikanth Technologies
Python Language and Library 135
OS MODULE
Function Meaning
chdir(path) Changes current directory.
Srikanth Technologies
136 Python Language and Library
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.
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
Srikanth Technologies
Python Language and Library 137
01 import os
02
03 # Get all files and folders from the given path
04 allfiles = os.walk(r"c:\dev\python\lang")
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)
Character Description
[] A set of characters
\ Signals a special sequence (can also be used to escape special
characters)
Srikanth Technologies
138 Python Language and Library
The following are special sequences that have special meaning in a regular
expression.
Character Description
\d Returns a match where the string contains digits (numbers from
0-9).
\D Returns a match where the string DOES NOT contain digits.
\s Returns a match where the string contains a white space
character.
\S Returns a match where the string DOES NOT contain a white
space character.
\w Returns a match where the string contains any word characters
(characters from a to Z, digits from 0-9, and the underscore _
character).
\W Returns a match where the string DOES NOT contain any word
characters.
Srikanth Technologies
Python Language and Library 139
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 of
string,flags=0) 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 expression
string,flags=0) pattern, returns a corresponding match object.
Returns None if the string does not match the
pattern.
>>> 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)
>>> re.search(r'\d+',st)
<re.Match object; span=(4, 7), match='123'> >>>
>>> re.findall(r'\d+',st)
['123', '456']
>>> re.split(r'[a-z ]+',st) ['', '123', '456']
>>> re.sub(r'[0-9]','.',st)
'abc ... xyz pqr ...'
Srikanth Technologies
Python Language and Library 141
Match Object
Match object is returned by match() and search() and fullmatch() functions of
re module.
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.
Srikanth Technologies
142 Python Language and Library
The following example uses grouping concept to extract name and phone
number from the given string.
Srikanth Technologies
Python Language and Library 143
❑ Type time contains hour, minute, second and microsecond.
❑ Type datetime is a composite of date and time.
❑ Type timedelta contains days, seconds, microseconds.
❑ They are all immutable.
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).
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
Srikanth Technologies
144 Python Language and Library
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
Srikanth Technologies
146 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
Srikanth Technologies
Python Language and Library 147
Srikanth Technologies
148 Python Language and Library
(en_US)
>>> cd = datetime.now()
>>> cd.strftime("%d-%m-%Y %H:%m:%S") '19-03-2020
15:03:07'
The following program takes date of birth from user and displays age in years,
months and days.
Srikanth Technologies
Python Language and Library 149
MULTITHREADING
Srikanth Technologies
150 Python Language and Library
Functions in threading module
The following are functions provided in multithreading module.
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
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.
The following program creates a thread to check whether the given number is
prime or not.
Srikanth Technologies
Python Language and Library 151
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()
REQUESTS MODULE
Requests is an elegant and simple HTTP library for Python, built for human
beings.
Srikanth Technologies
152 Python Language and Library
The following are important methods of requests module:
The Response object contains server’s response for an HTTP request. When a
request is made using requests module, it returns an object of Response
class.
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.
01 import requests
02
03 code = input("Enter country code :")
04
05 resp = requests.get
06 (f"https://restcountries.eu/rest/v2/alpha/
{code}") 07 if resp.status_code == 404:
08 print("Sorry! Country code not
found!") 09 elif resp.status_code != 200:
10 print("Sorry! Could not get country
details!") 11 else:
12 details = resp.json() # Convert JSON to
dict
13 print("Country Information");
14 print("Name : " + details["name"])
15 print("Capital : " + details["capital"])
16 print("Population : " +
17 str(details["population"])) 18
print("Sharing borders with :") 19 for c in
details["borders"]:
20 print(c)
BEAUTIFULSOUP MODULE
❑ 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.
Srikanth Technologies
154 Python Language and Library
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
Srikanth Technologies
Python Language and Library 155
02
03 with open("schedule.html") as f:
04 soup = BeautifulSoup(f, "html.parser")
Tag Object
Property Meaning
name Name of the tag
text Text of the tag
[attribute] Provides value for the given attribute
contents Provides all children of the tag
children Allows iteration over tag’s children
descendants Provides all descendants of the tag
Srikanth Technologies
156 Python Language and Library
Srikanth Technologies
Python Language and Library 157
# A simple string
soup.find_all('b')
# A regular expression
soup.find_all(re.compile("^b"))
Srikanth Technologies
158 Python Language and Library
DATABASE PROGRAMMING
❑ Python supports different databases.
❑ Python Database API Specification has been defined to provide similarity
between modules to access different databases.
❑ Database API is known as Python DB-API 2.0 with PEP 249 at
https://www.python.org/dev/peps/pep-0249
❑ It enables code that is generally more portable across databases as all
database modules provide the same API.
❑ Modules required to access database are to be downloaded.
❑ Module sqlite3, which is used to access SQLite database, is provided along
with Python.
Srikanth Technologies
Python Language and Library 159
SQLite3 Database
❑ SQLite is a C library that provides a lightweight disk-based database that
doesn’t require a separate server process and allows accessing the
database using a nonstandard variant of the SQL query language.
❑ It is possible to prototype an application using SQLite and then port the
code to a larger database such as Oracle.
❑ Python ships with SQLite Database.
MODULE SQLITE3
❑ It is the interface for SQLite database.
❑ This module is part of Python standard library.
❑ It implements DB API 2.0 specifications (PEP 249).
Srikanth Technologies
160 Python Language and Library
Method connect()
connect(parameters...)
Connection object
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.
Cursor Object
❑ Cursor represents a database cursor, which is used to manage the context
of a fetch operation.
Srikanth Technologies
Python Language and Library 161
❑ 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.
Srikanth Technologies
162 Python Language and Library
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
The following program shows how to connect to a database and create a table.
Srikanth Technologies
Python Language and Library 163
01 import sqlite3
02 con = sqlite3.connect(r"c:\dev\python\
test.db")
03 cur = con.cursor() 04 # create a table 05 try:
06 cur.execute("create table expenses
07 (id integer, date text, desc text, amount
real)") 08 print("Table EXPENSES created
successfully!") 09 except Exception as ex:
10 print("Sorry! Error : ",
ex.message) 11 finally:
12 con.close()
Srikanth Technologies
164 Python Language and Library
01 import sqlite3
02 con = sqlite3.connect(r"c:\dev\python\
test.db")
03 cur = con.cursor()
04
05 # insert a row
06 try:
07 # take data from user
08 des = input("Enter Description :")
09 amt = input("Enter Amount :")
10 row = (des, amt)
11 cur.execute("insert into expenses
12 (description, amount) values(?,?)", row)
13 con.commit()
14 print("Added successfully!") 15 except
Exception as ex: 16 print("Sorry! Error: ",
ex) 17 finally:
18 con.close()
Srikanth Technologies
Python Language and Library 165
01 import sqlite3
02
03 con = sqlite3.connect(r"c:\dev\python\test.db")
04 cur = con.cursor()
05
06 # List rows from EXPENSES
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 else:
12 cur.close()
13 except Exception as ex: 14
print("Error : ", ex) 15 finally:
16 con.close()
Srikanth Technologies
166 Python Language and Library
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("update expenses set amount=?
12 where id = ?", (amount,
id)) 13 if cur.rowcount == 1:
14 con.commit()
15 print("Updated successfully!") 16
else:
17 print('Sorry! Id not
found!') 18 except Exception as ex:
19 print("Sorry! Error: ", ex)
20 finally:
21 con.close()
Srikanth Technologies
Python Language and Library 167
01 import sqlite3
02
03 con = sqlite3.connect(r"c:\dev\python\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("delete from expenses where id=?",
(id,)) 11 if cur.rowcount == 1:
12 con.commit()
13 print("Deleted successfully!") 14
else:
15 print('Sorry! Id not
found!') 16 except Exception as ex:
17 print("Sorry! Error: ", ex)
18 finally:
19 con.close()
Srikanth Technologies
168 Python Language and Library
http://www.oracle.com/technetwork/database/database-technologies/
instant-client/downloads/index.html
01 import os
02 import cx_Oracle
03
04 # Include Oracle Instant Client in System PATH
05 os.environ['PATH'] = 'c:\\oraclexe\\client'
06
07 # Connect using username hr and password hr
08 con = cx_Oracle.connect("hr/hr@localhost")
09 print("Connected to Oracle successfully!") 10
con.close()
Srikanth Technologies
169 Python Language and Library
01 import os
02 import cx_Oracle
03
04 os.environ['PATH'] = 'c:\\oraclexe\\client'
05 con = cx_Oracle.connect("hr/hr@localhost")
06 cur = con.cursor()
07
08 # using names for parameters
09 cur.execute
10 ("insert into jobs
values(:id,:title,:min,:max)",
11 id='PP',title='Python Programmer',min=5000,
max=1000);
12 print("Inserted Job Successfully!")
13
14 # Using numbers for parameters
15 cur.execute("insert into jobs
values(:1,:2,:3,:4)",
16 ('PyP', 'Python Programmer', 5000, 1000));
17 print("Inserted Job Successfully!")
18 cur.close()
19 con.commit() 20 con.close()
Srikanth Technologies
170 Python Language and Library
http://www.srikanthtechnologies.com/blog/python/using_cx_oracle.aspx
Srikanth Technologies