You are on page 1of 196

DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING

Study Material for Academic Year 2020-21 (Odd Semester)

COURSE NAME : PYTHON PROGRAMMING

COURSE CODE : 19ISE36

SEMESTER : III

Department of ISE NHCE


PYTHON PROGRAMMING
19ISE36
UNIT1
Introduction to Python: The basic elements of Python, The first Program, Objects, Expression,
Numerical Types, Variables, Keywords and Assignments, multiple Assignments, Operators and
Operands, Order of operations, Decision making, Loop control structures, Input data handling

PYTHON INTRODUCTION

Python is one of the most popular programming languages in this era.

Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-
68, SmallTalk, and Unix shell and other scripting languages.

Python source code is now available under the GNU General Public License (GPL).
Python 1.0 was released on 20 February, 1991.Python 2.0 was released on 16 October
2000 and had many major new features.

Python 3.0 was released on 3 December 2008.

WHO USES PYTHON TODAY?

 Google makes extensive use of Python in its web search systems.


 The popular YouTube video sharing service is largely written in Python.
 The Dropbox storage service codes both its server and desktop client software primarily
in Python.
 Instagram , Quora websites extensively developed in python
 The Raspberry Pi single-board computer promotes Python as its educational language.
 The widespread BitTorrent peer-to-peer file sharing system began its life as a Python
program.
 Google‗s App Engine web development framework uses Python as an application
language.
 Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware
testing.
 NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific programming
tasks.

APPLICATIONS OF PYTHON

 Python is used inWeb Development using Django framework


 Data Science and Machine Learning using PyBrain, scikit-learn etc)
 Python is used in Data Analytics (matplotlib)
 Python is used in Artificial Intelligence (AIMA, pyDatalog) and Scientific Computing
(numpy)
 Image Processing (OpenCV) and Signal Processing (scipy.signal) using Python
 Robotics (ROS – Robotics OS, pyro)
 Games development is performed using Python
PYTHON FEATURES

Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.

Easy-to-read: Python code is more clearly defined and visible to the eyes.

Easy-to-maintain: Python's source code is fairly easy-to-maintain.

A broad standard library: Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.

Interactive Mode: Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.


Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.

Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.

Databases support: Python provides interfaces to all major commercial databases.

GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries, and windows systems, such as Windows MFC, Macintosh,
and the X Window system of UNIX.


Scalable: Python provides a better structure and support for large programs than shell
scripting.

INTERPRETED VERSUS COMPILED

Compiler: A compiler is a computer program that transforms (translates) source code of a


programming language into another computer language (the target language) which a
sequence of machine-level primitive operations. Compiled languages usually produce
programs that run more quickly and use less space.
1. Scans the entire program and translates it as a whole into machine code.
2. It takes large amount of time to analyze the source code but the overall execution time
is comparatively faster.
3. It generates the error message only after scanning the whole program. Hence
debugging is comparatively hard.
4. Programming language like C, C++ use compilers.
Interpreter: An interpreter is a computer program that executes instructions written in a
programming language. It translates the source code in a first step into a more efficient
representation and executes this code
1. Interpreter translates program one statement at a time.
2. It takes less amount of time to analyze the source code but the overall execution time
is slower.
3. Continues translating the program until the first error is met, in which case it stops.
Hence debugging is easy.
4. An interpreter works in exactly the same way as a compiler, with one difference:
instead of code generation, it loads the output in-memory and executes it directly on
your system.
5. Programming language like Python, Ruby use interpreters.

CODE TRANSLATION IN PYTHON

Python first compiles the source code (the statements in the file with extension .py file) into a
format known as byte code . Compilation is simply a translation step, and byte code is a
lower-level, and platform- independent, representation of your source code. Compiled code is
usually stored in .pyc files , and is regenerated when the source is updated.

Python translates each of your source statements into a group of byte code
instructions by decomposing them into individual steps. This byte code translation is
performed to speed execution —byte code can be run much more quickly than the original
source code statements.

The bytecode (.pyc file) is loaded into the Python runtime and interpreted by a Python Virtual
Machine , which is a piece of code that reads each instruction in the bytecode and executes
whatever operation is indicated. Byte code compilation is automatic, and the PVM is just part
of the Python system that you have installed on the machine. Technically, it's just the last step
of what is called the Python interpreter.

Figure : Byte code Compilation

Once your program has been compiled to byte code (or the byte code has been loaded from
existing .pyc file), it is executed on the python virtual machine (PVM) (Cpython VM)
The standard Python implementation is a byte code virtual machine. This means that the
machine code (opcodes from your processor's opcode set) is not generated from your
program. The opcodes are only selected from the opcodes that are already compiled into the
virtual machine while the VM interprets the byte code. Hence Python execution is called as
―the Python interpreter.‖

ENVIRONMENT SET UP / INSTALLING PYTHON

Python is freely downloadable from the internet. There are multiple IDEs (Integrated
Development Environment) available for working with Python. Some of them are PyCharm,
LiClipse, IDLE etc. When you install Python, the IDLE editor will be available
automatically. Because, there are separate set of editors (IDE) available for different OS like
Window, UNIX, Ubuntu, Soloaris, Mac, etc. Apart from all these editors, Python program can be
run on command prompt also. The basic Python can be downloaded from the link:

https://www.python.org/downloads/

Python has rich set of libraries for various purposes like large-scale data processing,
predictive analytics, scientific computing etc. Based on one‘s need, the required packages can
be downloaded. But, there is a free open source distribution Anaconda, which simplifies
package management and deployment. To install Anaconda

https://anaconda.org/anaconda/python

Successful installation of anaconda provides you Python in a command prompt, the default
editor IDLE and also a browser-based interactive computing environment known as jupyter
notebook. The jupyter notebook allows the programmer to create notebook documents
including live code, interactive widgets, plots, equations, images etc.

UNIX AND LINUX INSTALLATION


Steps to install Python on Unix/Linux machine.
 Open a Web browser and go to https://www.python.org/downloads/.
 Follow the link to download zipped source code available for Unix/Linux.
 Download and extract files.
 Editing the Modules/Setup file if you want to customize some options.
 run ./configure script
 make
 make install
This installs Python at standard location /usr/local/bin and its libraries at
/usr/local/lib/pythonXX where XX is the version of Python.

WINDOWS INSTALLATION
Steps to install Python on Windows machine.

 Open a Web browser and go to https://www.python.org/downloads/.


 Follow the link for the Windows installer python-XYZ.msi file where XYZ is the
version you need to install.
 To use this installer python-XYZ.msi, the Windows system must support Microsoft
Installer 2.0. Save the installer file to your local machine and then run it to find out if
your machine supports MSI.
 Run the downloaded file. This brings up the Python install wizard, which is really
easy to use. Just accept the default settings, wait until the install is finished, and you
are done.

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python


is designed to be highly readable. It uses English keywords frequently where as other
languages use punctuation, and it has fewer syntactical constructions than other languages.

SETTING UP PATH FOR PYTHON


Programs and other executable files can be in many directories, so operating systems provide
a search path that lists the directories that the OS searches for executables.The path is stored
in an environment variable, which is a named string maintained by the operating system. This
variable contains information available to the command shell and other programs.
The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive;
Windows is not).
Example of Python Installation Directory –

Step1 : Copy the below link C:\Users\Vandana\AppData\Local\Programs\Python\Python36-


34\Scripts
Step 2:Right click on my computer
Step3: Go to Properties  Advanced system setting  Environment variables
Step 4: create a new system variable  Give name as path and value as link shown in step 1
and put semicolon(;) at the end, click on ok at all windows

RUNNING PYTHON
A. RUNNING PYTHON INTERPRETER (REPL) INTERACTIVE SHELL MODE:

Python comes with an interactive interpreter (shell). When you type python in your
shell or command prompt, the python interpreter becomes active with a >>> prompt and
waits for your commands. When you type 2 + 3, Python took this command, calculated the
sum and then printed it. Again the same steps of reading, evaluating, printing happened for
the second command. This loop is called the read-eval-print-loop.
Now you can type any valid python expression at the prompt. Python reads the typed
expression, evaluates it and prints the result.

Python shell can be used a simple calculator. The recent output value is automatically stored
by the interpreter in special variable name ―_‖.The underscore variable is only in python
shell. It is NOT available in python scripts.

>>> hex(65)
'0x41'
>>> int(0x41)
65

B. RUNNING PYTHON SCRIPTS IN IDLE (SCRIPT MODE):

Typing programs directly into the shell is highly inconvenient. Most programmers prefer to
use some sort of text editor that is part of an integrated development environment (IDE).
IDLE is an IDE (application) that comes as part of the standard Python installation package.
IDLE provides:
 a text editor with syntax highlighting, autocompletion, and smart indentation,
 a shell with syntax highlighting
 an integrated debugger, which you should ignore for now.

When IDLE starts it will open a shell window into which you can type Python commands. It
will also provide you with a file menu and an edit menu.

• Goto File menu click on New File (CTRL+N) and write the code and save add.py

a=int(input("Enter a value "))


b=int(input("Enter b value"))
c=a+b
print ("The sum is",c)

• Run the program by pressing F5 or Run

IDLE can be found in Anaconda inside Anaconda3\Lib\idlelib\idle.bat

The IDE shipped with Anaconda is Spyder, which is more powerful than IDLE. It comes
with a good editor with great code completion and code analysis features, an interactive help
widget, Python and IPython consoles, a variables explorer and more. It can be launched from
the Anaconda's launcher.

C. RUNNING PYTHON SCRIPTS IN COMMAND PROMPT:

 Before going to run we have to check the PATH in environment variables.


 Open your text editor, type the following text and save it as test.py.

 And run this program by calling python test.py. Make sure you change to the directory where
you saved the file before doing it.

OBJECTS

Objects are the core things that Python programs manipulate. Every object has a type that
defines the kinds of things that programs can do with objects of that type. Types are either
scalar or non-scalar. Scalar objects are indivisible. Basic Scalar objects are numbers
(int,float,complex),Boolean, None type. Non Scalar objects are string,list,tuple,dictionary.

Every Object in python has a reference place in memory. Python assigns a long number as
identifier of the memory location to each object. This can be checked using id() function. The
data type of the object can be observed using the type() function.

>>> id(23)
1423339264
>>> type(23)
<class 'int'>

Python is a dynamically typed language, as there is no advance declaration associating an


variable with a particular data type. An identifier or variable can be associated with any type
of object, and it can later be reassigned to another object of the same (or different) type.
Although an identifier/variable has no declared type, the object to which it refers has a
definite type.

VARIABLES

Variables are reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory. Variables provide a way to associate names
with objects.

Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.
ASSIGNING VALUES TO VARIABLES

Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables. An assignment statement associates the name to the left of the =
symbol with the object denoted by the expression to the right of the =.

The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable. For example –

MULTIPLE ASSIGNMENTS TO VARIABLES

Python allows you to assign a single value to several variables


simultaneously. For example –

a=b=c=1

Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.

a, b, c = 1, 2.5, ”mothi”

Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.

>>>x, y = 2, 3
binds x to 2 and y to 3.

>>>x, y = 2, 3
>>>x, y = y, x
>>>print( 'x =', x)
>>>print ('y =', y)

will print

x=3
y=2
After the assignment y = x, both refer to the same object. The identity function id() can be
used to find the identity of a variable. Every instance (object or variable) has an identity, i.e.
an integer which is unique within the script or program, i.e. other objects have different
identities.

>>> x = 42
>>> id(x)
10107136
>>> y = x
>>> id(x), id(y)
(10107136, 10107136)
>>> y = 78
>>> id(x), id(y)
(10107136, 10108288)

KEYWORDS

The following list shows the Python keywords. These are reserved words and you cannot use
them as constan-t or variable or any other identifier names. All the Python keywords contain
lowercase letters only. You can use help() utility on shell , followed by help>keywords to
find the keywords supported in python.

INPUT Function:

To get input from the user you can use the input function. When the input function is called
the program stops running the program, prompts the user to enter something at the keyboard
by printing a string called the prompt to the screen, and then waits for the user to press the
Enter key. The user types a string of characters and presses enter. Then the input function
returns that string and Python continues running the program by executing the next statement
after the input statement. Python provides the function input(). input has an optional
parameter, which is the prompt string.

Syntax: input(optional string)


A function float() is used to convert a valid value enclosed within quotes into float number
as shown below –
>>> f=input("Enter a float value:")
Enter a float value: 3.5
>>> type(f)
<class 'str'>
>>> f=float(f)
>>> type(f)
<class 'float'>

A function chr() is used to convert an integer input into equivalent ASCII character.
>>> a=int(input("Enter an integer:"))
Enter an integer:65
>>> ch=chr(a)
>>> print("Character Equivalent of ", a, "is ",ch)
Character Equivalent of 65 is A

OUTPUT function:

We use the print() function to output data to the standard output device (screen). This
function prints the object/string written in function.

The arguments of the print function are the following ones:

print(value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

The print function can print an arbitrary number of values ("value1, value2, ..."), which are
separated by commas. These values are separated by blanks as sep separator is used between
the values. It defaults into a space character. After all values are printed, end is printed. It
defaults into a new line ( \n ).

A print call is ended by a newline, as we can see in the following usage:

To change this behaviour, we can assign an arbitrary string to the keyword parameter "end".
This string will be used for ending the output of the values of a print call:

print("today", end =" ")


print("today is sunday")
>>> today today is sunday
>>> print("vandana\ncp")
vandana
cp

>>> print("18","2","2018",sep='-')
18-2-2018

>>> company="Flipkart"
>>> address="Bangalore"
>>> print(company, address, sep='@')
Flipkart@Bangalore
The output of the print function is send to the standard output stream (sys.stdout) by default.
By redefining the keyword parameter "file" we can send the output into a different stream
e.g. sys.stderr or a file:

INDENTATION

Python does not support braces to indicate blocks of code for class and function definitions or
flow control. Blocks of code are denoted by line indentation. All the continuous lines
indented with same number of spaces would form a block. Python strictly follow indentation
rules to indicate the blocks.

Code blocks are identified by indentation rather than using symbols like curly braces.
Without extra symbols, programs are easier to read. Also, indentation clearly identifies which
block of code a statement belongs to. Of course, code blocks can consist of single statements,
too. It makes Python simplistic in nature and easy to read. It ensures that the visual structure
of a program is an accurate representation of the semantic structure of that program.

All statements with the same distance to the right belong to the same block of code. The
block ends at a line less indented or the end of the file. If a block has to be more deeply
nested, it is simply indented further to the right.

COMMENTS

Python has commenting capability for the purpose of in-code documentation. Comments start
with a #, and Python will render the rest of the line as a comment. Python also has extended
documentation capability, called docstrings. Docstrings can be one line, or multiline.
Python uses triple quotes at the beginning and end of the docstring.
DATA TYPES
Based on what value is stored in variables and what operations we can do on them, variables
are grouped into so called Data types.
Numbers: Number data types store numeric values. Number objects are created when you
assign a value to them. They are immutable objects and cant change their values. Python
supports different numerical types:

 int is used to represent integers. Literals of type int are written in the way we typically denote
integers (e.g., -3 or 5 or 10002). There is only one "int" type,( which contains both "int" and
"long" from Python2) and is unlimited in size.
 float is used to represent real numbers. Literals of type float always include a decimal point
(e.g., 3.0 or 3.17 or -28.72). (It is also possible to write literals of type float using scientific
notation. For example, the literal 1.6E3 stands for 1.6*103, i.e., it is the same as 1600.0.)
 Complex numbers are written as <real part> + <imaginary part>j
For examples:
>>> x = 3 + 4j
>>> y = 2 - 3j
>>> z = x + y
>>> print(z)
(5+1j)

Strings: Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows either pair of single or double quotes.
Lists: Lists are the most versatile of Python's compound sequence data types. A list contains
items separated by commas and enclosed within square brackets ([ ]). They are mutable.
Tuples: A tuple is sequence data type that is similar to the list. A tuple consists of a number
of values separated by commas. Tuples are enclosed within parenthesis and are immutable
Dictionary: Python's dictionaries are kind of hash-table of key-value pairs. A dictionary key
can be any Python type, but are usually numbers or strings. Values, on the other hand, can be
any arbitrary Python object. Dictionaries are enclosed within curly braces.
STRING
A string is a sequence (contiguous set of characters) of characters, enclosed either within a
pair of single quotes or double quotes. Python allows for either pairs of single or double quotes.
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end. Each character of a string
corresponds to an index number, starting with zero as shown below –
S= ―Hello World‖

Character H e L l o w o r l d

index 0 1 2 3 4 5 6 7 8 9 10

>>> s = 'I am a string enclosed in single quotes.'


>>> txt = "He said: \"It doesn't matter, if you enclose a string in single or double quotes!\""
>>> print(txt)
Output: He said: "It doesn't matter, if you enclose a string in single or double quotes!"

They can also be enclosed in matching groups of three single or double quotes. In this case
they are called triple-quoted strings.

txt = '''A string in triple quotes can extend


over multiple lines like this one, and can contain
'single' and "double" quotes.'''

>>>name = "harish"
>>>print (type(name))
>>> <type 'str'>

>>>qoute = "I'm good"


>>>print ("qoute: " + quote)
>>> qoute: I'm good

qoute = "qoute: " + 'He said "I am not going" to her'


print (quote)
>>> qoute: He said "I am not going" to her

>>> s = "Hello World"


>>> s[0]
'H'
>>> s[5]
''
The last character of a string can be accessed like this:
>>> s[len(s)-1]
'd'

Operations supported by String

1. Concatenation :Strings can be glued together (concatenated) with the + operator:


"Hello" + "World" will result in "HelloWorld"
2. Repetition : String can be repeated or repeatedly concatenated with the asterisk operator
"*":
For Example *-*" * 3 will result in "*-**-**-*"
3. Indexing : Indexing can be used to extract individual characters from a string. In Python,
all indexing is zero-based.
For Example, 'abc'[0] results in 'a'.
'abc'[3] results in IndexError: string index out of range.

SLICING OPERATION

A segment or a portion of a string is called as slice. Only a required number of characters can
be extracted from a string using colon (:) symbol. The basic syntax for slicing a string, st:
st[i:j:k]
This will extract character from ith character of st till (j-1)th character in steps of k. If first
index i is not present, it means that slice should start from the beginning of the string. If the
second index j is not mentioned, it indicates the slice should be till the end of the string. The
third parameter k, also known as stride, is used to indicate number of steps to be incremented
after extracting first character. The default value of stride is 1.
st="Hello World"
1. print("st[:] is", st[:]) #output Hello World

As both index values are not given, it assumed to be a full string.


2. print("st[0:5] is ", st[0:5]) #output is Hello

Starting from 0th index to 4th index (5 is exclusive), characters will be printed.

3. print("st[0:5:1] is", st[0:5:1]) #output is Hello


This code also prints characters from 0th to 4th index in the steps of 1. Comparing
this example with previous example, we can make out that when the stride value
is 1, it is optional to mention.
4. print("st[3:8] is ", st[3:8]) #output is lo Wo

Starting from 3rd index to 7th index (8 is exclusive), characters will be printed.
5. print("st[7:] is ", st[7:]) #output is orld
Starting from 7th index to till the end of string, characters will be printed.
6. print(st[::2]) #outputs HloWrd
This example uses stride value as 2. So, starting from first character, every
alternative character (char+2) will be printed.
7. print("st[4:4] is ", st[4:4]) #gives empty string

Here,rd st[4:4] indicates, slicing should start from 4th character and end with (4-
1)=3 character, which is not possible. Hence the output would be an empty
string.
8. print(st[3:8:2]) #output is lo
Starting from 3rd character, till 7th character, every alternative index is considered.

9. print(st[1:8:3]) #output is eoo


Starting from index 1, till 7th index, every 3rd character is extracted here.
10. print(st[-4:-1]) #output is orl
Characters at the indices -4, -3 and -2 will be displayed. Observe the role of stride
with default value 1 here. That is, it is computed as -4+1 =-3, -3+1=-2 etc.
11. print(st[-1:]) #output is d
Here, starting index is -1, ending index is not mentioned (means, it takes the index
10) and the stride is default value 1. So, we are trying to print characters from -1
(which is the last character of negative indexing) till 10th character (which is also
the last character in positive indexing) in incremental order of 1. Hence, we will
get only last character as output.
12. print(st[:-1]) #output is Hello Worl

Here, starting index is default value 0 and ending is -1 (corresponds to last character
in negative indexing). But, in slicing, as last index is excluded always, -1st character
is omitted and considered only up to -2nd character.

13. print(st[::]) #outputs Hello World


Here, two colons have used as if stride will be present. But, as we haven‘t
mentioned stride its default value 1 is assumed. Hence this will be a full string.
14. print(st[::-1]) #outputs dlroW olleH
This example shows the power of slicing in Python. Just with proper slicing, we could
able to reverse the string. Here, the meaning is a full string to be extracted in the
order of -1. Hence, the string is printed in the reverse order.
15. print(st[::-2]) #output is drWolH
Here, the string is printed in the reverse order in steps of -2. That is, every alternative
character in the reverse order is printed. Compare this with example (6) given above.
Strings are Immutable
The objects of string class are immutable. That is, once the strings are created (or initialized),
they cannot be modified. No character in the string can be edited/deleted/added. Instead, one
can create a new string using an existing string by imposing any modification required.
>>> st= ―Hello World‖

>>> st[3]='t'
TypeError: 'str' object does not support item assignment
Here, we are trying to change the 4th character (index 3 means, 4th character as the first index
is 0) to t. The error message clearly states that an assignment of new item (a string) is not
possible on string object. So, to achieve our requirement, we can create a new string using
slices of existing string as below –
>>> st= ―Hello World‖

>>> st1= st[:3]+ 't' + st[4:]


>>> print(st1)
Helto World #l is replaced by t in new string st1

BOOLEANS
int variables can be assigned any whole number. string variables can be assigned any
charecters. bool variables(otherwise known as booleans) are special. They can be assigned
only 2 values - True or False

>>>flag = True
>>>print( flag)
>>>True >>> var=12
>>>flag = False >>>bool(var)
>>>print( flag) True
>>>False >>>bool(0)
>>>type(True) False
>>> <type 'bool'>

>>> 5 == 5
True
>>> 5 == 6
False
COMPLEX

LISTS
Lists are the most versatile of Python's compound data types. A list contains items separated
by commas and enclosed within square brackets ([]). To some extent, lists are similar to
arrays in C. One difference between them is that all the items belonging to a list can be of
different data type. List are mutable objects, where its values can be changed.

The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The plus
(+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
For example −
TUPLE

A tuple is a sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed(mutable), while tuples are enclosed in parentheses ( (
) ) and cannot be updated(immutable).Tuples can be thought of as read-only lists.

DICTIONARY
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces (*+). For example –

dict={‗Name‘:‘varshini‘,‘Age‘:6,‘Grade‘:‘1st‘}

print(―dict[Name]:‖,dict[‗Name‘])
print(―dict[Age]:‖,dict[‗Age‘])
print(dict.keys())
print(dict.values())
print(dict.items())
dict[‗Age‘]=7
print(―After updation age is:‖,dict[‗Age‘])

Output:
dict[Name]: varshini
dict[Age]:6
After updation age is : 7
OPERATORS

Different types of operators are

ARITHMETIC OPERATORS
Arithmetic operators are used for doing common arithmetic operations like addition,
substraction etc. They are + - * / % **. For example, 2/3 is 2 divided by 3.

There are two kinds of division operators:

 "true division" performed by "/"

>>>12/2 >>>15/2
Out[26]: 6.0 Out[28]: 7.5

 "floor division" performed by "//"

>>>12//2 >>>15//2
Out[27]: 6 Out[29]: 7

RELATIONAL OPERATORS
Relational operators include >, >=, <, <=, ==, !=. They take 2 operands and return a boolean
result(True or False). For example, the greater than operator (a > b) returns True if a is
bigger than b. Following table contains examples for other operators.
LOGICAL OPERATORS
There are three logical operators: not, or, and. 'not a' evaluates to the opposite of what 'a' is. 'a
and b' evaluates to True only if both a, b are True. 'a or b' evaluates to False if both a,b are
False. They behave exactly like !, ||, && operators in C.

a not a

True False
False True

a b a and b a or b

True True True True


True False False True
False True False True
False False False False

condition = True
print (not condition)
print (condition or False)
print (condition and False)
Out: False
Out: True
Out: False
ORDER OF OPERATIONS

When more than one operator appears in an expression, the order of evaluation depends on
the rules of precedence. For mathematical operators, Python follows mathematical
convention. The acronym PEMDAS is a useful way to remember the rules:

 Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first, 2
* (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an
expression easier to read, as in (minute * 100) / 60, even if it doesn't change the result.
 Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is
3, not 27.
 Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3-1 is 5, not
4, and 6+4/2 is 8, not 5.

Operators with the same precedence are evaluated from left to right. So in the expression 5-3-
1 is 1, not 3 because the 5-3 happens first and then 1 is subtracted from 2.

BRANCHING OR DECISION CONTROL STATEMENTS

Often times, instead of letting each line execute, we would need to selectively execute some
lines. This can be done by if, if-else, if-elif-else blocks. Python seperates blocks based on
their indentation. Unlike other langauges, python doesn‘t use curly brackets{} for creating
blocks.

In Python, a conditional statement has the


form:

if Boolean expression:
block of code
else:
block of code

Control flow
A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed.
if x%2==0:
print(―x is even‖)
else:
print(―x is odd‖)

Sometimes there are more than two possibilities and we need more than two branches.
chained conditional use elif(short form for else if).Also called as elif ladder

if x<y:
print(― x is less than y‖)
elif x>y:
print(―x is greater than y‖)
else:
print(―x and y are equal‖)

Nested Conditions
if x == y:
print 'x and y are equal'
else:
if x < y:
print 'x is less than y'
else:
print 'x is greater than y'

Ternary operator/Conditional expressions


Ternary operator is a shorter form of an if-else statement.
Syntax
expression-1 if condition else expression-2

number = 24
result = "odd" if number % 2 != 0 else "even"
print(result)

Output: even

ITERATION
A generic iteration (also called looping) mechanism is depicted in figure. It begins with a test,
if it evaluates to True, the program executes the loop body once, and then goes back to
reevaluate the test. This process is repeated until the test evaluates to False, after which
control passes to the code following the iteration statement. Iteration is a processing repeating
some task. In a real time programming, we require a set of statements to be repeated certain
number of times and/or till a condition is met. Every programming language provides certain
constructs to achieve the repetition of tasks.
The while Statement

while condition:
statement_1
statement_2
…………….
statement_n
statements_after_while

Here, while is a keyword. The condition is evaluated first. Till its value remains true, the
statement_1 to statement_n will be executed. When the condition becomes false, the loop is
terminated and statements after the loop will be executed. Consider an example –

n=1
while n<=5:
print(n) #observe indentation
n=n+1
print("over")

The output of above code segment would

1
2
3
4
5
over

Infinite Loops, break and continue


A loop may execute infinite number of times when the condition is never going to become
false. For example,
n=1
while True:
print(n)
n=n+1
Here, the condition specified for the loop is the constant True, which will never get
terminated.

In some situations, we deliberately want to come out of the loop even before the normal
termination of the loop. For this purpose break statement is used.

while True:
x=int(input("Enter a number:"))
if x>= 0:
print("You have entered ",x)
else:
print("You have entered a negative number!!")
break #terminates the loop
Sample output:
Enter a number:23
You have entered 23
Enter a number:-2

You have entered a negative number!!


Programmer would like to move to next iteration by skipping few statements in the loop,
based on some condition. For this purpose continue statement is used.

sum=0
count=0
while True:
x=int(input("Enter a number:"))
if x%2 !=0:
continue Read a number from the keyboard
else:
sum+=x
count+=1 If that number is odd, without doing anything
else, just move to next iteration for reading
if count==5: another number
break
If the number is even, add it to sum
print("Sum= ", sum) and increment the accumulator
variable. When accumulator crosses 5,
Sample Output: stop the program
Enter a number:13
Enter a number:12
Enter a number:4
Enter a number:5
Enter a number:-3
Enter a number:8
Enter a number:7
Enter a number:16
Enter a number:6
Sum= 46

DEFINITE LOOPS USING FOR


The while loop iterates till the condition is met and hence, the number of iterations are
usually unknown prior to the loop. Hence, it is sometimes called as indefinite loop. When we
know total number of times the set of statements to be executed, for loop will be used. This is
called as a definite loop. The for-loop iterates over a set of numbers, a set of words, lines in a
file etc. The syntax of for-loop would be –

for var in list/sequence:


statement_1
statement_2
………………
statement_n
statements_after_for

Here, for and in are keywords


list/sequence is a set of elements on which the loop is iterated. That is, the
loop will be executed till there is an element in list/sequence
Statements constitutes body of the loop
Ex: In the below given example, a list names containing three strings has been created. Then
the counter variable x in the for-loop iterates over this list. The variable x takes the elements
in names one by one and the body of the loop is executed.

names=["Ram", "Shyam", "Bheem"]


for x in names:
print(x)
The output would be –
Ram
Shyam
Bheem
The for loop can be used to print (or extract) all the characters in a string as shown below –
for i in "Hello":
print(i, end=‘\t‘)

Output:
H e l l o
FOR LOOP WITH RANGE FUNCTION

When we have a fixed set of numbers to iterate in a for loop, we can use a function range().
The function range() takes the following format –

range(start, end, steps)


The start and end indicates starting and ending values in the sequence, where end is excluded
in the sequence (That is, sequence is up to end-1). The default value of start is 0. The
argument steps indicates the increment/decrement in the values of sequence with the default
value as 1. Hence, the argument steps is optional. Let us consider few examples on usage of
range() function.

Ex1.Printing the values from 0 to


for i in range(5):

print(i, end= ‗\t‘)


Output:
0 1 2 3 4

Ex2. Printing the values from 5 to 1 –


for i in range(5,0,-1):
print(i, end= ‗\t‘)
Output:
5 4 3 2 1

Ex3. Printing only even numbers less than 10

for i in range(0,10,2):
print(i, end= ‗\t‘)
Output:
0 2 4 6 8
Ex4. Count and sum of elements of a list
total = 0
count=0
for x in [4, -2, 41, 34, 25]:
total = total + x
count= count+1
print(―Total:‖, total)
print(―Count:‖, count)
Pass statement
The pass statement is a null operation; nothing happens when it executes. The pass statement
is also useful in places where your code will eventually go, but has not been written yet i.e. in
stubs.It is used as a placeholder in decision constructs, looping constructs (for,while),
functions.

Syntax:

pass

for letter in 'Python':


if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)

Output

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
PYTHON PROGRAMMING
19ISE36
UNIT 2

Functions and Scoping : Functions and Scoping, Function calls, Type conversion, Type
coercion, Math functions, Functions as Objects ,Composition ,Variables and parameters are
local, global, Recursion, Modules, Files Handling, Directories

FUNCTIONS:

A function is a block of organized, reusable code that is used to perform a single, related
action. It is a named sequence of statement used to perform a specific task.


Once a function is written, it can be reused as and when required. So, functions are
also called reusable code.

Functions provide modularity for programming. A module represents a part of the
program. Usually, a programmer divides the main task into smaller sub tasks called
modules.

Code maintenance will become easy because of functions. When a new feature has to
be added to the existing software, a new function can be written and integrated into
the software.

When there is an error in the software, the corresponding function can be modified
without disturbing the other functions in the software.

The use of functions in a program will reduce the length of the program.

Python has many built-in functions like sqrt( ), etc. but you can also create your own
functions. These functions are called user-defined functions.

Difference between a function and a method:

A function can be written individually in a python program. A function is called using


its name. When a function is written inside a class, it becomes a „method‟. A method is
called using object name or class name. A method is called using one of the following ways:

Objectname.methodname()

Classname.methodname()

Defining a Function
Rules to define a function in Python.
 Function blocks begin with the keyword def followed by the function name and
parentheses ( ).

 Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.

 The first statement of a function can be an optional statement - the documentation


string of the function or docstring.

 The code block within every function starts with a colon (:) and is indented.

 The statement return [expression] exits a function, optionally passing back an


expression to the caller. A return statement with no arguments is the same as return
none.

 A function that performs some task, but do not return any value to the calling function
is known as void function.

Syntax:
def functionname (parameters):
body of the function
return [expression]

Example:
def add(a,b):
"""This function sum the numbers"""
c=a+b
print c
return

Calling Function:
A function cannot run by its own. It runs only when we call it. While calling the function, we
should pass the necessary values to the function in the parentheses as:
add(5,12)
Example:
add(2,3)
add(2.3, 4.5)
add(a=2.3, b=4.5)
add(b=4.5, a=2.3)

Out: 5
Out: 6.8
Out: 6.8
Out: 6.8

Returning Results from a function:


We can return the result or output from the function using a „return‟ statement in the function
body. The function which returns some result to the calling function after performing a task is
known as fruitful function. The built-in functions like mathematical functions, random
number generating functions etc. are examples for fruitful functions.
One can write a user-defined .When a function does not return any result, we need not write
the return statement in the body of the function.

Returning multiple values from a function:


A function can returns a single value in the programming languages like C, C++ and JAVA.
But, in python, a function can return multiple values. When a function calculates multiple
results and wants to return the results, we can use return statement as:
return a, b, c
x, y, z = functionName( )
Here, „x‟, „y‟ and „z‟ are receiving the three values returned by the function.
Example:
def calc(a,b):
c=a+b
d=a-b
e=a*b
return c,d,e

x,y,z=calc(5,8)
print ("Addition=",x)
print ("Subtraction=",y)
print ("Multiplication=",z)

Map function
Map is built-in function that takes a function and applies it to a list..map() function returns a
list of the results after applying the given function to each item of a given iterable (list, tuple)
Syntax :
map(fun, iter)

Parameters :
fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.

print(list(map(len, ['this', 'will', 'return', 'lengths', 'of', 'each', 'word'])))


Out: [4, 4, 6, 7, 2, 4, 4]

Each element in the list is used a parameter for len() and the results form a list. Notice that len
is passed and not len(). This is because, we are not calling len. We are just passing len to
map. map will internally call it
def add(a,b):
return a+b
print(list(map(add, [1,2,3,4], [10,20,30,40])))

Out:[11,22, 33, 44]

def cube(number):
return number**3
print(list(map(cube, range(10))))

Out: [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]


def is_odd(num):
return num % 2 == 1
print(list(map(is_odd, range(5))))

Out: [False, True, False, True, False]

Functions are First Class Objects:

In Python, functions are considered as first class objects. It means we can use functions as
perfect objects. In fact when we create a function, the Python interpreter internally creates an
object. Since functions are objects, we can pass a function to another function just like we
pass an object (or value) to a function. The following possibilities are:


It is possible to assign a function to a variable.

It is possible to define one function inside another function.

It is possible to pass a function as parameter to another function.

It is possible that a function can return another function.

def first(msg):
print(msg)

first("Hello")

second = first
second("Hello")

Output
Hello
Hello

Q) Program to know how to pass a function as parameter to another function

def display(f):
return "hai"+f
def message():
return " how r u?"
fun=display(message())
print(fun) Output: hai how r u?

def inc(x):
return x + 1

def dec(x):
return x - 1
def operate(func, x):
result = func(x)
return result

>>>func(inc,3)
>>>4

Q) Program to know how a function can return another function.


def display():
def message():
return "how r u?"
return message
fun=display()
print(fun())

Output: how r u?

Q) Program to know how to define a function inside another function.


Output: how r u? ISE

def display(st):
def message():
return "how r u? "
res=message()+st
return res
x=display("ISE")
print(x)
Pass by Object Reference in Python

In Python, we can observe both pass by value and pass by reference behaviour while passing
the actual parameters to the function definition. Python supports pass by object reference
unlike in C, C++.

Pass by Value:

Pass by value represents that a copy of the variable value is passed to the function and any
modifications to that value will not reflect outside the function. In python, the values are sent
to functions by means of object references. If we store a value into a variable as:
x=10
So, 10 is the object and x is the name of that object. Also, objects are created on heap memory
which is a very huge memory that depends on the RAM of our computer system.

Example: A Python program to pass an integer to a function and modify it.


def modify(x):
x=15
print("inside",x,id(x))
x=10
modify(x)
print("outside",x,id(x))

Output: inside 15 6356456


outside 10 6356516

This means another object 15 is created in memory and that object is referenced by the name
„x‟. The reason why another object is created in the memory is that the integer objects are
immutable (not modifiable). So in the function, when we display „x‟ value, it will display 15.
Once we come outside the function and display „x‟ value, it will display numbers of „x‟ inside
and outside the function, and we see different numbers since they are different objects.

Pass by Reference:

Pass by reference represents sending the reference or memory address of the variable to the
function. The variable value is modified by the function through memory address and hence
the modified value will reflect outside the function also. In python, lists and dictionaries are
mutable. That means, when we change their data, the same object gets modified and new
object is not created.
Example: A Python program to pass a list to a function and modify it.
def modify(a):
a.append(5)
print("inside",a,id(a))
a=[1,2,3,4]
modify(a)
print("outside",a,id(a))

Output:
inside [1, 2, 3, 4, 5] 45355616
outside [1, 2, 3, 4, 5] 45355616
Inside the function, we are appending a new element „5‟ to the list. Since, lists are mutable,
adding a new element to the same object is possible. Hence, append( ) method modifies the
same object.

Formal and Actual Arguments:


When a function is defined, it may have some parameters. These parameters are useful to
receive values from outside of the function. They are called „formal arguments‟. When we
call the function, we should pass data or values to the function. These values are called „actual
arguments‟. In the following code, „a‟ and „b‟ are formal arguments and „x‟ and „y‟ are
actual arguments.
Example:
def add(a,b): # a, b are formal arguments
c=a+b
print c
x,y=10,15
add(x,y) # x, y are actual arguments

The actual arguments used in a function call are of 4 types:


a) Positional arguments
b) Keyword arguments
c) Default arguments
d) Variable length arguments

a) Positional Arguments:
These are the arguments passed to a function in correct positional order. Here, the number of
arguments and their position in the function definition should match exactly with the number
and position of argument in the function call.
def attach(s1,s2):
s3=s1+s2
print (s3)
attach("New","Delhi") #Positional arguments

b) Keyword Arguments:
Keyword arguments are arguments that identify the parameters by their names. For example,
the definition of a function that displays grocery item and its price can be written as:
def grocery(item, price):
At the time of calling this function, we have to pass two values and we can mention which
value is for what. For example,
grocery(item=’sugar’, price=50.75)
Here, we are mentioning a keyword „item‟ and its value and then another keyword „price‟
and its value. Please observe these keywords are nothing but the parameter names which
receive these values. We can change the order of the arguments as:
grocery(price=88.00, item=’oil’)

def grocery(item,price):
print "item=",item
print "price=",price
grocery(item="sugar",price=50.75) # keyword arguments
grocery(price=88.00,item="oil") # keyword arguments
Output:
item= sugar
price= 50.75
item= oil
price= 88.0

c) Default Arguments:
We can mention some default value for the function parameters in the definition.
def grocery(item, price=40.00)

Here, the first argument is „item‟ whose default value is not mentioned. But the second
argument is „price‟ and its default value is mentioned to be 40.00. So, a default argument is an
argument that assumes a default value if a value is not provided in the function call for that
argument.
Example: def grocery(item,price=40.00):
print("item=",item)
print("price=",price)
grocery(item="sugar",price=50.75)
grocery(item="oil")

Output:
item= sugar
price= 50.75
item= oil
price= 40.0

Example:
def print_series(n=5):
for i in range(n):
print(i)
print ('calling with 3 as parameter')
print_series(3)
print ('calling without an actual parameter')
print_series()

Output:
Out: calling with 3 as parameter
Out: 0
Out: 1
Out: 2
Out: calling without an actual parameter
Out: 0
Out: 1
Out: 2
Out: 3
Out: 4

d) Variable Length Arguments:


Sometimes, the programmer does not know how many values a function may receive. In that
case, the programmer cannot decide how many arguments to be given in the function
definition. A variable length argument is used in the function definition.
A variable length argument is an argument that can accept any number of values. The variable
length argument is written with a „*‟ symbol before it in the function definition as:
def add(farg, *args):
here, farg is the formal; argument and *args represents variable length argument. We can pass
1 or more values to this *args and it will store them all in a tuple.

Example:
def add(farg,*args):
sum=0
for i in args:
sum=sum+i
print("sum is",sum+farg)
add(5,10)
add(5,10,20)
add(5,10,20,30)

Output: sum is 15
sum is 35
sum is 65

Example:
def max(*numbers):
result = -1
for number in numbers:
if number > result:
result = number
print(result)

Out: max(12,3,19,1)
19

Scoping - Local and Global Variables:


 At top level, i.e., the level of the shell, a symbol table keeps track of all names defined
at that level and their current bindings.
 When a function is called, a new symbol table (sometimes called a stack frame) is
created. This table keeps track of all names defined within the function (including the
formal parameters) and their current bindings.
 If a function is called from within the function body, yet another stack frame is created.
 When the function completes, its stack frame goes away.

When we declare a variable inside a function, it becomes a local variable. A local variable is a
variable whose scope is limited only to that function where it is created. That means the local
variable value is available only in that function and not outside of that function.
Example-1:
def myfunction():
a=10
print("Inside function",a) #display 10
myfunction()
print("outside function",a) # Error, not available

Output:
Inside function 10
outside function
NameError: name 'a' is not defined
When a variable is declared above a function, it becomes global variable. Such variables are
available to all the functions which are written after it.

Example-2:
a=11
def myfunction():
b=10
print("Inside function",a) #display global var
print("Inside function",b) #display local var
myfunction()
print("outside function",a) # available
print("outside function",b) # error

Output:
Inside function 11
Inside function 10
outside function 11
outside function
NameError: name 'b' is not defined

The Global Keyword:

Sometimes, the global variable and the local variable may have the same name. In that case,
the function, by default, refers to the local variable and ignores the global variable. So, the
global variable is not accessible inside the function but outside of it, it is accessible.

Example-1:

a=11
def myfunction():
a=10
print("Inside function",a) # display local
myfunction()
print("outside function",a) # display global variable

Output:
Inside function 10
outside function 11

When the programmer wants to use the global variable inside a function, he can use the
keyword „global‟ before the variable in the beginning of the function body as:
global a
a=11
def myfunction():
global a
a=10
print("Inside function",a) # display global variable myfunction()
print("outside function",a) # display global variable

Output:
Inside function 10
outside function 10

Recursive Functions:
A function that calls itself is known as recursive function.
factorial(n) = n * factorial(n-1)
Example-1:
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result

for i in range(1,5):
Print("factorial of ",i,"is",factorial(i))
Output:
factorial of 1 is 1
factorial of 2 is 2
factorial of 3 is 6
factorial of 4 is 24

Anonymous Function or Lambdas:

These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.


Lambda forms can take any number of arguments but return just one value in the form of
an expression. They cannot contain commands or multiple expressions.

An anonymous function cannot be a direct call to print because lambda requires an
expression.

Lambda functions have their own local namespace and cannot access variables other than
those in their parameter list and those in the global namespace.

Although it appears that lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function stack
allocation during invocation for performance reasons.
The syntax is:
lambda argument_list: expression
Example:
Normal function
f=lambda x:x*x
value = f(5) def square(x):
print (value) return x*x
Usage of lambda function with map() Function
The advantage of the lambda operator can be seen when it is used in combination with the
map() function. map() is a function with two arguments:

def fahrenheit(T):
return ((float(9)/5)*T + 32)
def celsius(T):
return (float(5)/9)*(T-32)
temp = (36.5, 37, 37.5,39)
F = list(map(fahrenheit, temp))
C =list(map(celsius, F))

By using lambda, we wouldn't have had to define and name the functions fahrenheit() and
celsius(). You can see this in the following interactive session:

>>> temp = [39.2, 36.5, 37.3, 37.8]


>>> print(list( map(lambda x: (float(9)/5)*x + 32, temp)))
[102.56, 97.700000000000003, 99.140000000000001, 100.03999999999999]

>>> C = print(list(map(lambda x: (float(5)/9)*(x-32), temp)))


[39.200000000000003, 36.5, 37.300000000000004, 37.799999999999997]

map() can be applied to more than one list. The lists have to have the same length. map() will
apply its lambda function to the elements of the argument lists, i.e. it first applies to the
elements with the 0th index, then to the elements with the 1st index until the n-th index is
reached:
>>> a = [1,2,3,4]
>>> b = [17,12,11,10]
>>> c = [-1,-4,5,9]
>>> map(lambda
x,y:x+y,a,b) [18, 14, 14, 14]

>>> map(lambda
x,y,z:x+y+z,a,b,c) [17, 10, 19, 23]

>>> map(lambda x,y,z:x+y-z,


a,b,c) [19, 18, 9, 5]

Filter function
The function filter(function, list) offers an elegant way to filter out all the elements of a list,
for which the function function returns True. The function filter(f,l) needs a function f as its
first argument. f returns a Boolean value, i.e. either True or False. This function will be
applied to every element of the list l. Only if f returns True will the element of the list be
included in the result list.

>>> fib = [0,1,1,2,3,5,8,13,21,34,55]


>>> result = filter(lambda x: x % 2, fib)
>>> print( result)

[1, 1, 3, 5, 13, 21, 55]


>>> result = filter(lambda x: x % 2 == 0, fib)
>>> print(result)
[0, 2, 8, 34]

reduce()

The reduce(fun,seq) function is used to apply a particular function passed in its argument to all
of the list elements mentioned in the sequence passed along. This function is defined in
“functools” module.
At first step, first two elements of sequence are picked and the result is obtained. Next step is
to apply the same function to the previously attained result and the number just succeeding the
second element and the result is again stored. This process continues till no more elements are
left in the container. The final returned result is returned and printed on console.

import functools
lis = [ 1 , 3, 5, 6, 2, ]
# using reduce to compute sum of list
print ("The sum of the list elements is : ",end="")
print (functools.reduce(lambda a,b : a+b,lis))

# using reduce to compute maximum element from list


print ("The maximum element of the list is : ",end="")
print (functools.reduce(lambda a,b : a if a > b else b,lis))

Output:
The sum of the list elements is : 17
The maximum element of the list is : 6

Function composition

Function composition is a way of combining functions such that the result of each function is
passed as the argument of the next function. For example, the composition of two functions f
and g is denoted f(g(x)) .

Example: Actual function


def clean_and_lower(text):
return text.strip().lower()
print(clean_and_lower("Anderson "))

Function compostion for above example


def compose(f1, f2):
return lambda x: f1(f2(x))
clean_and_lower = compose(str.lower, str.strip)
print(clean_and_lower("Anderson "))
Another Example:

def compose2(f, g):


return lambda x: f(g(x))
double=lambda x: x ** 2
inc =lambda x: x + 1
inc_and_double = compose2(double, inc)
print(inc_and_double(10))

Output: 22

Modules:

A module is a file containing Python definitions and statements. 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__. For instance, use your favourite text
editor to create a file called fibo.py in the current directory with the following contents:

# Fibonacci numbers module


def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b
a, b = b, a+b

def fib2(n): # return Fibonacci series up to n


result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result

Now enter the Python interpreter and import this module with the following command:

>>> import fibo

This does not enter the names of the functions defined in fibo directly in the current symbol
table; it only enters the module name fibo there. Using the module name you can access the
functions:

>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

>>>fibo.__name__
'fibo'
from statement:


A module can contain executable statements as well as function 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. (They are also run if the file is
executed as a script.)


Each module has its own private symbol table, which is used as the global symbol table by
all functions defined in the module. Thus, the author of a module can use global variables
in the module without worrying about accidental clashes with a user‟s global variables. On
the other hand, if you know what you are doing you can touch a module‟s global variables
with the same notation used to refer to its functions, modname.itemname.


Modules can import other modules. It is customary but not required to place all import
statements at the beginning of a module (or script, for that matter). The imported module
names are placed in the importing module‟s global symbol table.

mymodule .py

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

import mymodule as mx
a = mx.person1["age"]
print(a)
mx.greeting(“Tom”)


There is a variant of the import statement that imports names from a module directly into
the importing module‟s symbol table. For example:

>>> from fibo import fib

>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not introduce the module name from which the imports are taken in the local
symbol table (so in the example, fibo is not defined). Only fib() is imported.There is even a
variant to import all names that a module defines:
>>> from fibo import *

>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

Built-in modules

import platform
x = platform.system()
print(x)

Namespaces and Scoping


Variables are names (identifiers) that map to objects. A namespace is a dictionary of
variable names (keys) and their corresponding objects (values).


A Python statement can access variables in a local namespace and in the global
namespace. If a local and a global variable have the same name, the local variable
shadows the global variable.


Each function has its own local namespace. Class methods follow the same scoping
rule as ordinary functions.


Python makes educated guesses on whether variables are local or global. It assumes
that any variable assigned a value in a function is local.


Therefore, in order to assign a value to a global variable within a function, you must
first use the global statement.


The statement global VarName tells Python that VarName is a global variable. Python
stops searching the local namespace for the variable.


For example, we define a variable Money in the global namespace. Within the
functionMoney, we assign Money a value, therefore Python assumes Money as a local
variable. However, we accessed the value of the local variable Money before setting it,
so an UnboundLocalError is the result. Uncommenting the global statement fixes the
problem.

Math functions

Python has a math module that provides most of the familiar mathematical functions.

>>> import math


This statement creates a module object named math. If you print the module object, you get
some information about it:

>>> print math


<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>
The module object contains the functions and variables defined in the module. To access one
of the functions, you have to specify the name of the module and the name of the function,
separated by a dot (also known as a period). This format is called dot notation.

>>> ratio = signal_power / noise_power


>>> decibels = 10 * math.log10(ratio)

>>> radians = 0.7


>>> height = math.sin(radians)

>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.707106781187

>>> math.sqrt(2) / 2.0


0.707106781187

>>>math.cos(45*math.pi/180)
0.7071067811865476

>>> math.tan(45*math.pi/180)
0.9999999999999999

Files  refer ppt and programs

Directories and Pickling

Directories
In a computer system, files are organized into directories. These may contain subdirectories
and files. We should import the OS module to be able to access the method.

>>> import os

To get the contents of a directory into a python list, we use the listdir() method.
>>> os.listdir()
['All Users', 'Default', 'Default User', 'desktop.ini', 'Public', 'TEMP', 'vandana']

>>>os.path.abspath(".\rpc.py")
'C:\\Users\\vandana\\Anaconda3\\Lib\\idlelib\\.\rpc.py'

>>> os.path.isdir("rpc.py")
False

>>> os.path.isdir("..\idlelib")
True

>>> os.path.isfile("rpc.py")
True
>>> os.path.isfile("..\idlelib")
False

>>>os.getcwd()
'C:\\Users\\vandana\\Anaconda3\\Lib\\idlelib

Cwd returns the path of current working directory as a string in python.


>>> type(os.getcwd())
<class 'str'>

To get the path of current working directory as a bytes object, we use the method getcwdb().
>>>os.getcwdb()
b'C:\\Users\\vandana\\Anaconda3\\Lib\\idlelib'

>>> print(os.getcwd())
C:\Users\vandana\Anaconda3\Lib\idlelib

>>> os.chdir("C:\\Users")
>>> os.getcwd()
'C:\\Users'

>>> os.mkdir("ptest")

>>>os.rmdir('dirname')

>>> os.rename("ptest","python-test")

>>>os.remove('C:\\Users\\lifei\\Desktop\\Christmas 2017\\Readme.txt')

>>> os.path.exists('C:\\Users\\lifei\\Desktop\\Myfolder')

>>> for roots,dirs,files in os.walk('C:\\Users\\lifei\\Desktop\\Papers'):


print(roots,len(dirs),len(files))

>> for roots,dirs,files in os.walk('C:\\Users\\lifei\\Desktop\\Papers'):


print(roots,dirs,files)

Pickling in Python

Pickle is used for serializing and de-serializing Python object structures, also called
marshalling or flattening. Serialization refers to the process of converting an object in memory
to a byte stream that can be stored on disk or sent over a network. Later on, this character
stream can then be retrieved and de-serialized back to a Python object. Any object in python
can be pickled so that it can be saved on disk.
Pickle “serialises” the object first before writing it to file. Pickling is a way to convert a
python object (list, dict, etc.) into a character stream. The idea is that this character stream
contains all the information necessary to reconstruct the object in another python script.
The pickle module implements binary protocols for serializing and de-serializing a
Python object structure. “Pickling” is the process whereby a Python object hierarchy is
converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream
(from a binary file or bytes-like object) is converted back into an object hierarchy.

Application:
1) Saving a program's state data to disk so that it can carry on where it left off when restarted
(persistence)

2) Sending python data over a TCP connection in a multi-core or distributed system


(marshalling)

3) Storing python objects in a database

4) Converting an arbitrary python object to a string so that it can be used as a dictionary key
(e.g. for caching & memoization).
5) Pickle is very useful for when you're working with machine learning algorithms, where you
want to save them to be able to make new predictions at a later time, without having to rewrite
everything or train the model all over again

The following types can be pickled:

 None, True, and False


 integers, floating point numbers, complex numbers
 strings, bytes, bytearrays
 tuples, lists, sets, and dictionaries containing only picklable objects
 functions defined at the top level of a module (using def, not lambda)
 built-in functions defined at the top level of a module
 classes that are defined at the top level of a module

Attempts to pickle unpicklable objects will raise the PicklingError exception

Example:

import pickle
a = ['test value','test value 2','test value 3']
fileObject = open(“test_file”,'wb')
pickle.dump(a,fileObject)
fileObject.close()
fileObject = open(“test_file”,'r')
b = pickle.load(fileObject)
print(b)
print(a==b, type(b))

Output
['test value','test value 2','test value 3']
True <class „list‟>
Module 3

Sequence Data Types : List, List Comprehension, Tuple, Dictionary, Set,


Strings

The most basic data structure in Python is the sequence. Each element of a sequence is assigned
a number - its position or index. The first index is zero, the second index is one, and so forth.

There are certain things you can do with all the sequence types. These operations include
indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has
built-in functions for finding the length of a sequence and for finding its largest and smallest
elements.

Python Lists

The list is the most versatile datatype available in Python, which can be written as a list
of comma-separated values (items) between square brackets. Important thing about a list is that
the items in a list need not be of the same type. Creating a list is as simple as putting different
comma-separated values between square brackets.

For example : list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a",
"b", "c", "d"]; Similar to string indices, list indices start at 0, and lists can be sliced,
concatenated and so on.

Accessing Values in Lists To access values in lists, use the square brackets for slicing along
with the index or indices to obtain value available at that index.

For example- list1 = ['physics', 'chemistry', 1997, 2000]

list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])

print ("list2[1:5]: ", list2[1:5])


Updating Lists You can update single or multiple elements of lists by giving the slice on the
left-hand side of the assignment operator, and you can add to elements in a list with the
append() method. For example- list = ['physics', 'chemistry', 1997, 2000] print ("Value
available at index 2 : ", list[2]) list[2] = 2001 print ("New value available at index 2 : ", list[2])

Delete List Elements To remove a list element, you can use either the del statement if you
know exactly which element(s) you are deleting.
Basic List Operations

Lists respond to the + and * operators much like strings; they mean concatenation and repetition
here too, except that the result is a new list, not a string.

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration

Indexing, Slicing and Matrixes: Since lists are sequences, indexing and slicing work the
same way for lists as they do for strings. Assuming the following inputL=['C++'', 'Java',
'Python']
Built-in List Functions & Methods

Python includes the following list functions −

Sr.No. Function with Description

2 len(list)

Gives the total length of the list.

3 max(list)

Returns item from the list with max value.

4 min(list)

Returns item from the list with min value.

5 list(seq)

Converts a tuple into list.

List len() Method : The len() method returns the number of elements in the list.

Syntax for len() method : len(list)

Parameters list - This is a list for which, number of elements are to be counted.

Return Value This method returns the number of elements in the list.
List max() Method : The max() method returns the elements from the list with maximum
value.

syntax for max() method : max(list)

Parameters list - This is a list from which max valued element are to be returned.

Return Value This method returns the elements from the list with maximum value.

List min() Method : The method min() returns the elements from the list with minimum value.
syntax for min() method min(list)

Parameters list - This is a list from which min valued element is to be returned.

Return Value This method returns the elements from the list with minimum value.

List list() Method : The list() method takes sequence types and converts them to lists. This is
used to convert a given tuple into list.

Note: Tuple are very similar to lists with only difference that element values of a tuple can not
be changed and tuple elements are put between parentheses instead of square bracket. This
function also converts characters in a string into a list.

Syntax for list() method : list( seq )

Parameters seq - This is a tuple or string to be converted into list.

Return Value This method returns the list.


Python includes following list methods

Sr.No. Methods with Description

1 list.append(obj)

Appends object obj to list

2 list.count(obj)

Returns count of how many times obj occurs in list

3 list.extend(seq)

Appends the contents of seq to list

4 list.index(obj)

Returns the lowest index in list that obj appears

5 list.insert(index, obj)

Inserts object obj into list at offset index

6 list.pop(obj=list[-1])

Removes and returns last object or obj from list

7 list.remove(obj)

Removes object obj from list


8 list.reverse()

Reverses objects of list in place

9 list.sort([func])

Sorts objects of list, use compare func if given

List append() Method : The append() method appends a passed obj into the existing list.
syntax for append() method list.append(obj)

Parameters obj - This is the object to be appended in the list.

Return Value This method does not return any value but updates existing list.

List count() Method The count() method returns count of how many times obj occurs in list.
syntax for count() method list.count(obj)

Parameters obj - This is the object to be counted in the list.

Return Value This method returns count of how many times obj occurs in list.

List extend() Method The extend() method appends the contents of seq to list.

syntax for extend() method- list.extend(seq)

Parameters seq - This is the list of elements

Return Value This method does not return any value but adds the content to an existing list.
List index() Method The index() method returns the lowest index in list that obj appears.
syntax for index() method list.index(obj)

Parameters obj - This is the object to be find out.

Return Value This method returns index of the found object otherwise raises an exception
indicating that the value is not found.

List insert() Method The insert() method inserts object obj into list at offset index.

syntax for insert() method list.insert(index, obj)

Parameters

index - This is the Index where the object obj need to be inserted.

obj - This is the Object to be inserted into the given list.

Return Value This method does not return any value but it inserts the given element at the given
index.
List pop() Method The pop() method removes and returns last object or obj from the list.
syntax for pop() method list.pop(obj=list[-1])

Parameters obj - This is an optional parameter, index of the object to be removed from the list.
Return Value This method returns the removed object from the list.

List remove() Method

Parameters obj - This is the object to be removed from the list.

Return Value This method does not return any value but removes the given object from the list.

List reverse() Method The reverse() method reverses objects of list in place.

syntax for reverse() method list.reverse()

Parameters NA

Return Value This method does not return any value but reverse the given object from the list.

List sort() Method The sort() method sorts objects of list, use compare function if given.
syntax for sort() method list.sort([func])

Parameters NA

Return Value This method does not return any value but reverses the given object from the list.
list.sort(reverse=True|False, key=myFunc)

reverse=True will sort the list descending. Default is reverse=False

Key= A function to specify the sorting criteria(s)

>>> l=['ABC','abc','aBc','AbC']

>>> print(l.sort())

None

>>> l

>>> l= [1, 3, 4, 2]

>>>l.sort(reverse = True)

>>>l

[4,3,2,1]

Sorting in reverse order based on length:

def myFunc(e):

return len(e)

cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']

cars.sort(reverse=False, key=myFunc)

print(cars)

cars.sort(reverse=True, key=myFunc)

print(cars)

[‘VW’,’BMW’,’Ford’,' Mitsubishi ']

[' Mitsubishi ', ‘Ford', 'BMW', 'VW']


sorted() returns a new sorted list, leaving the original list unaffected

list.sort() sorts the list in-place, mutating the list indices, and returns None.

ls2.sort()

ls3=sorted(ls2)

List Comprehension

Comprehensions in Python provide us with a short and concise way to construct new sequences (such
as lists, set, dictionary etc.) using sequences which have been already defined.

List Comprehensions provide an elegant way to create new lists. The following is the basic
structure of a list comprehension:
output_list = [output_exp for member in iterable if (var satisfies this condition)]

Every list comprehension in Python includes three elements:

expression is the member itself, a call to a method, or any other valid expression that returns
a value. In the example above, the expression i * i is the square of the member value.

member is the object or value in the list or iterable. In the example above, the member value
is i.

iterable is a list, set, sequence, generator, or any other object that can return its elements one
at a time. example, the iterable is range(10).

Note that list comprehension may or may not contain an if condition. List comprehensions can contain
multiple for (nested list comprehensions).
Reading multiple values using list comprehension

Accepting multiple input from user

x = list(map(int, input("Enter a multiple value: ").split()))

print("List of students: ", x)

Output:

Enter a multiple value: 2 3 4

List of students: [2, 3, 4]

Cloning lists

Obtaining exact copy of an existing object (or list) is called ‘cloning’. These various ways of
copying
1. Using slicing technique
This is the easiest and the fastest way to clone a list. This method is considered when
we want to modify a list and also keep a copy of the original. In this we make a copy
of the list itself, along with the reference. This process is also called cloning.

2. Using the list() method


This is the simplest method of cloning a list by using the builtin function list().
3. Shallow copy and deep copy
In Python, Assignment statements do not copy objects, they create bindings
between a target and an object. When we use = operator user thinks that this creates a
new object; well, it doesn’t. It only creates a new variable that shares the reference of
the original object. Sometimes a user wants to work with mutable objects, in order to
do that user looks for a way to create “real copies” or “clones” of these objects. Or,
sometimes a user wants copies that user can modify without automatically modifying
the original at the same time, in order to do that we create copies of objects.
A copy is sometimes needed so one can change one copy without changing the other.
In Python, there are two ways to create copies :
 Deep copy
 Shallow copy
In order to make these copy, we use copy module.
Shallow copy:
A shallow copy means constructing a new collection object and then populating it with
references to the child objects found in the original. The copying process does not
recurse and therefore won’t create copies of the child objects themselves. In case of
shallow copy, a reference of object is copied in other object. It means that any
changes made to a copy of object do reflect in the original object. In python, this is
implemented using “copy()” function.

Shallow copy

Shallow copy creates separate object but objects will have the reference to the same list
elements. Following code illustrates that when we add new element to the list, eleemnt will
be added to the list on which append was used but other list(copy of list) remains same.
But when we update the existing list element with new element, in shallow copy updating
modifies both the lists (because objects are different but they point/refer to same list
elements) as shown below

Deep copy
Deep copy is a process in which the copying process occurs recursively. It means first
constructing a new collection object and then recursively populating it with copies of
the child objects found in the original. In case of deep copy, a copy of object is copied
in other object. It means that any changes made to a copy of object do not reflect in
the original object. In python, this is implemented using “deepcopy()” function.
Deep copy

Shallow copy creates separate object and each object refers to separate list elemnts. Following
code illustrates that when we add new element to the list, eleemnt will be added to the list on
which append was used but other list(copy of list) remains same.

But when we update the existing list element with new element, in deep copy updating
modifies only the intended list but not the other copy list (because objects are different and
they point/refer to different list elements) as shown below
Dictionary

Each key is separated from its value by a colon (:), the items are separated by commas, and the
whole thing is enclosed in curly braces. An empty dictionary without any items is written with
just two curly braces, like this: {}. Keys are unique within a dictionary while values may not
be. The values of a dictionary can be of any type, but the keys must be of an immutable data
type such as strings, numbers, or tuples.

Accessing Values in Dictionary To access dictionary elements, you can use the familiar
square brackets along with the key to obtain its value.

If we attempt to access a data item with a key, which is not a part of the dictionary, we get an
error as follows-

Updating Dictionary You can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry as shown in a simple example given
below.
Delete Dictionary Elements You can either remove individual dictionary elements or clear
the entire contents of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a simple
example-

Properties of Dictionary Keys Dictionary values have no restrictions. They can be any
arbitrary Python object, either standard objects or user-defined objects. However, same is not
true for the keys.

There are two important points to remember about dictionary keys-

(a) More than one entry per key is not allowed. This means no duplicate key is allowed.
When duplicate keys are encountered during assignment, the last assignment wins.

(b) Keys must be immutable. This means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed. Following is a simple example-
Built-in Dictionary Functions and Methods
Python includes the following dictionary functions −

Sr.No. Function & Description

1. len(dict)

Gives the total length of the dictionary. This would be equal to the number of items in
the dictionary.

2. str(dict)

Produces a printable string representation of a dictionary

3. type(variable)

Returns the type of the passed variable. If passed variable is dictionary, then it would
return a dictionary type.

Dictionary len() Method The method len() gives the total length of the dictionary. This would
be equal to the number of items in the dictionary.

syntax for len() method len(dict)

Parameters dict - This is the dictionary, whose length needs to be calculated.

Return Value This method returns the length.

Dictionary str() Method The method str() produces a printable string representation of a
dictionary.

syntax for str() method − str(dict)

Parameters dict - This is the dictionary.

Return Value This method returns string representation.


Dictionary type() Method The method type() returns the type of the passed variable. If passed
variable is dictionary then it would return a dictionary type.

syntax for type() method : type(dict)

Parameters dict - This is the dictionary.

Return Value This method returns the type of the passed variable.

Python includes the following dictionary methods −

Sr.No. Method & Description

1 dict.clear()

Removes all elements of dictionary dict

2 dict.copy()

Returns a shallow copy of dictionary dict

3 dict.fromkeys()

Create a new dictionary with keys from seq and values set to value.

4 dict.get(key, default=None)

For key key, returns value or default if key not in dictionary

5 dict.has_key(key)

Removed, use the in operation instead.


6 dict.items()

Returns a list of dict's (key, value) tuple pairs

7 dict.keys()

Returns list of dictionary dict's keys

8 dict.setdefault(key, default = None)

Similar to get(), but will set dict[key] = default if key is not already in dict

9 dict.update(dict2)

Adds dictionary dict2's key-values pairs to dict

10 dict.values()

Returns list of dictionary dict's values

Dictionary clear() Method The method clear() removes all items from the dictionary.

syntax for clear() method : dict.clear()

Parameters NA Return Value This method does not return any value.

Dictionary copy() Method The method copy() returns a shallow copy of the dictionary.

syntax for copy() method : dict.copy()

Parameters NA

Return Value This method returns a shallow copy of the dictionary.


Dictionary fromkeys() Method The method fromkeys() creates a new dictionary with keys
from seq and values set to value.
syntax for fromkeys() methoddict.fromkeys(seq[, value]))

Parameters

 seq - This is the list of values which would be used for dictionary keys preparation.

 value - This is optional, if provided then value would be set to this value

Return Value This method returns the list.

Dictionary get() Method

The method get() returns a value for the given key. If the key is not available then returns
default value None.

Syntax for get() method : dict.get(key, default=None)

Parameters

key - This is the Key to be searched in the dictionary.


default - This is the Value to be returned in case key does not exist.

Return Value : This method returns a value for the given key. If the key is not available, then
returns default value as None.

Dictionary items() Method The method items() returns a list of dict's (key, value) tuple pairs.
syntax for items() method dict.items()

Parameters NA Return Value

This method returns a list of tuple pairs.


Dictionary keys() Method The method keys() returns a list of all the available keys in the
dictionary.

syntax for keys() method dict.keys()

Parameters NA

Return Value This method returns a list of all the available keys in the dictionary.

Dictionary setdefault() Method The method setdefault() is similar to get(), but will set
dict[key]=default if the key is not already in dict.

syntax for setdefault() method dict.setdefault(key, default=None)

Parameters

 key - This is the key to be searched.

 default - This is the Value to be returned in case key is not found.

Return Value This method returns the key value available in the dictionary and if given key is
not available then it will return provided default value.

Dictionary update() Method The method update() adds dictionary dict2's key-values pairs in
to dict. This function does not return anything.

syntax for update() method dict.update(dict2)

Parameters dict2 - This is the dictionary to be added into dict.

Return Value This method does not return any value.


Dictionary values() Method The method values() returns a list of all the values available in a
given dictionary.

syntax for values() method dict.values()

Parameters NA

Return Value This method returns a list of all the values available in a given dictionary.

Traversing the dictionary using loop:

Following code gives the keys in the dictionary

To retrieve values from dictionary we can use the following code:

To retrieve both keys and values together we use items() on dictionary as follows:
The pop() method removes the item with the specified key name

Following code creates a dictionary where keys are numbers and values are squares of numbers

The popitem() method removes the last inserted item (in versions before 3.7, a random item
is removed instead):

Nested Dictionaries

A dictionary can also contain many dictionaries, this is called nested dictionaries.

The dict() Constructor

It is also possible to use the dict() constructor to make a new dictionary:


Converting lists to dictionaries:

Zip() is used to zip the lists, and dict() constructor is used to convert to dictionary, first
list elements will be taken as keys and 2nd list elements will be taken as values

Tuples

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
main difference between the tuples and the lists is that the tuples cannot be changed unlike
lists. Tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as
putting different comma-separated values. Optionally, you can put these comma-separated
values between parentheses also. For example

The empty tuple is written as two parentheses containing nothing.

tup1 = ();

To write a tuple containing a single value you have to include a comma, even though there

is only one value.

tup1 = (50,)

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.

Accessing Values in Tuples

To access values in tuple, use the square brackets for slicing along with the index or indices

to obtain the value available at that index. For example


Updating Tuples Tuples are immutable, which means you cannot update or change the values
of tuple elements. You are able to take portions of the existing tuples to create new tuples as
the following example demonstrates.

Delete Tuple Elements Removing individual tuple elements is not possible. There is, of
course, nothing wrong with putting together another tuple with the undesired elements
discarded. To explicitly remove an entire tuple, just use the del statement. For example-

Basic Tuples Operations

Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a strings.

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation


('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1,2,3) : print (x, end = ' ') 123 Iteration

Indexing, Slicing, and Matrixes

Since tuples are sequences, indexing and slicing work the same way for tuples as they do for
strings, assuming the following input −

T=('C++', 'Java', 'Python')

Python Expression Results Description

T[2] 'Python' Offsets start at zero


T[-2] 'Java' Negative: count from the right

T[1:] ('Java', 'Python') Slicing fetches sections

No Enclosing Delimiters

No enclosing Delimiters is any set of multiple objects, comma-separated, written without


identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as
indicated in these short examples.

Built-in Tuple Functions

Python includes the following tuple functions −

Sr.No. Function & Description

1 cmp(tuple1, tuple2)

Compares elements of both tuples.


2 len(tuple)

Gives the total length of the tuple.

3 max(tuple)

Returns item from the tuple with max value.

4 min(tuple)

Returns item from the tuple with min value.

5 tuple(seq)

Converts a list into tuple.

Tuple len() Method The len() method returns the number of elements in the tuple.

syntax for len() method : len(tuple)

Parameters tuple - This is a tuple for which number of elements to be counted.

Return Value This method returns the number of elements in the tuple.

Tuple max() Method The max() method returns the elements from the tuple with maximum
value.

syntax for max() method : max(tuple)

Parameters tuple - This is a tuple from which max valued element to be returned.

Return Value This method returns the elements from the tuple with maximum value.

Tuple min() Method The min() method returns the elements from the tuple with minimum
value.

syntax for min() method : min(tuple)


Parameters tuple - This is a tuple from which min valued element is to be returned.

Return Value This method returns the elements from the tuple with minimum value.

Tuple tuple() Method The tuple() method converts a list of items into tuples.

syntax for tuple() method : tuple( seq )

Parameters seq - This is a tuple to be converted into tuple.

Return Value This method returns the tuple.

tup.count(x) Returns how many times the element ‘x’ is found in tuple.

Returns the first occurrence of the element ‘x’ in tuple. Raises ValueError
tup.index(x)
if ‘x’ is not found in the tuple.

Sorts the elements of tuple into ascending order. sorted(tup,reverse=True)


sorted(tup)
will sort in reverse order.
Following code creates list of tuples where each tuple has 2 values, 1st value is the number
and second value is the square of the number.

Python Sets

A set is an unordered collection of items. Every set element is unique (no duplicates) and must
be immutable (cannot be changed).

However, a set itself is mutable. We can add or remove items from it.

Sets can also be used to perform mathematical set operations like union, intersection,
symmetric difference, etc.

Creating Python Sets

A set is created by placing all the items (elements) inside curly braces {}, separated by comma,
or by using the built-in set() function.

It can have any number of items and they may be of different types (integer, float, tuple, string
etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.

# Different types of sets in Python

# set of integers

my_set = {1, 2, 3}

print(my_set)
# set of mixed datatypes

my_set = {1.0, "Hello", (1, 2, 3)}

print(my_set)

Output

{1, 2, 3}

{1.0, (1, 2, 3), 'Hello'}

Try the following examples as well.

# set cannot have duplicates

# Output: {1, 2, 3, 4}

my_set = {1, 2, 3, 4, 3, 2}

print(my_set)

# we can make set from a list

# Output: {1, 2, 3}

my_set = set([1, 2, 3, 2])

print(my_set)

# set cannot have mutable items

# here [3, 4] is a mutable list

# this will cause an error.

my_set = {1, 2, [3, 4]}

Output

{1, 2, 3, 4}
{1, 2, 3}

Traceback (most recent call last):

File "<string>", line 15, in <module>

my_set = {1, 2, [3, 4]}

TypeError: unhashable type: 'list'

Creating an empty set is a bit tricky.

Empty curly braces {} will make an empty dictionary in Python. To make a set without any
elements, we use the set() function without any argument.

# Distinguish set and dictionary while creating empty set

# initialize a with {}

a = {}

# check data type of a

print(type(a))

# initialize a with set()

a = set()

# check data type of a

print(type(a))

Output

<class 'dict'>

<class 'set'>
Modifying a set in Python

Sets are mutable. However, since they are unordered, indexing has no meaning.

We cannot access or change an element of a set using indexing or slicing. Set data type does
not support it.

We can add a single element using the add() method, and multiple elements using
the update() method. The update() method can take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.

# initialize my_set

my_set = {1, 3}

print(my_set)

# if you uncomment line 9,

# you will get an error

# TypeError: 'set' object does not support indexing

# my_set[0]

# add an element

# Output: {1, 2, 3}

my_set.add(2)

print(my_set)

# add multiple elements

# Output: {1, 2, 3, 4}
my_set.update([2, 3, 4])

print(my_set)

# add list and set

# Output: {1, 2, 3, 4, 5, 6, 8}

my_set.update([4, 5], {1, 6, 8})

print(my_set)

Output

{1, 3}

{1, 2, 3}

{1, 2, 3, 4}

{1, 2, 3, 4, 5, 6, 8}

Removing elements from a set

A particular item can be removed from a set using the methods discard() and remove().

The only difference between the two is that the discard() function leaves a set unchanged if the
element is not present in the set. On the other hand, the remove() function will raise an error in
such a condition (if element is not present in the set).

The following example will illustrate this.

# Difference between discard() and remove()

# initialize my_set

my_set = {1, 3, 4, 5, 6}

print(my_set)
# discard an element

# Output: {1, 3, 5, 6}

my_set.discard(4)

print(my_set)

# remove an element

# Output: {1, 3, 5}

my_set.remove(6)

print(my_set)

# discard an element

# not present in my_set

# Output: {1, 3, 5}

my_set.discard(2)

print(my_set)

# remove an element

# not present in my_set

# you will get an error.

# Output: KeyError

my_set.remove(2)

Output

{1, 3, 4, 5, 6}
{1, 3, 5, 6}

{1, 3, 5}

{1, 3, 5}

Traceback (most recent call last):

File "<string>", line 28, in <module>

KeyError: 2

Similarly, we can remove and return an item using the pop() method.

Since set is an unordered data type, there is no way of determining which item will be popped.
It is completely arbitrary.

We can also remove all the items from a set using the clear() method.

# initialize my_set

# Output: set of unique elements

my_set = set("HelloWorld")

print(my_set)

# pop an element

# Output: random element

print(my_set.pop())

# pop another element

my_set.pop()

print(my_set)

# clear my_set

# Output: set()
my_set.clear()

print(my_set)

print(my_set)

Output

{'H', 'l', 'r', 'W', 'o', 'd', 'e'}

{'r', 'W', 'o', 'd', 'e'}

set()

Python Set Operations

Sets can be used to carry out mathematical set operations like union, intersection, difference
and symmetric difference. We can do this with operators or methods.

Let us consider the following two sets for the following operations.

>>> A = {1, 2, 3, 4, 5}

>>> B = {4, 5, 6, 7, 8}

Set Union

Set Union in Python


Union of A and B is a set of all elements from both sets.

Union is performed using | operator. Same can be accomplished using the union() method.

# Set union method

# initialize A and B

A = {1, 2, 3, 4, 5}

B = {4, 5, 6, 7, 8}

# use | operator

# Output: {1, 2, 3, 4, 5, 6, 7, 8}

print(A | B)

Output

{1, 2, 3, 4, 5, 6, 7, 8}

Try the following examples on Python shell.

# use union function

>>> A.union(B)

{1, 2, 3, 4, 5, 6, 7, 8}

# use union function on B

>>> B.union(A)

{1, 2, 3, 4, 5, 6, 7, 8}

Set Intersection
Set Intersection in
Python

Intersection of A and B is a set of elements that are common in both the sets.

Intersection is performed using & operator. Same can be accomplished using


the intersection() method.

# Intersection of sets

# initialize A and B

A = {1, 2, 3, 4, 5}

B = {4, 5, 6, 7, 8}

# use & operator

# Output: {4, 5}

print(A & B)

Output

{4, 5}

Try the following examples on Python shell.

# use intersection function on A

>>> A.intersection(B)
{4, 5}

# use intersection function on B

>>> B.intersection(A)

{4, 5}

Set Difference

Set Difference in
Python

Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B.
Similarly, B - A is a set of elements in B but not in A.

Difference is performed using - operator. Same can be accomplished using


the difference() method.

# Difference of two sets

# initialize A and B

A = {1, 2, 3, 4, 5}

B = {4, 5, 6, 7, 8}

# use - operator on A
# Output: {1, 2, 3}

print(A - B)

Output

{1, 2, 3}

Try the following examples on Python shell.

# use difference function on A

>>> A.difference(B)

{1, 2, 3}

# use - operator on B

>>> B - A

{8, 6, 7}

# use difference function on B

>>> B.difference(A)

{8, 6, 7}

Set Symmetric Difference


Set Symmetric
Difference in Python

Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding
the intersection).

Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().

# Symmetric difference of two sets

# initialize A and B

A = {1, 2, 3, 4, 5}

B = {4, 5, 6, 7, 8}

# use ^ operator

# Output: {1, 2, 3, 6, 7, 8}

print(A ^ B)

Output

{1, 2, 3, 6, 7, 8}

Try the following examples on Python shell.

# use symmetric_difference function on A

>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}

# use symmetric_difference function on B

>>> B.symmetric_difference(A)

{1, 2, 3, 6, 7, 8}

Other Python Set Methods

There are many set methods, some of which we have already used above. Here is a list of all
the methods that are available with the set objects:

Method Description

add() Adds an element to the set

clear() Removes all elements from the set

copy() Returns a copy of the set

Returns the difference of two or more sets as a


difference()
new set

Removes all elements of another set from this


difference_update()
set

Removes an element from the set if it is a


discard()
member. (Do nothing if the element is not in set)

intersection() Returns the intersection of two sets as a new set


Updates the set with the intersection of itself
intersection_update()
and another

isdisjoint() Returns True if two sets have a null intersection

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Removes and returns an arbitrary set element.


pop()
Raises KeyError if the set is empty

Removes an element from the set. If the element


remove()
is not a member, raises a KeyError

Returns the symmetric difference of two sets as


symmetric_difference()
a new set

Updates a set with the symmetric difference of


symmetric_difference_update()
itself and another

union() Returns the union of sets in a new set

Updates the set with the union of itself and


update()
others

Other Set Operations

Set Membership Test

We can test if an item exists in a set or not, using the in keyword.


# in keyword in a set

# initialize my_set

my_set = set("apple")

# check if 'a' is present

# Output: True

print('a' in my_set)

# check if 'p' is present

# Output: False

print('p' not in my_set)

Output

True

False

Iterating Through a Set

We can iterate through each item in a set using a for loop.

>>> for letter in set("apple"):

... print(letter)

...

l
Built-in Functions with Set

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are
commonly used with sets to perform different tasks.

Function Description

Returns True if all elements of the set are true (or if the set is
all()
empty).

Returns True if any element of the set is true. If the set is empty,
any()
returns False.

Returns an enumerate object. It contains the index and value for all
enumerate()
the items of the set as a pair.

len() Returns the length (the number of items) in the set.

max() Returns the largest item in the set.

min() Returns the smallest item in the set.

Returns a new sorted list from elements in the set(does not sort the
sorted()
set itself).

sum() Returns the sum of all elements in the set.


Python Frozenset

Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed
once assigned. While tuples are immutable lists, frozensets are immutable sets.

Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand,
frozensets are hashable and can be used as keys to a dictionary.

Frozensets can be created using the frozenset() function.

This data type supports methods


like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_differe
nce() and union(). Being immutable, it does not have methods that add or remove elements.

# Frozensets

# initialize A and B

A = frozenset([1, 2, 3, 4])

B = frozenset([3, 4, 5, 6])

Try these examples on Python shell.

>>> A.isdisjoint(B)

False

>>> A.difference(B)

frozenset({1, 2})

>>> A | B

frozenset({1, 2, 3, 4, 5, 6})

>>> A.add(3)

...

AttributeError: 'frozenset' object has no attribute 'add'

Python Strings
A string is a sequence of characters.

Strings can be created by enclosing characters inside a single quote or double-quotes. Even
triple quotes can be used in Python but generally used to represent multiline strings and
docstrings.

# defining strings in Python

# all of the following are equivalent

my_string = 'Hello'

print(my_string)

my_string = "Hello"

print(my_string)

my_string = '''Hello'''

print(my_string)

# triple quotes string can extend multiple lines

my_string = """Hello, welcome to

the world of Python"""

print(my_string)

When you run the program, the output will be:

Hello

Hello

Hello
Hello, welcome to

the world of Python

How to access characters in a string?

We can access individual characters using indexing and a range of characters using slicing.
Index starts from 0. Trying to access a character out of index range will raise an IndexError.
The index must be an integer. We can't use floats or other types, this will result into TypeError.

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on. We can access a
range of items in a string by using the slicing operator :(colon).

#Accessing string characters in Python

str = 'programiz'

print('str = ', str)

#first character

print('str[0] = ', str[0])

#last character

print('str[-1] = ', str[-1])

#slicing 2nd to 5th character

print('str[1:5] = ', str[1:5])

#slicing 6th to 2nd last character

print('str[5:-2] = ', str[5:-2])


When we run the above program, we get the following output:

str = programiz

str[0] = p

str[-1] = z

str[1:5] = rogr

str[5:-2] = am

If we try to access an index out of the range or use numbers other than an integer, we will get
errors.

# index must be in range

>>> my_string[15]

...

IndexError: string index out of range

# index must be an integer

>>> my_string[1.5]

...

TypeError: string indices must be integers

Slicing can be best visualized by considering the index to be between the elements as shown
below.

If we want to access a range, we need the index that will slice the portion from the string.

String Slicing in
Python
Strings are immutable. This means that elements of a string cannot be changed once they have
been assigned. We can simply reassign different strings to the same name.

>>> my_string = 'programiz'

>>> my_string[5] = 'a'

...

TypeError: 'str' object does not support item assignment

>>> my_string = 'Python'

>>> my_string

'Python'

We cannot delete or remove characters from a string. But deleting the string entirely is possible
using the del keyword.

>>> del my_string[1]

...

TypeError: 'str' object doesn't support item deletion

>>> del my_string

>>> my_string

...

NameError: name 'my_string' is not defined

Python String Operations

There are many operations that can be performed with strings which makes it one of the most
used data types in Python.

To learn more about the data types available in Python visit: Python Data Types

Concatenation of Two or More Strings


Joining of two or more strings into a single one is called concatenation.

The + operator does this in Python. Simply writing two string literals together also
concatenates them.

The * operator can be used to repeat the string for a given number of times.

# Python String Operations

str1 = 'Hello'

str2 ='World!'

# using +

print('str1 + str2 = ', str1 + str2)

# using *

print('str1 * 3 =', str1 * 3)

When we run the above program, we get the following output:

str1 + str2 = HelloWorld!

str1 * 3 = HelloHelloHello

Writing two string literals together also concatenates them like + operator.

If we want to concatenate strings in different lines, we can use parentheses.

>>> # two string literals together

>>> 'Hello ''World!'

'Hello World!'

>>> # using parentheses

>>> s = ('Hello '

... 'World')
>>> s

'Hello World'

Iterating Through a string

We can iterate through a string using a for loop. Here is an example to count the number of 'l's
in a string.

# Iterating through a string

count = 0

for letter in 'Hello World':

if(letter == 'l'):

count += 1

print(count,'letters found')

When we run the above program, we get the following output:

3 letters found

String Membership Test

We can test if a substring exists within a string or not, using the keyword in.

>>> 'a' in 'program'

True

>>> 'at' not in 'battle'

False

Python String Formatting

Escape Sequence
If we want to print a text like He said, "What's there?", we can neither use single quotes nor
double quotes. This will result in a SyntaxError as the text itself contains both single and double
quotes.

>>> print("He said, "What's there?"")

...

SyntaxError: invalid syntax

>>> print('He said, "What's there?"')

...

SyntaxError: invalid syntax

One way to get around this problem is to use triple quotes. Alternatively, we can use escape
sequences.

An escape sequence starts with a backslash and is interpreted differently. If we use a single
quote to represent a string, all the single quotes inside the string must be escaped. Similar is
the case with double quotes. Here is how it can be done to represent the above text.

# using triple quotes

print('''He said, "What's there?"''')

# escaping single quotes

print('He said, "What\'s there?"')

# escaping double quotes

print("He said, \"What's there?\"")

When we run the above program, we get the following output:

He said, "What's there?"

He said, "What's there?"

He said, "What's there?"


Here is a list of all the escape sequences supported by Python.

Escape Sequence Description

\newline Backslash and newline ignored

\\ Backslash

\' Single quote

\" Double quote

\a ASCII Bell

\b ASCII Backspace

\f ASCII Formfeed

\n ASCII Linefeed

\r ASCII Carriage Return

\t ASCII Horizontal Tab

\v ASCII Vertical Tab

\ooo Character with octal value ooo

\xHH Character with hexadecimal value HH

Here are some examples


>>> print("C:\\Python32\\Lib")

C:\Python32\Lib

>>> print("This is printed\nin two lines")

This is printed

in two lines

>>> print("This is \x48\x45\x58 representation")

This is HEX representation

Raw String to ignore escape sequence

Sometimes we may wish to ignore the escape sequences inside a string. To do this we can
place r or R in front of the string. This will imply that it is a raw string and any escape sequence
inside it will be ignored.

>>> print("This is \x61 \ngood example")

This is a

good example

>>> print(r"This is \x61 \ngood example")

This is \x61 \ngood example

The format() Method for Formatting Strings

The format() method that is available with the string object is very versatile and powerful in
formatting strings. Format strings contain curly braces {} as placeholders or replacement fields
which get replaced.

We can use positional arguments or keyword arguments to specify the order.


# Python string format() method

# default(implicit) order

default_order = "{}, {} and {}".format('John','Bill','Sean')

print('\n--- Default Order ---')

print(default_order)

# order using positional argument

positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')

print('\n--- Positional Order ---')

print(positional_order)

# order using keyword argument

keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')

print('\n--- Keyword Order ---')

print(keyword_order)

When we run the above program, we get the following output:

--- Default Order ---

John, Bill and Sean

--- Positional Order ---

Bill, John and Sean

--- Keyword Order ---


Sean, Bill and John

Built-in String Methods

Python includes the following built-in methods to manipulate strings −

Sr.No. Methods with Description

1 capitalize()

Capitalizes first letter of string

2 center(width, fillchar)

Returns a space-padded string with the original string centered to a total of width
columns.

3 count(str, beg= 0,end=len(string))

Counts how many times str occurs in string or in a substring of string if starting
index beg and ending index end are given.

4 decode(encoding='UTF-8',errors='strict')

Decodes the string using the codec registered for encoding. encoding defaults to
the default string encoding.

5 encode(encoding='UTF-8',errors='strict')

Returns encoded string version of string; on error, default is to raise a ValueError


unless errors is given with 'ignore' or 'replace'.

6 endswith(suffix, beg=0, end=len(string))

Determines if string or a substring of string (if starting index beg and ending index
end are given) ends with suffix; returns true if so and false otherwise.

7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not
provided.

8 find(str, beg=0 end=len(string))

Determine if str occurs in string or in a substring of string if starting index beg and
ending index end are given returns index if found and -1 otherwise.

9 index(str, beg=0, end=len(string))

Same as find(), but raises an exception if str not found.

10 isalnum()

Returns true if string has at least 1 character and all characters are alphanumeric
and false otherwise.

11 isalpha()

Returns true if string has at least 1 character and all characters are alphabetic and
false otherwise.

12 isdigit()

Returns true if string contains only digits and false otherwise.

13 islower()

Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise.

14 isnumeric()

Returns true if a unicode string contains only numeric characters and false
otherwise.

15 isspace()
Returns true if string contains only whitespace characters and false otherwise.

16 istitle()

Returns true if string is properly "titlecased" and false otherwise.

17 isupper()

Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise.

18 join(seq)

Merges (concatenates) the string representations of elements in sequence seq into


a string, with separator string.

19 len(string)

Returns the length of the string

20 ljust(width[, fillchar])

Returns a space-padded string with the original string left-justified to a total of


width columns.

21 lower()

Converts all uppercase letters in string to lowercase.

22 lstrip()

Removes all leading whitespace in string.

23 maketrans()

Returns a translation table to be used in translate function.

24 max(str)
Returns the max alphabetical character from the string str.

25 min(str)

Returns the min alphabetical character from the string str.

26 replace(old, new [, max])

Replaces all occurrences of old in string with new or at most max occurrences if
max given.

27 rfind(str, beg=0,end=len(string))

Same as find(), but search backwards in string.

28 rindex( str, beg=0, end=len(string))

Same as index(), but search backwards in string.

29 rjust(width,[, fillchar])

Returns a space-padded string with the original string right-justified to a total of


width columns.

30 rstrip()

Removes all trailing whitespace of string.

31 split(str="", num=string.count(str))

Splits string according to delimiter str (space if not provided) and returns list of
substrings; split into at most num substrings if given.

32 splitlines( num=string.count('\n'))

Splits string at all (or num) NEWLINEs and returns a list of each line with
NEWLINEs removed.
33 startswith(str, beg=0,end=len(string))

Determines if string or a substring of string (if starting index beg and ending index
end are given) starts with substring str; returns true if so and false otherwise.

34 strip([chars])

Performs both lstrip() and rstrip() on string.

35 swapcase()

Inverts case for all letters in string.

36 title()

Returns "titlecased" version of string, that is, all words begin with uppercase and
the rest are lowercase.

37 translate(table, deletechars="")

Translates string according to translation table str(256 chars), removing those in


the del string.

38 upper()

Converts lowercase letters in string to uppercase.

39 zfill (width)

Returns original string leftpadded with zeros to a total of width characters; intended
for numbers, zfill() retains any sign given (less one zero).

40 isdecimal()

Returns true if a unicode string contains only decimal characters and false
otherwise.
Module 4

Object Oriented Programming in Python

Object-oriented programming is a programming paradigm that provides a means of


structuring programs so that properties and behaviors are bundled into individual objects.

For instance, an object could represent a person with properties like a name, age, and
address and behaviors such as walking, talking, breathing, and running. Or it could
represent an email with properties like a recipient list, subject, and body and behaviors like
adding attachments and sending.

Put another way, object-oriented programming is an approach for modeling concrete, real-
world things, like cars, as well as relations between things, like companies and employees,
students and teachers, and so on. OOP models real-world entities as software objects that
have some data associated with them and can perform certain functions.

Another common programming paradigm is procedural programming, which structures


a program like a recipe in that it provides a set of steps, in the form of functions and code
blocks, that flow sequentially in order to complete a task.

The difference between object-oriented and procedure-oriented programming is given


below:

BASIS FOR POP (Procedure oriented OOP (object oriented


COMPARISON programming) programming)

Basic Procedure/Structure oriented . Object oriented.

Approach Top-down. Bottom-up.

Basis Main focus is on "how to get Main focus is on 'data


the task done" i.e. on the security'. Hence, only
objects are permitted to
procedure or structure of a access the entities of a
program . class.

Division Large program is divided into Entire program is divided


units called functions. into objects.

Entity accessing No access specifier observed. Access specifier are


mode "public", "private",
"protected".

Overloading or Neither it overload functions It overloads functions,


Polymorphism nor operators. constructors, and
operators.

Inheritance Their is no provision of Inheritance achieved in


inheritance. three modes public private
and protected.

Data hiding & There is no proper way of Data is hidden in three


security hiding the data, so data is modes public, private, and
insecure protected. hence data
security increases.

Data sharing Global data is shared among the Data is shared among the
functions in the program. objects through the
member functions.

One of the popular approaches to solve a programming problem is by creating objects. This
is known as Object-Oriented Programming (OOP).

An object has two characteristics:

attributes

behavior

Major principles of object-oriented programming system are given below.


Overview of OOP Terminology

Class − A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class variables and
instance variables) and methods, accessed via dot notation.

Class variable − A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables are not used
as frequently as instance variables are.

Data member − A class variable or instance variable that holds data associated with a
class and its objects.

Function overloading − The assignment of more than one behavior to a particular


function. The operation performed varies by the types of objects or arguments involved.

Instance variable − A variable that is defined inside a method and belongs only to the
current instance of a class.

Inheritance − The transfer of the characteristics of a class to other classes that are derived
from it.

Instance − An individual object of a certain class. An object obj that belongs to a class
Circle, for example, is an instance of the class Circle.

Instantiation − The creation of an instance of a class.

Method − A special kind of function that is defined in a class definition.

Object − A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.

Operator overloading − The assignment of more than one function to a particular


operator.

Class

The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it should
contain an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax

class ClassName:
<statement-1>
.
.
<statement-N>

Object

The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.

Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code.

When we define a class, it needs to create an object to allocate the memory. Consider the
following example.

Example:

class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)

c1 = car("Toyota", 2016)
c1.display()

Method

The method is a function that is associated with an object. In Python, a method is not unique
to class instances. Any object type can have methods.
Inheritance

Inheritance is the most important aspect of object-oriented programming, which simulates


the real-world concept of inheritance. It specifies that the child object acquires all the
properties and behaviors of the parent object.

By using inheritance, we can create a class which uses all the properties and behavior of
another class. The new class is known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.

It provides the re-usability of the code.

Polymorphism

Polymorphism contains two words "poly" and "morphs". Poly means many, and morph
means shape. By polymorphism, we understand that one task can be performed in different
ways. For example - you have a class animal, and all animals speak. But they speak
differently. Here, the "speak" behavior is polymorphic in a sense and depends on the
animal. So, the abstract "animal" concept does not actually "speak", but specific animals
(like dogs and cats) have a concrete implementation of the action "speak".

Encapsulation

Encapsulation is also an essential aspect of object-oriented programming. It is used to


restrict access to methods and variables. In encapsulation, code and data are wrapped
together within a single unit from being modified by accident.

Data Abstraction

Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonyms because data abstraction is achieved through encapsulation.

Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of what a
function or a whole program does.
Python Class and Objects

Suppose a class is a prototype of a building. A building contains all the details about the
floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on
these details. Hence, the building can be seen as a class, and we can create as many objects
of this class.

On the other hand, the object is the instance of a class. The process of creating an object
can be called instantiation.

Creating classes in Python

In Python, a class can be created by using the keyword class, followed by the class name.
The syntax to create a class is given below.

Syntax

class ClassName:
#statement_suite

In Python, we must notice that each class is associated with a documentation string which
can be accessed by using <class-name>.__doc__. A class contains a statement suite
including fields, constructor, function, etc. definition.

Consider the following example to create a class Employee which contains two fields as
Employee id, and name.

The class also contains a function display(), which is used to display the information of
the Employee.

Example

class Employee:
id = 10
name = "Devansh"
def display (self):
print(self.id,self.name)
Here, the self is used as a reference variable, which refers to the current class object. It is
always the first argument in the function definition. However, using self is optional in the
function call.

The self-parameter

The self-parameter refers to the current instance of the class and accesses the class
variables. We can use anything instead of self, but it must be the first parameter of any
function which belongs to the class.

Creating an instance of the class

A class needs to be instantiated if we want to use the class attributes in another class or
method. A class can be instantiated by calling the class using the class name.

The syntax to create the instance of the class is given below.

<object-name> = <class-name>(<arguments>)

The following example creates the instance of the class Employee defined in the above
example.

Example

class Employee:
id = 10
name = "John"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
# Creating a emp instance of Employee class
emp = Employee()
emp.display()

Delete the Object

We can delete the properties of the object or object itself by using the del keyword.
Consider the following example.
Example

class Employee:
id = 10
name = "John"

def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
# Creating a emp instance of Employee class

emp = Employee()

# Deleting the property of object


del emp.id
# Deleting the object itself
del emp

Python Constructor

A constructor is a special type of method (function) which is used to initialize the instance
members of the class.

In C++ or Java, the constructor has the same name as its class, but it treats constructor
differently in Python. It is used to create an object.

Constructors can be of two types.

Parameterized Constructor

Non-parameterized Constructor

Constructor definition is executed when we create the object of this class. Constructors also
verify that there are enough resources for the object to perform any start-up task.

Creating the constructor in python


In Python, the method the __init__() simulates the constructor of the class. This method is
called when the class is instantiated. It accepts the self-keyword as a first argument which
allows accessing the attributes or method of the class.

We can pass any number of arguments at the time of creating the class object, depending
upon the __init__() definition. It is mostly used to initialize the class attributes. Every class
must have a constructor, even if it simply relies on the default constructor.

Consider the following example to initialize the Employee class attributes.

Example
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name

def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))

emp1 = Employee("John", 101)


emp2 = Employee("David", 102)

# accessing display() method to print employee 1 information

emp1.display()

# accessing display() method to print employee 2 information


emp2.display()

The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.
You declare other class methods like normal functions with the exception that the first
argument to each method is self. Python adds the self argument to the list for you; you do
not need to include it when you call the methods.

Counting the number of objects of a class

The constructor is called automatically when we create the object of the class. Consider the
following example.

Example
class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",Student.count)

Python Non-Parameterized Constructor

The non-parameterized constructor uses when we do not want to manipulate the value or
the constructor that has only self as an argument. Consider the following example.

Example
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")

Python Parameterized Constructor


The parameterized constructor has multiple parameters along with the self. Consider the
following example.

Example
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()

Python Default Constructor

When we do not include the constructor in the class or forget to declare it, then that becomes
the default constructor. It does not perform any task but initializes the objects. Consider the
following example.

Example
class Student:
roll_num = 101
name = "Joseph"

def display(self):
print(self.roll_num,self.name)

st = Student()
st.display()

Output:

101 Joseph

More than One Constructor in Single class


Let's have a look at another scenario, what happen if we declare the two same constructors
in the class.

Example
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")

st = Student()

Output:

The Second Constructor

In the above code, the object st called the second constructor whereas both have the same
configuration. The first method is not accessible by the st object. Internally, the object of
the class will always call the last constructor if the class has multiple constructors.

Python built-in class functions

The built-in functions defined in the class are described in the following table.

SN Function Description

1 getattr(obj,name,default) It is used to access the attribute of the object.

2 setattr(obj, name,value) It is used to set a particular value to the specific


attribute of an object.

3 delattr(obj, name) It is used to delete a specific attribute.


4 hasattr(obj, name) It returns true if the object contains some specific
attribute.

Example
class Student:
def __init__(self, name, id, age):
self.name = name
self.id = id
self.age = age

# creates the object of the class Student


s = Student("John", 101, 22)

# prints the attribute name of the object s


print(getattr(s, 'name'))

# reset the value of attribute age to 23


setattr(s, "age", 23)

# prints the modified value of age


print(getattr(s, 'age'))

# prints true if the student contains the attribute with name id

print(hasattr(s, 'id'))
# deletes the attribute age
delattr(s, 'age')

# this will give an error since the attribute age has been deleted
print(s.age)

Output:

John
23
True
AttributeError: 'Student' object has no attribute 'age'

Built-in class attributes

Along with the other attributes, a Python class also contains some built-in class attributes
which provide information about the class.

The built-in class attributes are given in the below table.

SN Attribute Description

1 __dict__ It provides the dictionary containing the information about


the class namespace.

2 __doc__ It contains a string which has the class documentation

3 __name__ It is used to access the class name.

4 __module__ It is used to access the module in which, this class is


defined.

5 __bases__ It contains a tuple including all base classes.

Example
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)

Output:

None
{'name': 'John', 'id': 101, 'age': 22}
__main__

Class and Instance Attributes and Methods

Class Attributes: class attributes are common to all instances/objects of a class. Class
attributes are defined in class definition but outside __init__() method.

Instance Attributes: Instance attributes are specific to each object and they change from
one object to other object. These are defined in __init__() method.

Class method: Methods defined to work with class attributes/variables.

Decorator @classmethod is used to define class methods.

Instance method: Methods defined to work with instance attributes/variables.

No Decorator is used to define instance methods.

Static method: Methods defined to include general definition. Static methods doesn’t work
with instance or class attributes

Decorator @staticmethod is used to define static methods.


Encapsulation

Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It


describes the idea of wrapping data and the methods that work on data within one unit. This
puts restrictions on accessing variables and methods directly and can prevent the accidental
modification of data. To prevent accidental change, an object’s variable can only be changed
by an object’s method. Those types of variables are known as private variable.
A class is an example of encapsulation as it encapsulates all the data that is member functions,
variables, etc.

Access modifiers

Access modifiers limit access to the variables and functions of a class. Python uses three
types of access modifiers; they are - private, public and protected.

Public members

Public members are accessible anywhere from the class. All the member variables of the
class are by default public.
Protected members

Protected members are accessible within the class and also available to its sub-classes. To
define a protected member, prefix the member name with a single underscore “_”. In
python implementation of protected is same as public except that protected is defined with
prefix of _ .

Private members

Private members are accessible within the class. To define a private member, prefix the
member name with a double underscore “__”.
Private data members cannot be accessed outside the class definition as well in the sub classes.
They can only be accessed within the class definition as shown below
Python Inheritance
The method of inheriting the properties of parent class into a child class is known as
inheritance. It is an OOP concept. Following are the benefits of inheritance.

Code reusability- we do not have to write the same code again and again, we can just inherit
the properties we need in a child class.

It represents a real world relationship between parent class and child class.

It is transitive in nature. If a child class inherits properties from a parent class, then all other
sub-classes of the child class will also inherit the properties of the parent class.

Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides


code reusability to the program because we can use an existing class to create a new class
instead of creating it from scratch.

In inheritance, the child class acquires the properties and can access all the data members
and functions defined in the parent class. A child class can also provide its specific
implementation to the functions of the parent class.

Types Of Inheritance In Python

Python supports 5 types of inheritance namely,

1. Single
2. Multiple
3. Multilevel
4. Hierarchical
5. Hybrid

Single Inheritance

In single inheritance, a child class inherits all the properties of a parent class.

Syntax
class derived-class(base class):
<class-suite>

A class can inherit multiple classes by mentioning all of them inside the bracket. Consider
the following syntax.

Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()

Output:

dog barking
Animal Speaking

Multi-Level inheritance

Multi-Level inheritance is possible in python like other object-oriented languages. Multi-


level inheritance is archived when a derived class inherits another derived class. There is
no limit on the number of levels up to which, the multi-level inheritance is archived in
python.
The syntax of multi-level inheritance is given below.

Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
.
.
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()

Output:

dog barking
Animal Speaking
Eating bread...

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.

The syntax to perform multiple inheritance is given below.

Syntax
class Base1:
<class-suite>

class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>

class Derived(Base1, Base2, ...... BaseN):


<class-suite>
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))

Output:

30
200
0.5

Method Resolution Order


Method Resolution Order(MRO) it denotes the way a programming language resolves a
method or attribute. Python supports classes inheriting from other classes. The class being
inherited is called the Parent or Superclass, while the class that inherits is called the Child
or Subclass. In python, method resolution order defines the order in which the base classes
are searched when executing a method. First, the method or attribute is searched within a
class and then it follows the order we specified while inheriting. This order is also called
Linearization of a class and set of rules are called MRO(Method Resolution Order). While
inheriting from another class, the interpreter needs a way to resolve the methods that are
being called via an instance. Thus we need the method resolution order. MRO is following
the order: left-to-right, depth-first
Hierrachical inheritance

In this type of inheritance, more than one child classes inherit all the properties of
the same parent class

class Parent:

def func1(self):

print("this is function 1")

class Child(Parent):

def func2(self):
print("this is function 2")

class Child2(Parent):

def func3(self):

print("this is function 3")

ob = Child()

ob1 = Child2()

ob.func1()

ob.func2()

Hybrid Inheritance in Python

Hybrid inheritance is a combination of multiple and multilevel inheritance. More than one
child class inherits a parent class. Those two child class, in turn, acts as the parent class for
a grandchild class as shown in the below image.
class Parent:

def func1(self):

print("this is function one")

class Child(Parent):

def func2(self):

print("this is function 2")

class Child1(Parent):

def func3(self):

print(" this is function 3"):

class Child3(Parent , Child1):

def func4(self):
print(" this is function 4")

ob = Child3()

ob.func1()

The issubclass(sub,sup) method

The issubclass(sub, sup) method is used to check the relationships between the specified
classes. It returns true if the first class is the subclass of the second class, and false
otherwise.

Consider the following example.

Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))

Output:

True
False
The isinstance (obj, class) method

The isinstance() method is used to check the relationship between the objects and classes.
It returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e.,
class.

Consider the following example.

Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(isinstance(d,Derived))

Output:

True

Python Super() Function

Super function allows us to call a method from the parent class.

class Parent:

def func1(self):

print("this is function 1")

class Child(Parent):

def func2(self):
Super().func1()

print("this is function 2")

ob = Child()

ob.func2()

Redefining Methods:

If you want your subclass to redefine a method of the parent class (so that it does something
different), you can just type a new definition for this method’s name in the subclass.

The old code won’t get executed.

If you want the old code to be executed in addition to your new code for some method, then
you must explicitly call the parent’s version of the method.

parentClass.methodName(self, a, b, c)

If you want your subclass to redefine a method of the parent class (so that it does something
different), you can just type a new definition for this method’s name in the subclass.

The old code won’t get executed.

If you want the old code to be executed in addition to your new code for some method, then
you must explicitly call the parent’s version of the method.

parentClass.methodName(self, a, b, c)

The only time you ever explicitly pass ‘self’ as an argument is when calling a
method of an ancestor.

Redefining the __init__

Same as for redefining any other method…

In this case, it’s very common that you will want to execute the ancestor’s __init__
method in addition to your new commands.

You’ll often see something like this in the __init__ method of subclasses:
parentClass.__init__(self, x, y)

where parentClass is the name of the parent’s class.

class User:

def __init__(self, name):

self.name = name

def printName(self):

print ("Name = " + self.name)

class Programmer(User):

def __init__(self,fname,lname):

User.__init__(self,fname)

self.last_name =lname

def printName(self):

print("FullName",self.name,self.last_name)

def display(self):

User.printName(self)

brian = User("brian")

brian.printName()

diana = Programmer("Diana","Peter")

diana.printName()

diana.display()

Output:
Name = brian

FullName Diana Peter

Name = Diana

Polymorphism in Python

Polymorphism is taken from the Greek words Poly (many) and morphism (forms). It means
that the same function name can be used for different types. This makes programming more
intuitive and easier.

In Python, we have different ways to define polymorphism.

A child class inherits all the methods from the parent class. However, in some situations,
the method inherited from the parent class doesn’t quite fit into the child class. In such
cases, you will have to re-implement method in the child class.

There are different methods to use polymorphism in Python. You can use different
function, class methods or objects to define polymorphism.

Polymorphism in python can be implemented using overloading and overriding


techniques.

Overloading: Overloading, in the context of programming, refers to the ability of a


function or an operator to behave in different ways depending on the parameters that are
passed to the function, or the operands that the operator acts on. Overloading a method
fosters reusability. For instance, instead of writing multiple methods that differ only
slightly, we can write one method and overload it. Overloading also improves code clarity
and eliminates complexity.

Overloading Built-in Functions

It is possible for us to change the default behavior of Python's built-in functions. We only
have to define the corresponding special method in our class.

Let us demonstrate this using Python's len() function on our Purchase class:
class Purchase:
def __init__(self, basket, buyer):
self.basket = list(basket)
self.buyer = buyer

def __len__(self):
return 10;

purchase = Purchase(['pen', 'book', 'pencil'], 'Python')


print(len(purchase))

Overloading User-Defined Functions


To overload a user-defined function in Python, we need to write the function logic in such
a way that depending upon the parameters passed, a different piece of code executes inside
the function. Take a look at the following example:
class Student:
def hello(self, name=None):
if name is not None:
print('Hey ' + name)
else:
print('Hey ')

# Creating a class instance


std = Student()

# Call the method


std.hello()

# Call the method and pass a parameter


std.hello('Nicholas')

Function Overloading in Python

Depending on how the function has been defined, we can call it with zero, one, two, or even
many parameters. This is referred to as "function overloading".

Function overloading is further divided into two types: overloading built-in functions and
overloading custom functions.

Polymorphism with Function and Objects

You can create a function that can take any object, allowing for polymorphism.

Let’s take an example and create a function called “func()” which will take an object which
we will name “obj”. Now, let’s give the function something to do that uses the ‘obj’ object
we passed to it. In this case, let’s call the methods type() and color(), each of which is
defined in the two classes ‘Tomato’ and ‘Apple’. Now, you have to create instantiations of
both the ‘Tomato’ and ‘Apple’ classes if we don’t have them already:
class Tomato():

def type(self):

print("Vegetable")

def color(self):

print("Red")

class Apple():

def type(self):

print("Fruit")

def color(self):

print("Red")

def func(obj):

obj.type()

obj.color()

obj_tomato = Tomato()

obj_apple = Apple()

func(obj_tomato)

func(obj_apple)

Output:

Vegetable
Red
Fruit
Red

Polymorphism with Class Methods

Python uses two different class types in the same way. Here, you have to create a for
loop that iterates through a tuple of objects. Next, you have to call the methods without
being concerned about which class type each object is. We assume that these methods
actually exist in each class.

Here is an example to show polymorphism with class:

class India():
def capital(self):
print("New Delhi")

def language(self):
print("Hindi and English")

class USA():
def capital(self):
print("Washington, D.C.")

def language(self):
print("English")

obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
Output:

New Delhi
Hindi and English
Washington, D.C.
English

Operator Overloading
Python allows us to change the default behavior of an operator depending on the operands
that we use. This practice is referred to as "operator overloading".

The functionality of Python operators depends on built-in classes. However, the same
operator will behave differently when applied to different types. A good example is the "+"
operator. This operator will perform an arithmetic operation when applied on two numbers,
will concatenate two strings, and will merge two lists.

This feature in Python that allows the same operator to have different meaning according
to the context is called operator overloading.

class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
p1 = Point(1, 2)
p2 = Point(2, 3)
print(p1+p2)

Output

Traceback (most recent call last):


File "<string>", line 9, in <module>
print(p1+p2)
TypeError: unsupported operand type(s) for +: 'Point' and 'Point'

Here, we can see that a TypeError was raised, since Python didn't know how to add
two Point objects together.
However, we can achieve this task in Python through operator overloading.

To overload operators their respective special methods should be implemented in the class.

To overload the + operator, we will need to implement __add__() function in the class. To
overload the - operator, we will need to implement __sub__() function in the class.

Consider that we have two objects which are a physical representation of a class (user-defined
data type) and we have to add two objects with binary ‘+’ operator it throws an error, because
compiler don’t know how to add two objects. So we define a method for an operator and that
process is called operator overloading. We can overload all existing operators but we can’t
create a new operator. To perform operator overloading, Python provides some special
function or magic function that is automatically invoked when it is associated with that
particular operator. For example, when we use + operator, the magic method __add__ is
automatically invoked in which the operation for + operator is defined.

NAME Symbol Special Function

Addition + __add__(self, other)

Subtraction - __sub__(self, other)

Division / __truediv__(self, other)

Floor Division // __floordiv__(self, other)

Modulus(or Remainder) % __mod__(self, other)


Power ** __pow__(self, other)

Addition + __add__(self, other)

Subtraction - __sub__(self, other)

Division / __truediv__(self, other)

Floor Division // __floordiv__(self, other)

Modulus(or Remainder) % __mod__(self, other)

Power ** __pow__(self, other)

Less than < __lt__(self, other)

Greater than > __gt__(self, other)

Equal to == __eq__(self, other)

Not equal != __ne__(self, other)

Less than or equal to <= __le__(self, other)

Greater than or equal to >= __gt__(self, other)

Assignment Operators :

OPERATOR MAGIC METHOD

-= __ISUB__(SELF, OTHER)

+= __IADD__(SELF, OTHER)
*= __IMUL__(SELF, OTHER)

/= __IDIV__(SELF, OTHER)

//= __IFLOORDIV__(SELF, OTHER)

%= __IMOD__(SELF, OTHER)

**= __IPOW__(SELF, OTHER)

>>= __IRSHIFT__(SELF, OTHER)

<<= __ILSHIFT__(SELF, OTHER)

&= __IAND__(SELF, OTHER)

|= __IOR__(SELF, OTHER)

^= __IXOR__(SELF, OTHER)

Unary Operators :

OPERATOR MAGIC METHOD

– __NEG__(SELF, OTHER)

+ __POS__(SELF, OTHER)

~ __INVERT__(SELF, OTHER)

class A:
def __init__(self, a):
self.a = a
def __lt__(self, other):
if(self.a<other.a):
return "ob1 is lessthan ob2"
else:
return "ob2 is less than ob1"
def __eq__(self, other):
if(self.a == other.a):
return "Both are equal"
else:
return "Not equal"

ob1 = A(2)
ob2 = A(3)
print(ob1 < ob2)

ob3 = A(4)
ob4 = A(4)
print(ob1 == ob2)

output:

ob1 is lessthan ob2

Not equal

Overriding:

A subclass may change the functionality of a Python method and


variables(attributes) in the superclass. It does so by redefining them.

Polymorphism in python defines methods in the child class that have the same name as the
methods in the parent class. In inheritance, the child class inherits the methods from the
parent class. Also, it is possible to modify a method in a child class that it has inherited
from the parent class.

This is mostly used in cases where the method inherited from the parent class doesn’t fit
the child class. This process of re-implementing a method in the child class is known
as Method Overriding. Here is an example that shows polymorphism with inheritance:

class Bird:

def intro(self):

print("There are different types of birds")

def flight(self):

print("Most of the birds can fly but some cannot")

class parrot(Bird):

def flight(self):

print("Parrots can fly")

class penguin(Bird):

def flight(self):

print("Penguins do not fly")

obj_bird = Bird()

obj_parr = parrot()

obj_peng = penguin()

obj_bird.intro()
obj_bird.flight()

obj_parr.intro()

obj_parr.flight()

obj_peng.intro()

obj_peng.flight()

Output:

There are different types of birds


Most of the birds can fly but some cannot
There are different types of bird
Parrots can fly
There are many types of birds
Penguins do not fly

Garbage Collection in Python

Python’s memory allocation and deallocation method is automatic. The user does not have
to preallocate or deallocate memory similar to using dynamic memory allocation in
languages such as C or C++.
Python uses two strategies for memory allocation:

1. Reference counting
2. Garbage collection
the Python interpreter only used reference counting for memory management. Reference
counting works by counting the number of times an object is referenced by other objects in
the system. When references to an object are removed, the reference count for an object is
decremented. When the reference count becomes zero, the object is deallocated. Ex-

filter_none
# Literal 9 is an object
b=9

# Reference count of object 9


# becomes 0.
b=4
The literal value 9 is an object. The reference count of object 9 is incremented to 1 in line 1.
In line 2 its reference count becomes zero as it is dereferenced. So garbage collector
deallocates the object.

A reference cycle is created when there is no way the reference count of the object can reach.
Reference cycles involving lists, tuples, instances, classes, dictionaries, and functions are
common. The easiest way to create a reference cycle is to create an object which refers to
itself as in the example below:

def create_cycle():

# create a list x
x=[]

# A reference cycle is created


# here as x contains reference to
# to self.
x.append(x)

create_cycle()
Because create_cycle() creates an object x which refers to itself, the object x will not
automatically be freed when the function returns. This will cause the memory that x is using
to be held onto until the Python garbage collector is invoked.

Because reference cycles take computational work to discover, garbage collection must be a
scheduled activity. Python schedules garbage collection based upon a threshold of object
allocations and object deallocations. When the number of allocations minus the number of
deallocations is greater than the threshold number, the garbage collector is run. One can
inspect the threshold for new objects (objects in Python known as generation 0 objects) by
importing the gc module and asking for garbage collection thresholds:

# loading gc
import gc

# get the current collection


# thresholds as a tuple
print("Garbage collection thresholds:",
gc.get_threshold())
Output:

Garbage collection thresholds: (700, 10, 10)

Manual Garbage Collection


Invoking the garbage collector manually during the execution of a program can be a good
idea on how to handle memory being consumed by reference cycles.
The garbage collection can be invoked manually in the following way:

# Importing gc module
import gc

# Returns the number of


# objects it has collected
# and deallocated
collected = gc.collect()

# Prints Garbage collector


# as 0 object
print("Garbage collector: collected",
"%d objects." % collected)
If few cycles are created, then how manual collection works:
Example:
filter_none

edit

play_arrow

brightness_4

import gc
i=0

# create a cycle and on each iteration x as a dictionary


# assigned to 1
def create_cycle():
x={}
x[i+1] = x
print x

# lists are cleared whenever a full collection or


# collection of the highest generation (2) is run
collected = gc.collect() # or gc.collect(2)
print "Garbage collector: collected %d objects." % (collected)

print "Creating cycles..."


for i in range(10):
create_cycle()

collected = gc.collect()

print "Garbage collector: collected %d objects." % (collected)


Output:

Garbage collector: collected 0 objects.

Creating cycles...

{1: {...}}

{2: {...}}
{3: {...}}

{4: {...}}

{5: {...}}

{6: {...}}

{7: {...}}

{8: {...}}

{9: {...}}

{10: {...}}

Garbage collector: collected 10 objects.

There are two ways for performing manual garbage collection: time-based and event-based
garbage collection.
Time-based garbage collection is simple: the garbage collector is called after a fixed time
interval.
Event-based garbage collection calls the garbage collector on event occurrence. For
example, when a user exits the application or when the application enters into idle state.
gc.enable()Enable automatic garbage collection.

gc.disable()Disable automatic garbage collection.

gc.isenabled()Returns true if automatic collection is enabled.

gc.collect() run a full collection.


Module 5

Exception handling and web scrapping

Python Exceptions

An exception can be defined as an unusual condition in a program resulting in the interruption


in the flow of the program.

Whenever an exception occurs, the program stops the execution, and thus the further code is
not executed. Therefore, an exception is the run-time errors that are unable to handle a Python
script. An exception is a Python object that represents an error.

The cause of an exception is often external to the program itself. For example, an incorrect
input, a malfunctioning IO device etc. Because the program abruptly terminates on
encountering an exception, it may cause damage to system resources, such as files. Hence,
the exceptions should be properly handled so that an abrupt termination of the program is
prevented. Exceptions are raised when the program is syntactically correct but the code resulted
in an error.

Python provides a way to handle the exception so that the code can be executed without any
interruption. If we do not handle the exception, the interpreter doesn't execute all the code that
exists after the exception.

>>> print( 0 / 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
This time, you ran into an exception error. This type of error occurs whenever syntactically
correct Python code results in an error. The last line of the message indicated what type of
exception error you ran into.

Instead of showing the message exception error, Python details what type of exception error
was encountered. In this case, it was a ZeroDivisionError. Python comes with various built-in
exceptions as well as the possibility to create self-defined exceptions.
Example:

# initialize the amount variable


marks = 10000

# perform division with 0


a = marks / 0
print(a)
Output:

Common Exceptions

Python provides the number of built-in exceptions, but here we are describing the common
standard exceptions. A list of common exceptions that can be thrown from a standard Python
program is given below.

1. ZeroDivisionError: Occurs when a number is divided by zero.


2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

Advantages of Exception Handling

 Separating Error Handling Code from "Regular" Code.


 Propagating Errors Up the Call Stack.
 Function A calls function B which in turn calls function C and an exception occurs in
function C. If it is not handled in C, the exception passes to B and then to A.
 If never handled, an error message is given and program comes to a sudden, unexpected
halt.
 Grouping Error Types and Error Differentiation.

Exception hierarchy

Sr.No. Exception Name & Description

1
Exception

Base class for all exceptions

2
StopIteration

Raised when the next() method of an iterator does not point to any object.

3
SystemExit

Raised by the sys.exit() function.


4
StandardError

Base class for all built-in exceptions except StopIteration and SystemExit.

5
ArithmeticError

Base class for all errors that occur for numeric calculation.

6
OverflowError

Raised when a calculation exceeds maximum limit for a numeric type.

7
FloatingPointError

Raised when a floating point calculation fails.

8
ZeroDivisionError

Raised when division or modulo by zero takes place for all numeric types.

9
AssertionError

Raised in case of failure of the Assert statement.

10
AttributeError

Raised in case of failure of attribute reference or assignment.

11
EOFError

Raised when there is no input from either the raw_input() or input() function and
the end of file is reached.

12
ImportError

Raised when an import statement fails.

13
KeyboardInterrupt

Raised when the user interrupts program execution, usually by pressing Ctrl+c.
14
LookupError

Base class for all lookup errors.

15
IndexError

Raised when an index is not found in a sequence.

16
KeyError

Raised when the specified key is not found in the dictionary.

17
NameError

Raised when an identifier is not found in the local or global namespace.

18
UnboundLocalError

Raised when trying to access a local variable in a function or method but no value
has been assigned to it.

19
EnvironmentError

Base class for all exceptions that occur outside the Python environment.

20
IOError

Raised when an input/ output operation fails, such as the print statement or the
open() function when trying to open a file that does not exist.

21
IOError

Raised for operating system-related errors.

22
SyntaxError

Raised when there is an error in Python syntax.

23
IndentationError
Raised when indentation is not specified properly.

24
SystemError

Raised when the interpreter finds an internal problem, but when this error is
encountered the Python interpreter does not exit.

25
SystemExit

Raised when Python interpreter is quit by using the sys.exit() function. If not
handled in the code, causes the interpreter to exit.

26
TypeError

Raised when an operation or function is attempted that is invalid for the specified
data type.

27
ValueError

Raised when the built-in function for a data type has the valid type of arguments,
but the arguments have invalid values specified.

28
RuntimeError

Raised when a generated error does not fall into any category.

29
NotImplementedError

Raised when an abstract method that needs to be implemented in an inherited class


is not actually implemented.

Exception handling in python


The try-expect statement

If the Python program contains suspicious code that may throw the exception, we must place
that code in the try block. The try block must be followed with the except statement, which
contains a block of code that will be executed if there is some exception in the try block.
The try: block contains one or more statements which are likely to encounter an exception.
If the statements in this block are executed without an exception, the subsequent except:
block is skipped.

If the exception does occur, the program flow is transferred to the except: block. The
statements in the except: block are meant to handle the cause of the exception appropriately.
For example, returning an appropriate error message.

You can mention a specific type of exception in front of the except keyword. The subsequent
block will be executed only if the specified exception occurs. There may be multiple except
clauses with different exception types in a single try block. If the type of exception doesn't
match any of the except blocks, it will remain unhandled and the program will terminate.

The rest of the statements after the except block will continue to be executed, regardless if
the exception is encountered or not.

You can mention a specific type of exception in front of the except keyword. The
subsequent block will be executed only if the specified exception occurs. There may be
multiple except clauses with different exception types in a single try block. If the type of
exception doesn't match any of the except blocks, it will remain unhandled and the program
will terminate.
Syntax

try:
#block of code

except Exception1:
#block of code

except Exception2:
#block of code

#other code

Consider the following example.

Example 1

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")

Output:

Enter a:10
Enter b:0
Can't divide with zero

We can also use the else statement with the try-except statement in which, we can place the
code which will be executed in the scenario if no exception occurs in the try block.

The syntax to use the else statement with the try-except statement is given below.

try:
#block of code

except Exception1:
#block of code

else:
#this code executes if no except block is executed

In Python, keywords else and finally can also be used along with the try and except clauses.
While the except block is executed if the exception occurs inside the try block, the else
block gets processed if the try block is found to be exception free.

Consider the following program.

Example 2

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it will return exception c
lass
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")

Output:

Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>
The except statement with no exception

Python provides the flexibility not to specify the name of exception with the exception
statement.

Consider the following example.

Example

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
The except statement using with exception variable

We can use the exception variable with the except statement. It is used by using
the as keyword. this object will return the cause of the exception. Consider the following
example:

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")

Output:

Enter a:10
Enter b:0
can't divide by zero
division by zero

 Python facilitates us to not specify the exception with the except statement.

 We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.

 We can also specify an else block along with the try-except statement, which will be
executed if no exception is raised in the try block.

 The statements that don't throw the exception should be placed inside the else block.

Example

try:
#this will throw an exception if the file doesn't exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()

Output:

File not found


Declaring Multiple Exceptions

The Python allows us to declare the multiple exceptions with the except clause. Declaring
multiple exceptions is useful in the cases where a try block throws multiple exceptions. The
syntax is given below.

Syntax

try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)


#block of code

else:
#block of code

Consider the following example.

try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")
Output:

Arithmetic Exception
The try...finally block

Python provides the optional finally statement, which is used with the try statement. It is
executed no matter what exception occurs and used to release the external resource. The finally
block provides a guarantee of the execution.

We can use the finally block with the try block in which we can pace the necessary code, which
must be executed before the try statement throws an exception.

The syntax to use the finally block is given below.

Syntax

try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
The finally block consists of statements which should be processed regardless of an
exception occurring in the try block or not. As a consequence, the error-free try block skips
the except clause and enters the finally block before going on to execute the rest of the
code. If, however, there's an exception in the try block, the appropriate except block will
be processed, and the statements in the finally block will be processed before proceeding
to the rest of the code.
Raising exceptions

An exception can be raised forcefully by using the raise clause in Python. It is useful in in that
scenario where we need to raise an exception to stop the execution of the program.

For example, there is a program that requires 2GB memory for execution, and if the program
tries to occupy 2GB of memory, then we can raise an exception to stop the execution of the
program.

The syntax to use the raise statement is given below.

Syntax

1. raise Exception_class,<value>
To raise an exception, the raise statement is used. The exception class name follows it.

An exception can be provided with a value that can be given in the parenthesis.
To access the value "as" keyword is used. exception variable is used sed as a reference variable
which stores the value of the exception.

We can pass the value to an exception to specify the exception type.

Example

try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")

Output:

Enter the age:17


The age is not valid

Example 2 Raise the exception with message

try:
num = int(input("Enter a positive integer: "))
if(num <= 0):
# we can pass the message in the raise statement
raise ValueError("That is a negative number!")
except ValueError as e:
print(e)

Output:

Enter a positive integer: -5


That is a negative number!

Example 3
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
if b is 0:
raise ArithmeticError
else:
print("a/b = ",a/b)
except ArithmeticError:
print("The value of b can't be 0")

Output:

Enter a:10
Enter b:0
The value of b can't be 0

User defined exceptions

Programmers may name their own exceptions by creating a new exception class. Exceptions need
to be derived from the Exception class, either directly or indirectly. Although not mandatory,
most of the exceptions are named as names that end in “Error” similar to naming of the standard
exceptions in python.
Steps in User defined Exception:
1. Create Custom Exception Class
class MyException(Exception):
def __init__(self, arg):
self.msg = arg
2. Raise the exception
raise MyException(‘message’)
3. Handle the custom exception thrown
try:
code
except MyException as me:
print( me )

For example:
Assertions:
Assertions in any programming language are the debugging tools which help in smooth flow of
code. Assertions are mainly assumptions that a programmer knows always wants to be true and
hence puts them in code so that failure of them doesn’t allow the code to execute further. This
has a much greater utility in testing and Quality assurance role in any development domain.
Different types of assertions are used depending upon the application.
An assertion is a sanity-check that you can turn on or turn off when you are done with your
testing of the program.

The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more
accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an
exception is raised.

Programmers often place assertions at the start of a function to check for valid input, and after
a function call to check for valid output.

In python assert keyword helps in achieving this task. This statement simply takes input a
boolean condition, which when returns true doesn’t return anything, but if it is computed to be
false, then it raises an AssertionError along with the optional message provided.

Syntax : assert condition, error_message(optional)


Parameters :
condition : The boolean condition returning true or false.
error_message : The optional argument to be printed in console in case of AssertionError
Returns :
Returns AssertionError, in case the condition evaluates to false along with the error message
which when provided.
Assertion errors can be handling in the same way as exceptioms usimg try except blocks
Web Scraping using Python

Web scraping is the process of gathering information from the Internet. Even copy-pasting the
lyrics of your favorite song is a form of web scraping! However, the words “web scraping”
usually refer to a process that involves automation. Web scraping is an automated method used
to extract large amounts of data from websites. The data on the websites are unstructured. Web
scraping helps collect these unstructured data and store it in a structured form. There are
different ways to scrape websites such as online Services, APIs or writing your own code.

Challenges of Web Scraping


The Web has grown organically out of many sources. It combines a ton of different
technologies, styles, and personalities, and it continues to grow to this day. In other words, the
Web is kind of a hot mess! This can lead to a few challenges you’ll see when you try web
scraping.

One challenge is variety. Every website is different. While you’ll encounter general structures
that tend to repeat themselves, each website is unique and will need its own personal treatment
if you want to extract the information that’s relevant to you.
Another challenge is durability. Websites constantly change. Say you’ve built a shiny new
web scraper that automatically cherry-picks precisely what you want from your resource of
interest. The first time you run your script, it works flawlessly. But when you run the same
script only a short while later, you run into a discouraging and lengthy stack of tracebacks!

Applications of Web Scraping

 Price Comparison: Services such as ParseHub use web scraping to collect data from
online shopping websites and use it to compare the prices of products.
 Email address gathering: Many companies that use email as a medium for marketing,
use web scraping to collect email ID and then send bulk emails.
 Social Media Scraping: Web scraping is used to collect data from Social Media
websites such as Twitter to find out what’s trending.
 Research and Development: Web scraping is used to collect a large set of data
(Statistics, General Information, Temperature, etc.) from websites, which are analyzed
and used to carry out Surveys or for R&D.
 Job listings: Details regarding job openings, interviews are collected from different
websites and then listed in one place so that it is easily accessible to the user.

Why is Python Good for Web Scraping?


Here is the list of features of Python which makes it more suitable for web scraping.

 Ease of Use: Python is simple to code. You do not have to add semi-colons “;” or curly-
braces “{}” anywhere. This makes it less messy and easy to use.
 Large Collection of Libraries: Python has a huge collection of libraries such
as Numpy, Matlplotlib, Pandas etc., which provides methods and services for various
purposes. Hence, it is suitable for web scraping and for further manipulation of
extracted data.
 Dynamically typed: In Python, you don’t have to define datatypes for variables, you
can directly use the variables wherever required. This saves time and makes your job
faster.
 Easily Understandable Syntax: Python syntax is easily understandable mainly
because reading a Python code is very similar to reading a statement in English. It is
expressive and easily readable, and the indentation used in Python also helps the user
to differentiate between different scope/blocks in the code.
 Small code, large task: Web scraping is used to save time. But what’s the use if you
spend more time writing the code? Well, you don’t have to. In Python, you can write
small codes to do large tasks. Hence, you save time even while writing the code.
 Community: What if you get stuck while writing the code? You don’t have to worry.
Python community has one of the biggest and most active communities, where you can
seek help from.

Process to Scrape Data from A Website


When you run the code for web scraping, a request is sent to the URL that you have mentioned.
As a response to the request, the server sends the data and allows you to read the HTML or
XML page. The code then, parses the HTML or XML page, finds the data and extracts it.

To extract data using web scraping with python, you need to follow these basic steps:

1. Find the URL that you want to scrape


2. Inspecting the Page
3. Find the data you want to extract
4. Write the code
5. Run the code and extract the data
6. Store the data in the required format

Now let us see how to extract data from the Flipkart website using Python.

Libraries used for Web Scraping


Python has various applications and there are different libraries for different purposes

Selenium: Selenium is a web testing library. It is used to automate browser activities.

BeautifulSoup: Beautiful Soup is a Python package for parsing HTML and XML documents.
It creates parse trees that is helpful to extract the data easily.

Pandas: Pandas is a library used for data manipulation and analysis. It is used to extract the
data and store it in the desired format.
The requests library:The first thing we’ll need to do to scrape a web page is to download the
page. We can download pages using the Python requests library. The requests library will make
a GET request to a web server, which will download the HTML contents of a given web page
for us. There are several different types of requests we can make using requests, of
which GET is just one.
After running our request, we get a Response object. This object has status_code property,
which indicates if the page was downloaded successfully: A status_code of 200 means that the
page downloaded successfully.

We can use the BeautifulSoup library to parse this document, and extract the text from the p
tag. We first have to import the library, and create an instance of the BeautifulSoup class to
parse our document:
from bs4 import BeautifulSoup

soup = BeautifulSoup(page.content, 'html.parser')

As all the tags are nested, we can move through the structure one level at a time. We can first
select all the elements at the top level of the page using the children property of soup. Note that
children returns a list generator, so we need to call the list function on it: list(soup.children)

Working with PDF

PyPDF2 is a pure-python PDF library capable of splitting, merging together, cropping,


and transforming the pages of PDF files. It can also add custom data, viewing options, and
passwords to PDF files. It can retrieve text and metadata from PDFs as well as merge entire
files together.

Installing PyPDF2 can be done with pip or conda if you happen to be using Anaconda instead
of regular Python.

Here’s how you would install PyPDF2 with pip:

$ pip install pypdf2


Extract Document Information From a PDF
Here you import PdfFileReader from the PyPDF2 package. The PdfFileReader is a
class with several methods for interacting with PDF files. In this example, you
call .getDocumentInfo(), which will return an instance of DocumentInformation. This contains
most of the information that you’re interested in. You also call .getNumPages() on the reader
object, which returns the number of pages in the document.
To extract contents from pdf:
To Copy pdf contents

Working with Excel Spreadsheets

• Opening an excel spreadsheet import openpyxl


wb = openpyxl.load_workbook('D:\PYTHON LAB\Iris_data_sample.xlsx') print(type(wb))

• Getting Sheet List and Name sheet_list = wb.sheetnames print("SHEET LIST = ",sheet_list)
sheet = wb['ISE_A’] print("SHEET = ",sheet)

• Name and Title, Active


print(type(sheet))
print(sheet.title) a
notherSheet = wb.active
print(anotherSheet)

Working with Excel Spreadsheets


Accessing Sheet value and labels
iv=sheet['B2']
print("B2 Value from XL file = ",iv.value,"ROW VAL = ",iv.row,"COL VAL = ",iv.column)
print("COORDINATE = ",iv.coordinate)
• Printing Multiple Values together print("Printing Multiple Values together") for
i in range(1, 8, 2):
print(i, sheet.cell(row=i, column=2).value)
• Creating Workbook
wb = openpyxl.load_workbook('example.xlsx') sheet = wb.active
sheet.title = 'Spam Spam Spam' wb.save('example_copy.xlsx')

Getting Rows And Columns From The Sheets


import openpyxl
wb = openpyxl.load_workbook('D:\PYTHON LAB\Iris_data_sample.xlsx')
sheet = wb.get_sheet_by_name('Iris_data') tuple(sheet['A1':'C3'])
for rowOfCellObjects in sheet['A1':'C3']: for cellObj in rowOfCellObjects:
print(cellObj.coordinate, cellObj.value) print('--- END OF ROW ---')

Read The Spreadsheet Data


import openpyxl, pprint print('Opening workbook...')
wb = openpyxl.load_workbook('D:\automate\tripDetails.xlsx')
sheet = wb.get_sheet_by_name('tripDetails')
countyData = {}
print('Reading rows...')
for row in range(2, sheet.max_row + 1): state = sheet['B' + str(row)].value county = sheet['C'
+ str(row)].value pop = sheet['D' + str(row)].value
Working with Excel Spreadsheets
>>> import openpyxlTING AND REMOVING SHEETS
>>> wb = openpyxl.Workbook()
>>> wb.sheetnames ['Sheet']
>>> wb.create_sheet() <Worksheet "Sheet1"> >>> wb.sheetnames ['Sheet', 'Sheet1']
>>> wb.create_sheet(index=0, title='First Sheet') <Worksheet "First Sheet">
>>> wb.sheetnames
['First Sheet', 'Sheet', 'Sheet1']
>>> wb.create_sheet(index=2, title='Middle Sheet') <Worksheet "Middle Sheet">
>>> wb.get_sheet_names()
['First Sheet', 'Sheet', 'Middle Sheet', 'Sheet1']
Writing Values To Cells
>>> import openpyxl
>>> wb = openpyxl.Workbook()
>>> sheet = wb['Sheet‘]
>>> sheet['A1'] = 'Hello world!'
>>> sheet['A1'].value
'Hello world!'
Working with Word Documents - READING WORD • pip install python-docx
DOCUMENTS
>>> import docx
>>> doc = docx.Document('demo.docx‘)
>>> len(doc.paragraphs)
7
>>> doc.paragraphs[0].text 'Document Title‘
>>> doc.paragraphs[1].text
'A plain paragraph with some bold and some italic‘
>>> len(doc.paragraphs[1].runs)
4
>>> doc.paragraphs[1].runs[0].text 'A plain paragraph with some ‘ >>>
doc.paragraphs[1].runs[1].text 'bold‘
>>> doc.paragraphs[1].runs[2].text
' and some ‘

Getting The Full Text From A Import Docx .Docx File


Filename=input(“Enter document name”)
doc = docx.Document(filename) fullText = []
for para in doc.paragraphs: fullText.append(para.text)
print('\n'.join(fullText))
Handling CSV File
Reading a csv file using Reader object import csv
exampleFile = open('example.csv') exampleReader = csv.reader(exampleFile) for row in
exampleReader:
print('Row #' + str(exampleReader.line_num) + ' ' + str(row))

Writing to a csv file using Writer object import csv


outputFile = open('output.csv', 'w', newline='') outputWriter = csv.writer(outputFile)
outputWriter.writerow(['spam', 'eggs', 'bacon', 'ham'])
outputWriter.writerow(['Hello, world!', 'eggs', 'bacon', 'ham']) outputWriter.writerow([1, 2,
3.141592, 4])
outputFile.close()

You might also like