100% found this document useful (1 vote)
12 views483 pages

Python Notes PDF

The document provides an overview of Python, highlighting its features, history, and comparisons with other programming languages like C and Java. It discusses Python's popularity due to its productivity, readability, and ease of learning, as well as the differences between interactive and script modes of coding. Additionally, it covers fundamental concepts such as memory allocation, object-oriented programming, and the distinctions between compilers and interpreters.

Uploaded by

vajibameensd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
12 views483 pages

Python Notes PDF

The document provides an overview of Python, highlighting its features, history, and comparisons with other programming languages like C and Java. It discusses Python's popularity due to its productivity, readability, and ease of learning, as well as the differences between interactive and script modes of coding. Additionally, it covers fundamental concepts such as memory allocation, object-oriented programming, and the distinctions between compilers and interpreters.

Uploaded by

vajibameensd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Today’s Agenda

 What is python?
 Why python is so famous?
 History of python
 Comparison with C, JAVA
 ALL, MLL, HLL
 Compiler vs Interpreter

What is python??
Python is an interpreted, high-level, general-
purpose programming language. Created
by Guido van Rossum and first released in
1991, Python's design philosophy emphasizes code readability with
its notable use of significant whitespace. Its language
constructs and object-oriented approach aim to help programmers
write clear, logical code for small and large-scale projects.

It supports multiple programming paradigms,


including structured (particularly, procedural), object-oriented,
and functional programming.

1 Python Fundamentals| Rooman Technologies


It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

Why python is so famous and most


recognized language?
First and foremost reason why Python is
much popular because it is highly
productive as compared to other
programming languages like C++ and Java. It
is much more concise and expressive
language and requires less time, effort, and
lines of code to perform the same
operations.

The Python features like one-liners and dynamic type system allow
developers to write very fewer lines of code for tasks that require
more lines of code in other languages. This makes Python very easy-
to-learn programming language even for beginners and newbies. For
instance, Python programs are slower than Java, but they also take
very less time to develop, as Python codes are 3 to 5 times shorter
than Java codes.

Python is also very famous for its simple programming syntax, code
readability and English-like commands that make coding in Python lot
easier and efficient.

2 Python Fundamentals| Rooman Technologies


History of Python
Python was conceived in the late 1980s by Guido van
Rossum at Centrum Wiskunde & Informatica (CWI) in
the Netherlands as a successor to the ABC language (itself inspired
by SETL), capable of exception
handling and interfacing with
the Amoeba operating system.

Python's name is derived from the


British comedy group Monty Python,
whom Python creator Guido van Rossum
enjoyed while developing the language.
Monty Python references appear
frequently in Python code and
culture; for example, the metasyntactic
variables often used in Python literature are spam and eggs instead
of the traditional foo and bar. The official Python documentation
also contains various references to Monty Python routines.

Comparison with C and JAVA


Let us consider an example of swapping of two numbers in all top
three programming languages.

3 Python Fundamentals| Rooman Technologies


Case 1 – C language

Case 2 – Java

4 Python Fundamentals| Rooman Technologies


Case 3 – Python

Output-

ALL, MLL, HLL


Before you learn any programming language, it is important
for one to understand some of the basics about computer
and what are the languages that a computer can
understand.

Let’s have a view on it.

A computer is a collection of hardware components. Let us


consider here few hardware components such as:

5 Python Fundamentals| Rooman Technologies


microprocessor RAM

Hard disk GPU

Out of these and many other hardware components, the


most important or the heart of the computer is the
Microprocessor or CPU.

Microprocessor or CPU: A microprocessor is an electronic


component that is used by a computer to do its work.
It is a central processing unit on a single integrated
circuit chip containing millions of very small components
including transistors, resistors, and diodes that work
together. They are created using a technology called as
Semiconductor technology.
6 Python Fundamentals| Rooman Technologies
Semiconductor Technology??

Any device which is made up of transistors is referred to


as working in Semiconductor Technology.

A transistor is a device that regulates current or voltage


flow and acts as a switch or gate for electronic signals. The
transistors have three terminals emitter, base and
collector.

There are two types of transistors:

1) NPN transistor.
2) PNP transistor.

Transistor

NPN PNP

Transistors can only store voltages. There are


two levels of voltages:

Low Voltage referred to as → 0V

High Voltage referred to as→ 5V

If we see the same in Software engineer’s view, he/she looks the


two levels as:

Low Voltage referred to as → 0

High Voltage referred to as→ 1

Therefore, in the perspective of a software engineer a


Microprocessor or CPU can understand combinations of 0 and 1.

7 Python Fundamentals| Rooman Technologies


Programming Languages

Language is the main medium for communicating between


the computer systems. A program is a collection of
instructions that can be executed by a computer to
perform a specific task.

There were several programming languages used to communicate


with the Computer.
Case-1:

The world’s first computer was


invented in the year 1940’s.
During that time the task of a
programmer was not simple.
For example, if they wanted
microprocessor to perform any
operation then they had to use
combinations of 0’s and 1’s.
During this time all the programs
where written in the language called
as Machine Level Language. It is one of the low-level
programming languages.

Codes written in 1940’s as


To perform addition of two numbers: 0110110
To perform subtraction of two numbers: 1110111
To perform multiplication of two 1010101
numbers:
To perform division of two numbers: 0100100
MLL microprocessor

011011
111011 Output
101010

8 Python Fundamentals| Rooman Technologies


The machine level code was taken as input and given to the
microprocessor as the machine understands the binary value
code and it gives the output.

The main advantage of using Machine language is that there is


no need of a translator to translate the code, as the
Computer directly can understand.

The disadvantage was, it was difficult for a programmer to


write the code or remember the code in this type of
language.

Case-2:

The problem with Machine level code approach was decided to be


changed in the year 1950’s.

They thought that instead of writing a long sequence of 0’s


and 1’s a single instruction can be given.
For example we use,
Codes in 1950’s written as

To perform addition of two


numbers: ADD
To perform subtraction of two
numbers: SUB
To perform multiplication of
two numbers: MUL
To perform division of two
numbers: DIV

This approach of writing code is what called as Assembly


Level Language. Instead of using numbers like in Machine
languages here we use words or names in English forms.

9 Python Fundamentals| Rooman Technologies


ALL Microprocessor

ADD
SUB
MUL Assembler Output
DIV

An Assembler is software which takes Assembly Level Language


(ALL) programs as input and converts it into Machine Level
Language (MLL) program.

Case-3:

People always want the things to be simple and easier so, in


1960’s they came up with next type of language called High
Level Programming Language.

High Level Languages are written in a form that is close to


our human language, enabling the programmer to just focus on
the problem being solved.

For example we use,


Codes in 1960’s written as

To perform addition of two


numbers: +
To perform subtraction of
two numbers: -
To perform multiplication of
two numbers: *
To perform division of two
numbers: /

10 Python Fundamentals| Rooman Technologies


HLL Microprocessor

- Compiler Output
*

A compiler is software which takes High Level Language (HLL)


programs as input and converts it into Machine Level Language
(MLL) program.

Compiler vs Interpreter
Compilation

Interpretation

11 Python Fundamentals| Rooman Technologies


Interpreters and compilers are very similar in structure. The main
difference is that compilation is the process of converting a HLL
program into MLL using software called as compiler. In compilation
the entire HLL program is converted to MLL in one shot by the
compiler and hence all the MLL instructions are readily available for
CPU.

Interpretation is the process of converting HLL program into MLL


using software called as interpreter. In interpretation, at any given
point of time only a single line of HLL program is converted to MLL
which is then executed by CPU. Post execution the next line is
converted and executed. This process repeat itself till all lines in
the program are converted and executed. Because of this, CPU does
not have all lines of program readily available for execution.

An interpreter will typically generate an efficient Machine Level


representation and immediately evaluate it.

12 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Programming in Python
 Interactive mode & Script mode
 Difference b/w interactive & script mode
 Memory allocation
 Object Oriented Programming
 Principles of OOP

Programming in Python
After knowing what is Python and different features of it and the
history behind. Let us now get to know if python is an interpreted
programming language or if it is compiled programming language

This is how a python file executes. Each instruction is given to the


interpreter which converts it into machine level and feeds to CPU to
get the output. And again to get the next instruction we have to go
back to the source file and continue the process. So no doubt python
is an interpreted language.

1 Python Fundamentals| Rooman Technologies


Interactive mode & Script mode
Let us now look into different modes of writing a code in python:

Interactive mode

The interactive mode involves running your codes directly on the


Python shell which can be accessed from the command line/terminal
of the operating system. Single line fed to the interpreter is
executed at that moment of time, and waits for next line to be
entered. Each line is given to the interpreter which internally
converts HLL to MLL and the gives the respective output.

>>>print(“Python”)
Python Interpreter
Python

>>>a = 10
// similarly all other lines, one by one
>>>b = 20 are given to interpreter.

>>>c = a+b

>>>print( c ) // lines starting with >>> Represents


the code or the input to the
30 interpreter. Lines without >>> are the
outputs

And whenever a variable with value is fed to the interpreter a


container gets created internally with the value in it. As shown
below:

c 30

b 20

a 10

And to exit this interactive mode you should give quit( ) as input.

2 Python Fundamentals| Rooman Technologies


Pros and cons of Interactive Mode

Pros:

 It is great for single line or smaller codes.


 Interactive mode is a good way to
play around and try variations on
syntax.

Cons:

 Once you come out of interactive


mode, you cannot revisit the
previous code.
 It is harder to edit longer programs or even existing program.
 Codes cannot be saved in interactive mode.

Script Mode

To overcome the drawbacks of interactive mode we have the second


mode of writing a code called as Script mode. Let us know different
platforms of typing a python code in script mode.

 Notepad //basic text editor


 Microsoft Word //basic text editor
 Different IDE (IDLE, Spider, PyCharm, Jupyter Notebook)

Here let us get to know how to run a python script in command line.

Script mode in command line

We know that if we type python and press enter we are into


interactive mode like shown below:

3 Python Fundamentals| Rooman Technologies


Let us type the same addition code in python script and see how it
works.

Let us see how to run a python script in command line.

Syntax:

Note: Before running this command, make sure you are in the same
directory as of the python script you want to run.

Output:

In the script mode, you have to create a file, give it a name with
a .py the extension then run your code. The file which contains
python code and has to be executed is called as python script. The

4 Python Fundamentals| Rooman Technologies


script mode is recommended when you need to create large
applications.

As we have the python script in HLL, conversion must happen as


below:

Python Script

Script mode + Interactive mode

Let us see how to enter interactive mode after running the python
script

Syntax:

Command line execution:

5 Python Fundamentals| Rooman Technologies


Difference b/w interactive & script
mode in python
Interactive mode Script Mode
A way of using the python A way of using the python
interpreter by typing commands interpreter to read & execute
& expressions at any prompt. statements in a script
Can’t save and edit the code. Can save and edit the code
If we want to experiment with If we are clear about the code,
the code, we can use interactive use script mode.
mode.
We cannot save the statements We can save the statements for
for further use and we have to further use and no need to
retype. retype all the statements to
return them.

Memory allocation
On one end we have the instructions and on the other end
microprocessor. To give these instructions as the input to
microprocessor we need to store it so that the microprocessor has
direct access to the instructions. To store these instructions we
have something called as RAM (Random Access Memory). RAM is a
temporary memory directly connected to the microprocessor, and
the main purpose of RAM is to store the instructions before it is
given to microprocessor. And then line by line instructions gets
converted to MLL and then given to microprocessor.

6 Python Fundamentals| Rooman Technologies


RAM is the most important memory in the computer where all
execution of the program happens on the RAM. In fact if the
instructions are on the RAM then only
execution can happen if not execution
cannot be performed.

RAM is a semiconductor technology device


just like the microprocessor, which means
it is made of transistors. So therefore
RAM always needs constant supply of
electricity for it to work. Once the supply
is gone all the instructions and operations happening inside the RAM
vanishes. That is the reason RAM is said to be volatile in nature.

Hard Disk RAM is the main memory, as it is volatile in


nature we have secondary memory which is
called as Hard disk which is a magnetic
device. To use the instructions again and again
you need to make a copy of those instructions
and store it in hard disk. Those instructions
while are store in hard disk are called as file.

7 Python Fundamentals| Rooman Technologies


The process of taking a copy from RAM and storing in hard disk is
called as saving. And loading is a task where we are taking file and
transferring it to RAM.

All computers have these two memory devices namely hard disk and
RAM. Where hard disk is used for permanent storage and RAM is
used for temporary storage.

Note: Microprocessor is connected only to RAM. And RAM is


connected to the hard disk.

Object Oriented Programming


We have two different types of programming languages, which are
structural programming language and the second is object oriented
programming (OOP) language. Here we will be focusing on OOP
language.

Before going ahead with the object orientation, let us get to know
what is orientation?

Orientation  Perspective  Way of looking at something

Let us take an example of glass of water and try to understand in


better way:

8 Python Fundamentals| Rooman Technologies


Different
perspectives

A chemist will see the glass of water as liquid + gas, an optimistic


person will look at it as half full glass, a pessimistic person will see it
as half empty glass, a realist will see it as glass of water, but a
developer will always view it as an object.

Object Orientation is the way of looking at this world as a collection


of objects. In this world no object is completely useless. All objects
are in constant interaction with each other. No object exists in
isolation.

9 Python Fundamentals| Rooman Technologies


Principles of OOP
 View everything around you as objects.
 Every object belongs to a type. Where type does not exist but
the objects of the type exist in reality.
 Every object has two parts:
1. State of an object /properties
2. Behaviour of an object/actions
 To handle the properties of the states of an object we have a
concept called as data types
 Similarly to handle behaviour of an object we have a concept
called as functions

Let’s see the same with example of bike

State/properties: Behaviours:

 Brand  start( )
 Price  change_gear( )
 Cylinder capacity (cc)  accelerate( )
 Colour  brake( )

10 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Data types
 Memory Mapping
 Coding - data types

Data types
Before going ahead with what is data type and why do we need it?
We should first know how a data is stored in a system.

In every electronic system we have RAM which stores the data


temporarily. All the data that we enter is in high level but it is
always stored in low level inside the system so that the
system/machine can understand.

So RAM consists of several bytes, each byte consists of 8 bits,


each bit has two transistors which can store high and low value (1’s
and 0’s).

RAM Transistors

1 Python Fundamentals| Rooman Technologies


Now we know that RAM can only take inputs in 0’s and 1’s. Apparently
the data in real world is not combination of 0’s and 1’s. We have
basic 4 types of real world data which are integers, real numbers,
characters, yes/no types of data.

The basic data types in python which represents integers, real


world, characters, yes/no type data are int, float, str, bool
respectively.

These data types help to convert high level form of data to


combination of 0’s and 1’s that is binary format.

Examples:

Integers – Age of a person, Number of people, House number,


Population of a country, number of galaxies or planets all represent
whole numbers. Whole numbers belong to integer type data.

2 Python Fundamentals| Rooman Technologies


Real world data – Height &
weight of a person, GDP of
country, your CGPA/SGPA,
Literacy rate are all examples
of real world data where it may
or may not be a whole number.
These real world data belong to
float data type.

Character – We are surrounded


by several things while have
names, there isn’t a single thing
in the world that don’t have a name for it. And for communication
words play major role. All these are characters which belong to
string data type.

Yes/no – We ask several yes or no, true or false questions to one


another like married or not? Graduated or not? Employed or not?
Literate or not? All these belong to boolean data type.

There are several other data types in python which we shall


explore one by one in upcoming sessions.

Memory Mapping
All the operations carried out by computer or any electronic device
happens on the RAM. In simple words we can say that RAM is shared
by different applications. So when we are trying to execute the
python code, it won’t occupy all the space in RAM. It’ll use only a
certain region on the RAM. Within this region there are few
divisions or segmentations are present. This region contains
something called as stack and private heap.

3 Python Fundamentals| Rooman Technologies


In this course all the programs will be explained with respect to
these regions.

Objects are allocated on private heap. References are allocated on


stack. And address of the object created on private heap will be
present inside the reference, which means reference is pointing to
the object.

Note: As python is dynamically typed


programming language, we need not declare
the type of object. Based on the value given
the language itself decides the type of an
object. And in programming languages class
means type.

Coding - data types


1) Integer data type - int

4 Python Fundamentals| Rooman Technologies


2) Real world data type - float

3) Character data type - str

In python language we don’t have separate data type for character


and string. Here string data type is inclusive of single character
type data, collection of characters, and also multi line strings. Which
in depth we shall study while learning about strings.

5 Python Fundamentals| Rooman Technologies


4) Complex numbers –

We have seen the real numbers and integers but there are also
imaginary numbers in this world. These imaginary numbers belong to
complex numbers.

If you want to know where these


imaginary numbers are used in real
world then here are few examples, in
mathematics I’m sure everyone is
aware of quadratic equations and
certainly in schooling days we have
come across using complex numbers
there. And we also use it in electricity,
especially in alternating current (AC). Where? How? Why? If these
are questions in your mind then you can personally read about it.

6 Python Fundamentals| Rooman Technologies


5) Boolean – bool

Boolean type of data will have two states true/false. Based on the
condition that we want to check, the return value of expression
changes. In python Boolean type of data belongs to bool.

7 Python Fundamentals| Rooman Technologies


Today’s Agenda
 List
 Tuple
 Set
 Dictionary

Lists
A list object is an ordered collection of one or more data items, not
necessarily of the same type, put in square brackets.

1 Python Fundamentals| Rooman Technologies


 We can access single elements from list by using positive indices
or negative.

 Lists are mutable, which means we can append elements and remove
whenever needed. By using append() and remove() respectively.

2 Python Fundamentals| Rooman Technologies


Tuple
A Tuple object is an ordered collection of one or more data items, not
necessarily of the same type, put in parentheses.

 Like lists in tuple also we can access single elements with both positive and
negative indices.

 Tuple are immutable, which means we cannot append or remove


any elements from a tuple.

3 Python Fundamentals| Rooman Technologies


Set
 In set we cannot access single elements because internally set does
not store the data in the order we provide it. That is the reason it is
called unordered collection of data. And as it is unordered data,
certainly it doesn’t have indices.

 Set is mutable, which means we can add or remove the elements


using add() and remove() respectively. But remember that the
order in which it adds an element is not as we enter it.

4 Python Fundamentals| Rooman Technologies


 No duplication, which means the data inside set are unique.
Although duplicated entries will not give an error, the entries will
not get stored and be seen on screen.

Dictionary
A dictionary is a collection which is unordered, changeable and
indexed. In Python dictionaries are written with curly brackets, and
they have keys and values. Each key will be mapped to a value.

5 Python Fundamentals| Rooman Technologies


Dictionaries are mutable – which means we can add and remove
keys. A key can be removed by using pop( ). Many other operations
can be done as well, which we shall learn in future sessions.

6 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Typecasting
 Mutable and Immutable datatypes
 Overview of datatypes

Typecasting
The process of converting one type of data to another type in
programming language is called as typecasting. In python typecasting
is done using the functions already present in python these functions
are called as built-in functions.

int( ) str( ) list( ) set( ) hex( ) chr( )

float( ) complex( ) tuple( ) dict( ) oct( ) ord( )

From the above mentioned built-in functions let’s focus on the basic
datatypes for now, rest of them we shall see in later on sessions.

 First conversion:

Integer Float
float( )

1 Python fundamentals| Rooman Technologies


Integer value must be converted to a
floating point value, if this must
happen then we have to use a function
which converts integer type data to
float type data. Which is none other
than float( ).

 Second conversion:

Float Integer
int( )

Let’s reverse the order now by converting floating type data to


integer type data by using int( ).

2 Python fundamentals| Rooman Technologies


Note: We observe that 0.9 is lost during the
conversion, because integer type data will not store
decimal point values. Therefore we have to be very
careful during type casting. In some cases 0.9 is a
very huge value whereas in some other cases it is
completely fine.

 Third conversion:

Float Complex
complex( )

Let us convert a floating number to a complex number which


contains a real number and an imaginary number.

We can also give an imaginary number as shown below

 Fourth conversion:

Integer String
str( )

3 Python fundamentals| Rooman Technologies


We have many other conversions which we will perform as and
when needed. But let us see the last conversion which is most
commonly used, integer type data to string type.

String type data can certainly store numbers as well. We can


know the type by printing it.

Mutable & Immutable datatypes


As we already know that mutable means changeable and immutable
means non changeable. The datatypes whose values cannot be
changed are called immutable datatypes and likewise the
datatypes whose values can be changed are called mutable
datatypes.

4 Python fundamentals| Rooman Technologies


Immutable Mutable

 Int,  List
 Float,  Dict
 Str,  Set
 Bool,
 Tuple

 Immutable datatypes – ( Integer )


Let us try assigning a value to variable a and try to change
values.
In below diagram we can see that a value gets changed but
internally two different objects are created with different
address. So the variable a is now pointing to the new value.

5 Python fundamentals| Rooman Technologies


Let us try to verify the above statement by printing the address of
both the objects.

We can see from the above diagram that both objects have
different references. Which implies, when we try to modify the
values assigned to a variable, new object gets created instead of
modifying the existing value.

It is the same feature of immutability of certain datatypes which


makes python memory efficient in the background. Which simply
means that, when two variables are assigned the same value, two
objects does not get created on private heap instead both the
variables will be pointing to the same object. Because by now we
know that some datatypes are immutable and their values cannot be
changed. This is demonstrated in the below diagram,

6 Python fundamentals| Rooman Technologies


Above we have shown with respect to integer type data, whereas the
same works for float, bool, string and tuple also because all these
belong to immutable type data. And certainly we have also checked
for equality of two variables by is operator.

 Mutable datatype – ( list )

Let us create a list having some set of values and try to append new
values. If you have gone through previous sessions you know that
certainly that is possible in lists. Let’s see it either ways

7 Python fundamentals| Rooman Technologies


Let us now try to create another list with same values and see if
memory is efficient in this case as well

We can see that when new list lst1 was equated to lst it resulted as
false (Equality basically checks the references). This is because lists
are mutable. So if any changes are made to one list the other list
might get affected too. That’s the reason no two lists type data will
be pointing to a same lists object.

Overview of datatypes

8 Python fundamentals| Rooman Technologies


Today’s Agenda
▪ Introduction to Functions
▪ Why Functions?
▪ Different types of functions
▪ User Defined functions in detail

Introduction to Functions
Definition: A Function is a set of statements that takes inputs,
performs some specific task and produces output.
How do i declare a function in python?
The four steps to defining a function in Python are the following:

Use the keyword def to declare the function and follow this up
with the function name.

Add parameters to the function: they should be within the
parentheses of the function. End your line with a colon.

Add statements that the functions should execute.

End your function with a return statement if the function should
output something.

1 Python fundamentals| Rooman Technologies


Why Functions?
After getting to know how a python function looks like, let us now
understand why functions by considering few examples.

Let us consider two operations of adding two numbers and dividing


two numbers as shown below.

a = 10
b = 20
c = a+b
print(c)

d = 100
e = 10
f=d/e
print(f)

Above lines of codes will perform addition and division of two


numbers, but if in case you want to perform addition of two numbers
again, the only option is to copy the same lines of code and use them
again as shown below:
a = 10
b = 20
c = a+b
print(c)

d = 100
e = 10
f=d/e
print(f)

2 Python fundamentals| Rooman Technologies


a = 10
b = 20
c = a+b
print(c)

But as a programmer this is not the right


approach which one should follow, the
efficient way of doing this is by following dry approach which stands
for DO-NOT-REPEAT-YOURSELF.
So, the solution is including the lines of code inside a block and give
it a suitable name. That way you can use the same block of code
multiple times by making use of name given to it.
Using the above approach, we can achieve:
Reusability and Modularity.
Reusability refers to resuing the same block of codes multiple
times.
Modularity refers to dividing the entire code into different logical
blocks of code.
From object orientation perspective, the behaviour of an object is
taken care by functions in python.

OBJECT
a = 10
b = 20
c = a+b
print(c) [Link]
Functions Behaviour
[Link]
d = 100
e = 10
f=d/e
print(f)

3 Python fundamentals| Rooman Technologies


Types of Functions in python
Python consists of four types of functions:

1. User Defined Functions


2. Built-in-functions.
3. Lambda functions.
4. Recursive Functions.

User Defined Functions: These functions are defined or created by


user.
Built-in-functions: These functions are already defined in
Python libraries and we can call them directly.
Lambda functions: A lambda function can take any number of
arguments, but can only have one expression.
Recursive Functions: A Python function which is defined to call itself
during its execution is known as python recursive function.

User defined Functions


A user defined function in python can be declared in four different
ways as shown below:
Without With Without With
Input Input Input Input

Without Without With With


Return Input Return Input Return Input Return Input

4 Python fundamentals| Rooman Technologies


[Link] that takes no input and does not return any output .
Below is the code which consists of a function mul() which falls in the first
category of user defined functions which is a function that takes no input and
returns no output.
In the code given below there is not only mul(), it also has main() inside which
we are calling mul().
All such statements which are not present inside any functions are automatically
placed within the main() function and is automatically called in python. The
moment a method gets called its stack frame gets created.
The first function that gets called in a python program is always the main().
Whenever a main function gets called its stack frame gets created on stack
which simply shows main() has begun execution.
Inside main(), we are calling mul() which results in the creation of stack frame of
mul() on stack.
Whatever is present at the top of stack is always the one which is currently
executing and hence mul() starts executing inside which we are creating three
objects a,b,c. The references are created inside the stack frame of mul() and
objects are created on private heap. Once mul() finishes execution, its stack
frame gets deleted and then the control is given back to main(). After the
execution of main(), its stack frame also gets deallocated memory on stack. If all
the stack frames are destroyed, all the references also gets deleted. Now the
objects on heap do not have any reference pointing to them, once pyhton
encounters there no references pointing to objects, it treats those objects as
garbage objects and deletes them. To perform deletion of garbage objects,
python provides a software called as garbage collector which deallocates
memory for all the garbage objects.

5 Python fundamentals| Rooman Technologies


[Link] that takes input and does not return any output .
Below is the code which consists of a function mul() which falls in the second
category of user defined functions which is a function that takes input and
returns no output.
While calling a method that requires arguments, one must pass number of
arguments accepted by the methods as shown below where we are passing
10,20 while calling mul(10,20). 10 and 20 are now stored inside x and y.

3. Function that takes no input but returns output .


Below is the code which consists of a
function mul() which falls in the third
category of user defined functions which
is a function that takes no input and
returns output.
One must make use of return statement
inside the function to return a value.
Once return statement gets executed,
control goes to the statement which had
called that function. Now it is the choice
of the caller to collect the value returned
by function or not. In the below code the
returned value is collected inside res
which is created inside the stack frame of
main() as shown in figure below.
Note: Pyhton functions can return muliple values.

6 Python fundamentals| Rooman Technologies


[Link] that takes input and returns output .
Below is the code which consists of a function mul() which falls in the fourth
category of user defined functions which is a function that takes two inputs x,y
and returns output.
Based on situations, we must make use of different functions.
For example, you need your bank account details and to do so you must give
your details as input upon which your details will be returned to you.
This way, based on different scenarios, different types of functions should be
used to achieve the required task.

7 Python fundamentals| Rooman Technologies


Today’s Agenda
 Types of arguments
 Positional arguments
 Default arguments
 Keyword arguments
 Variable length arguments
 Variable keyword length arguments

Types of arguments
The input passed through a function is technically called as
argument. Let us know better

Parameters

Arguments

Parameters collect the inputs, which is passed to the function when


it is called.

1 Python fundamentals | Rooman Technologies


We have different types of arguments:

1. Positional arguments
2. Default arguments (Optional arguments)
3. Keyword arguments
4. Variable length arguments (Arbitrary arguments)
5. Variable keyword length arguments (Arbitrary keyword
arguments)

Positional Arguments

In the above example we are performing power operation. Here the


arguments are 2,5 and parameters are a,b where a gets assigned as
2 and b gets assigned as 5 based on the positions. To verify this let’s
try to interchange the positions and check whether the value of c
changes or remains same.

2 Python fundamentals | Rooman Technologies


As we can see, a gets assigned as 5 and b gets assigned as 2. Which
proves the above statement, if passed in the above format, position
definitely matters.

If we miss a single argument then error appears, let us see what the
error is

Error clearly tells us that we are missing an argument b. So now let


us see how to get away with this.

Default Arguments

In the above example we have only single argument, assuming b will


take the default value assigned to it as 0. Giving a value while
declaring the parameter is referred to as default value.
3 Python fundamentals | Rooman Technologies
Certainly we can also give two arguments

Output:

Let us see another example

Here we have third argument. Let us see if we get the output as


expected, that is 5*3*2 = 30

Output:

As the message reflected, non-default argument cannot follow


default argument. But certainly after positional arguments we can
have as many default arguments as possible.

4 Python fundamentals | Rooman Technologies


Keyword arguments
In positional arguments we noticed that if order changes the output
also changes. We can overcome this by using keyword arguments, let
us see how

We can see that, if we mention the keywords while passing


arguments the output does not depend on the order or the position
of the arguments. This is the advantage of using keyword arguments.

Variable length argument


Passing any number of arguments to a function is called as variable
length argument. Let us know better by an example

5 Python fundamentals | Rooman Technologies


In the above example we are trying to pass different number of
arguments but only first argument is what the function is taking, so
certainly some changes in function declaration is needed, let us see
what is the change and how that change will accept multiple
arguments

We can now see that by attaching a star or asterisk in front of the


parameter, the function is now ready to take different number of
arguments. This is because toppings is now considered as tuple. Let
us verify that by printing the type of toppings

6 Python fundamentals | Rooman Technologies


Note: * in front of the parameter makes it a tuple. But while calling
for it we should just enter name which does not contain *.

Let us see another case

Output:

In the above example we are trying to pass another argument. But


crust is a positional argument/non-default argument. So if we use
keyword and assign the value, the output is as expected. But what if
we don’t use the keyword?? Let’s see

Output:

Here we see that cheese and thin both are


considered as toppings. So if we are passing any arguments before
or after the variable length argument it is mandatory to use
keyword arguments.

7 Python fundamentals | Rooman Technologies


Variable keyword length arguments
In the previous example we saw how to pass different number of
arguments, but all of them were toppings. What if each argument we
pass represents different data. Let us see how to resolve this

Output:

We certainly got the output, but we still can’t


recognise what is 28, 60.5, M. To resolve this we
must give a key to each value entered as shown
below

Output:

The error states that it doesn’t recognise name and similarly age,
avg, gender. To resolve this we must make another change, let us see
what that is, and how it resolves the issue

8 Python fundamentals | Rooman Technologies


Output:

All we did was add another * to the parameter.


And we can see in output that the keys and values are enclosed with
{ } which states ** in front of a parameter makes it a dictionary.
Which can store different arguments along with keywords
associated with it.

Here also we have the same rule as seen earlier that if we are
passing any arguments before or after the variable keyword length
argument it is mandatory to use keyword arguments.

9 Python fundamentals | Rooman Technologies


Today’s Agenda
 File, script and module
 Built-in modules
 Documentation string

File, script & module


A file from the hard disk when executed on command line then such
a program or a file is called as a script.

If we have a single file with numerous set of functions then it is


difficult to work with such file. The better way is to group similar
set of functions and make a separate file of it and name accordingly.
These files are called as modules.

Whenever we are in need of certain functions, instead of defining a


function again we can just use the function present in particular
module by bringing to current file. This process is called as
importing and is done by using
the keyword import.

Importing functions from


modules to a file reduces the
length of code and certainly
reduces the complexity.

1 Python fundamentals| Rooman Technologies


Let us now consider an example where we have certain functions in a
module called as mymodule and want to use functions present in it, in
the python script called as [Link] and see how this works.

Instead of calling a module by its name every single time we want to


use a function from that module, we can rename it and this is called
as aliasing. This can be done by using keyword called as as. Let us see
how to do this

2 Python fundamentals| Rooman Technologies


There is definitely a simpler way for this, which is by using a
keyword called as from. Let us see how it makes things easy

In above example * means import all the functions present in


mymodule to the present file. And we can use the functions just by
calling by its name.

If the module contains huge number of functions and we want to use


only a couple of functions from it then instead of using * and
importing all functions we can just mentions the function which we
want to use and import them selectively as shown below

3 Python fundamentals| Rooman Technologies


If you want to import more than one function from the module the
all you have to do is

Note: Knowing that a function is present in the module but calling it


without importing, will definitely throw an error saying <function
name> is not defined.

And also do not mix these different ways of importing functions, it


will give an error. Better follow just one method.

4 Python fundamentals| Rooman Technologies


Built-in modules
Whatever we have seen so far are user defined modules, where we
have created a module with certain functions in it. But there are
some modules which contain numerous functions in it and are already
present in python these are called as built-in modules.

Let us explore one such called as math

help() is a function which will give you complete description about


each function present in that module. Above are only few functions
present in math module.

And if you just want to know the different functions present in the
module without any description the just use dir() function as shown
below

5 Python fundamentals| Rooman Technologies


By looking at the square brackets we can say that it returns the list
of functions name present in a particular module.

To get the help for a specific function, let us see what to do

Let us check if it works as expected

6 Python fundamentals| Rooman Technologies


Let us check some more functions like ceil(), floor()

For example:

Now let’s see what floor() does

For example:

7 Python fundamentals| Rooman Technologies


Documentation string
Earlier we saw how to create a module, but we have seen that every
module has a description so that it’s easy for a programmer to know
what does a function inside particular module do. The description
provided is called as documentation. The definition of that function
is called documentation string which is enclosed within triple quotes.

Let us understand by an example

We can certainly see the documentation of all the functions in


power_of module.

To see description of selected functions, as said earlier we have to


use help(<module_name>.<function_name>) as shown below

8 Python fundamentals| Rooman Technologies


There is also a second way to access the documentation string. Every
function has a variable, the name of this variable is __doc__(double
underscore doc double underscore)/dunder doc. Let us see how to
access it

9 Python fundamentals| Rooman Technologies


Today’s Agenda
 Return keyword
 Main function
 Taking user inputs

Return keyword
In the other programming languages like Java, C we have seen that

A function can take numerous parameters but return returns only


single value. But in python not only does a function accept multiple
values as input but also returns multiple values.

Output:

1 Python Fundamentals| Rooman Technologies


By looking at the output format we can see that the values are
stored in tuple. Which means, when a function returns multiple
values it is stored inside tuple.

So now we know how to print. Let us see how to store those values

Output:

Now let us see how to store in multiple variables

Output:

In the above output, the tuple is now unpacked and 10 is given to


res1, 20 to res2 and 30 to res3.

2 Python Fundamentals| Rooman Technologies


Note: Number of variables should be equal to number of values
returned by the tuple.

Main function – main( )


Let us create [Link] which consists of functions power_of and
get_remainder and then import the module in [Link]

[Link]

[Link]

Output:

We can see in the above output, call to the functions from mymodule
got automatically executed which is not what we wanted.

3 Python Fundamentals| Rooman Technologies


Whenever we import a module, we just want to import the functions
in the module and don’t want the function calls to get executed. So
let us see how to do that

 Every python file has a variable name called as dunder name.


The content inside this variable is based on whether the
python file is executed in script mode or imported in other file.
 If it is executed in script mode, dunder name contains
__main__
 If it is imported in other file, dunder name will be same as the
file name.
__name__ or
dunder name

Script mode Imported in


other python file

__main__ filename

 Now we know that, the function call commands must execute


only when the python file is executed in script mode. So let us
make the required changes in mymodule

4 Python Fundamentals| Rooman Technologies


Now if we execute [Link] we expect function calls to not get
executed unless explicitly called for. Let us see if we succeed this
time

Certainly we got as expected. Now let us call functions in mymodule


explicitly in [Link] and see the output

Output:

With this information let us create a main()

5 Python Fundamentals| Rooman Technologies


Output:

Now just like Java, C, C++ here in python also we have main() which is
where the execution will start.

Taking user inputs


All clients expect the input to be given by user. So it is very
important that we know how to take inputs from user.

User
input

During program Before program


execution execution

input( ) Command
function line

 During program execution – input()

6 Python Fundamentals| Rooman Technologies


Output:

Note: Irrespective of what we enter as input, it is considered


as string. As division cannot be performed on strings let us
type cast it to integer.

Output:

We can further more reduce the size of code and make it


efficient as following

7 Python Fundamentals| Rooman Technologies


Output:

Before going to the next way of accepting inputs let us see


another example

eval() is a function which evaluates an expression.


Output:

8 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Taking input from command line
 print() function
 Flow of control
 Logical operators
 Comparisons

Taking input from command line


Inputs are also called as arguments. Arguments passed to a program
via command line, even before the program begins execution is called
as command line arguments.

These command line arguments are stored in list, and the name of
this list is argv. Anything that is typed after python followed by
space is considered as input. Which means even the python file name
is also considered as input. And as we know list is ordered, which
means the first elements with 0th index is always the name of python
file.

But if you try to directly access the elements inside the argv list.
Compiler throws error, that’s because this list is present inside a
module called as sys. So without importing that module you cannot
access the elements inside the list.

1 Python Fundamentals| Rooman Technologies


Let us import sys and see the changes in output

The inputs taken through command line are string by default. So we


have to change its datatype by type casting before perform any
arithmetic operations.

2 Python Fundamentals| Rooman Technologies


print( ) function
print() is the function that is used the most while coding. Let us see
what is the syntax of it and what are the different arguments a
print() expects.

Syntax: print(value(s), sep=’ ’, end=’\n’, file=file, flush=flush)

Note: Right now let us not concentrate much on the last two
arguments file and flush.

Value(s): Accepts multiple input values.

Sep: Separates the values. Separated by spaces(default) if not


mentioned any.

End: Ends the line by \n (new line), if not mentioned otherwise.

Let us see some examples

x,y,z are the values here. Separated by spaces and ended by newline.
Which are the default values accepted by the arguments.

Let us try changing the default values for separation of values and
ending of the line in the following example

We can now see that the values are separated by * and line has
ended by ??.
3 Python Fundamentals| Rooman Technologies
Note: As this is interactive mode we have been directed to new line.
But in case of script mode the cursor would be just after ?? and not
in next line.

Output:

We can see that in script mode second print statement does not end
with newline, instead it ends with ?? so as the cursor is after the ??
the next statements gets printed there itself.

Flow of control
The flow of python interpreter is usually sequential. Where it starts
from first and executes each line one by one and then ends
execution. But there might be certain instances where a set of lines
need to be executed only if a certain condition is true/false. As
these statements control the flow of program these are called
control statements/conditional statements.

We have different conditional statements


like:

 if statement
 if else statement
 if elif else statement

4 Python Fundamentals| Rooman Technologies


if statement

A condition is checked, if it is true the statements under if gets


executed, if it is false then it comes out of the conditional
statement.

Output:

Let us check what happens if the condition is false

Output:

In the above output we can see that nothing gets printed, that’s
because there is no statement under false condition/else
statements which we shall see next.

if else statement

A condition is passed if it is true the statements under if gets


executed, if it is false then the statements under else or false
condition gets executed.

Let us see an example of checking if a number is even or odd

5 Python Fundamentals| Rooman Technologies


Output:

if elif else statement

When there are multiple conditions to be checked we use if elif else


statement. Elif is a short form of else if.

Before knowing this conditional statement with an example let us see


different comparisons that can be done and some logical operators

Logical operators
 and
 or
 not

6 Python Fundamentals| Rooman Technologies


Object identity is
checks the equality Comparisons
of references of
Equal == checks
objects.
equality

Less than or equal to


<= checks a number Not equal !=
is lesser than or checks inequality
equal to the other
number
Greater than >
Greater than or checks which
equal to >= checks a number is greater
number is greater
Less than < checks
than or equal to the
which number is
other number
lesser
We shall come across many examples where we will be using logical
operators and the different comparisons. Let us see an example of if
elif else statement

7 Python Fundamentals| Rooman Technologies


In the above example we have seen and operator as well as if elif
else statement. Now let’s see some other logical operators

OR operator

NOT operator

In python we have certain values when passed in conditional


statements, they evaluate to be false. These values are called false
values which are: False, None, 0, empty sequence (‘’, (), []), empty
mapping i.e. {}

8 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Looping statements
 While loop
 For loop
 range()
 When to use for and while loop

Looping Statements
We can also change the flow of control by using looping statements.
Previously we saw how some a part of code gets skipped by not
satisfying the condition. Here we shall see how to make a certain
section of code repeat itself for given number of times. This is only
called as iteration or looping of statements.

In python we have two types of looping statements

 while loop
 for loop

1 Python fundamentals| Rooman Technologies


While loop
In while loop as long as the condition is satisfied
the set of statements repeats its execution. And
once the condition is false the control exits the
loop and executes the rest of the code if any.

Syntax:

while <condition>:

body of the loop

Let us see an example

Output:

Note: initialisation, condition check and incrementation is necessary


in while loop.

2 Python fundamentals| Rooman Technologies


For loop
This is less like the for keyword in other
programming languages, a for loop is used for
iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).

Iterable is something which can work on/with for


loop.

Syntax:

for var in iterable:

body of the loop

Let us see an example

Output:

Above example we see that no condition was checked and no


initialisation is required.

3 Python fundamentals| Rooman Technologies


range( )
If you want to write for loop in traditional way, that is also possible
in python. Where you can specify the number of times your loop
should execute by using the function called as range().

Syntax: range(start, stop, step)

Start: Which position to start from. By default it is 0. //optional

Stop: Which position to stop at (not included). //required

Step: Number specifying incrementation. Default is 1. //optional

Let us see some examples

Output:

Internally a range object is created which is ranging from 0 to 5.

Let us see it in list format

Output:

4 Python fundamentals| Rooman Technologies


Now let us see range starting from non-zero element and with a
different step

Output:

When to use for and while loop


 While loop must be used when you are not sure
how many times a loop should repeat itself. As
long as the condition is true the loop must
execute.
 For loop should be used when you are sure about
the number of times the iterations should be
performed. Here there is no condition checked.

Let us consider an example of banking where you don’t know how


many times you have to withdraw the money. As long as the min
balance is less than actual balance the withdrawal should continue

Output:

5 Python fundamentals| Rooman Technologies


Above example we don’t know how many times the loop should
execute, but we know the condition. In such cases while loop
should be used.

Let’s say we know how much to withdraw, considering 5000rs is


amount to be withdrawn

Output:

Above case we know how many times a loop has to execute. And
there is no condition to be satisfied. In such cases we use for
loop.

Let us see the difference between while loop and for loop

6 Python fundamentals| Rooman Technologies


Today’s Agenda
 Break statement
 Continue statement
 Lambda functions

Break statement
Before we know what the break statement does, let us see where
and why we should use it. Let us consider an example of prime
number

A prime number is a number which is divisible by 1 and the number


itself. If a number is divisible by any other number 1 and number
itself then the number is not a prime number or also called as
composite numbers.

1 Python fundamentals| Rooman Technologies


Output:

pass is a null statement. The interpreter does not ignore


a pass statement, but nothing happens and the statement results
into no operation. The pass statement is useful when you don't write
the implementation of a function but you want to implement it in the
future.

Let us see if the same logic works when we enter a non-prime


number

We can see that there is a mistake in logic because 6 is divisible by


2 and 3 before being divisible by number itself therefore it is not a
prime number.

So when we check for divisibility of 2, 3 and so on, once we


encounter perfect divisibility the current loop should break and
resume the next statements. This is done by break statement.

2 Python fundamentals| Rooman Technologies


Let us see the above example using break statement

Output:

We see that now the logic works perfect for both prime and non-
prime numbers.

 Let us see some short cut operators with the following example

Output:

3 Python fundamentals| Rooman Technologies


Instead of writing sum = sum + 5 the shorter version of the same
expression is sum += 5. Let us verify this

Output:

Same applies for multiplication, division, subtraction etc

Continue statement
Let us first consider an example of calculating even and odd sum

Output:

There is some problem with the odd sum logic. That is, once we know
the number is even the odd sum statement should not execute,
instead i value should increment and if statement should execute
again. This is where continue statement would fit in properly.

4 Python fundamentals| Rooman Technologies


The continue statement rejects all the remaining statements in the
current iteration of the loop and moves the control back to the top
of the loop. The continue statement can be used in both while and
for loops.

Output:

Lambda functions
In python whenever we want to create a function we can use two
keywords def and lambda.

We have seen earlier that when we create a function using def we


have to name the function. Whereas in lambda functions there is no
name for the function or we can say that it is anonymous function.

Syntax:

lambda arguments : expression

lambda functions are single line, single use or one time use functions.

5 Python fundamentals| Rooman Technologies


Let us see how to create one and how to call lambda functions.

Output:

What if we want to call the lambda function more than once? Is it


possible? Because without name how can a function be called? If
these are the questions in back of your mind, let us see the next
example and get the doubts cleared

Output:

We can see that, to use lambda function more than once we have to
assign it a reference and pass the inputs using that reference as
many times as we want.

6 Python fundamentals| Rooman Technologies


Today’s Agenda
 General use of lambda functions
 filter()
 reduce()
 map()
 Other examples

General use of lambda functions


Lambda functions are used whenever the following built-in functions
are used

 filter()
 reduce()
 map()

filter( )
The filter() method filters the given sequence with the help of a
function that tests each element in the sequence to be true or not.

Syntax:

filter (function,sequence)

1 Python Fundamentals| Rooman Technologies


Let us try to understand with the normal function declaration using
def and then compare with lambda function

To each element in the list lst, fun function is applied and checks if
the result is true or false. All the true resulted elements are
collected in a new list evn_lst and displayed. In the output we can
see that evn_lst is a filter object, to get the list we have to type
cast it to list. And the new output displays the filtered list evn_lst.

Let us now see how the code changes when we use lambda function

We can see how a six line code has been reduced to a single line code
with less complexity.

2 Python Fundamentals| Rooman Technologies


reduce( )
The reduce() 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.

Syntax:

reduce (function,sequence)

In the above diagram we are trying to reduce the list lst by adding
all the elements and storing the result in res.

Let us see how to use reduce() with normal def function before
comparing with lambda function

3 Python Fundamentals| Rooman Technologies


Using def function we had to write the logic in 4 lines let us see how
the code changes with the use of lambda function

We can see that the code reduced to a single line statement with
less complexity.

4 Python Fundamentals| Rooman Technologies


map( )
map() function returns a map object of the results after applying
the given function to each item of a given sequence (list, tuple etc.)

For example let’s take a list with certain


numbers and map it with its squared
values.

Syntax:

map (function,sequence)

Let us try to code the above logic using def function first and then
use lambda function

Output:

In the above output we see that similar to filter, in mapping also map
object is created and to see the result in list format we have to
type cast it to list.

5 Python Fundamentals| Rooman Technologies


Let us see the same code with lambda function now

Output:

Certainly the code has again reduced with less complexity here as
well.

Other examples
In python a function can not only be given as input to a function. If
you choose to, you can design a function in such a way that about
calling a function it would return a function as output to you.

Let us see how

Output:

But what if we want to call it multiple times?? Let us see the solution

6 Python Fundamentals| Rooman Technologies


Output:

Like this we can call lambda function multiple times.

Now let us see using fun1() how can we create a mathematical table
of any given number

Output:

7 Python Fundamentals| Rooman Technologies


Similarly we can give any number and generate its mathematical
table. Why not try yourself and verify

8 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Scope of variable
 Global variable
 Local variable
 globals() & locals()
 Recursive function

Scope of variable
A variable is only available from inside the region it is created. This
is called scope. There are two types of variable

 Global variable with global scope:


Variable created outside all functions are global variables.
These variables can be accessed through out the code.
 Local Variable with local scope:
Variables created within a function are local variables. These
are accessed only within that function.

1 Python Fundamentals| Rooman Technologies


Global variables
Let us understand using an example

Output:

We have declared global and local variable, let us see where these
can be accessed

Output:

In the above example we can see that global variable is accessible


throughout the program. Therefore the scope is said to be global.

2 Python Fundamentals| Rooman Technologies


Local variables

Output:

In the beginning we saw that y can be accessed inside the function.


But in the above example when tried to access y outside the function
we are getting an error that “y is not defined”. That is because the
scope of local variable is restricted inside the function only.

globals( ) & locals( )


Is there a way to know which variable is local and which is global?
Certainly there is a way. Let us see what that is

3 Python Fundamentals| Rooman Technologies


All the global variables are mapped to their respective values and
these are stored in a dictionary. To access this dictionary, you have
to call globals(). As seen in above output, there are several global
variables apart from x. For example dunder name, function fun is
having its object as its value etc.

Similarly all local variables are mapped to their values and are stored
in a dictionary, which can be accessed by calling locals().

A doubt might arise in back of your mind. What if both global and
local variable have same name??? Let’s see what happens then

Output:

Whenever local & global variables have same name, if tried accessing
inside a function then local variable is what you’ll get.

4 Python Fundamentals| Rooman Technologies


If at all you want to access global variable inside the function then
you have to use a keyword called global as shown below

Output:

When we say global x, wherever x is used it acts like a global


variable. To verify this we can print x outside the function and cross
check the value.

Output:

Note that integer is immutable, therefore a new object will get


created with new address and the address will be reassigned
whenever we are trying to change the values.

5 Python Fundamentals| Rooman Technologies


Recursive function
In simple words, a function that calls itself is called as recursive
function. Let us take a basic example and look further

Considering that we want to calculate the factorial of 5

As we can see to calculate the factorial of a number we have to


calculate factorial of its previous number. Which in general can we
written as fact(n) = n*fact(n-1). Let us try to code the above logic

Memory perspective

Output:

6 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Strings
 Handling a string
 Representation of string

Strings
We have brief knowledge about strings from datatypes section. Let
us begin with knowing what are the different ways of creating
strings in python

For creating string both „ ‟ and “ ” can be used. But for creating a
multiline string its mandatory to use „‟‟ „‟‟ (triple quotes).

1 Python Fundamentals| Rooman Technologies


Output:

Handling a string
We know that a string can be created using „ ‟ or “ ”. But what if we
want to print a statement like Practice makes “Perfect” on the
output screen. Let‟s see what are the different ways of handling
such strings in python

Output:

Great!! But what if we want perfect within quotes?? Let‟s see


further

This will certainly give an error. We can predict by noticing the


colour change in the string
Considered as a string

„Practice makes ‟perfect„ ‟ //perfect is unknown entity for compiler


Considered as a string

2 Python Fundamentals| Rooman Technologies


Output:

Let us see what are the different ways to debug this

 Using escape character (\)

Output:

Anything that is after the \ is considered to be a part of


string.

 Using quotes

Output:

If the string is enclosed within „ ‟ then we can use “ ” inside the


string and vice versa.

3 Python Fundamentals| Rooman Technologies


Output:

Now that we know how to print a sentence with characters enclosed


in „ ‟ and “ ”. Let us see what if we want to print “Practice” makes
„Perfect‟. Notice that here we are using both „ ‟ and “ ” in one
sentence itself

By now we can guess that we certainly cannot enclose the above


sentence in „ ‟ or “ ”, because that might give an error. So let‟s try
with „‟‟ „‟‟ and see what happens

Output:

The error basically means that compiler doesn‟t know if the string is
ending with pair of double quotes (““) or triple quote and a single
quote („‟‟ „) or single quote and a triple quote („ „‟‟) . This can be
resolved by giving proper space to separate one from each other

4 Python Fundamentals| Rooman Technologies


Output:

In general outer quotes and inner quotes must not be same.

Representation of string
Let us now see how strings are represented in python

Output:

When a string is created, a string type object is created on memory.


As string is a sequence type object, which means it is ordered and
has positional values or index values. When we tell print(s) entire
string gets printed. But as string is collection of characters we can
also access one character at a time. Let us see how

Output:

5 Python Fundamentals| Rooman Technologies


A string is also an iterable in python. Recollect the for loop session,
where anything on which a for loop can be applied on is called as an
iterable.

Output:

If you recollect datatypes session, you know that in python strings


are immutable. Let us verify this

Here we are trying to change the 4th position of string Python which
is o to i

Output:

6 Python Fundamentals| Rooman Technologies


The above error basically tells us that, in python string values cannot
be changed or strings are immutable.

Now let us see some interesting things that strings exhibit

Output:

We see that both the objects s1 and s2 are stored in different


addresses. Now, both the strings have l and o in common. Let us see
at what address o is stored in both the strings

7 Python Fundamentals| Rooman Technologies


Output:

Interestingly we see that both the o‟s are stored in same address.
Before knowing how let us take a simple example and understand

Output:

As strings are immutable, if the values are same then the address
will also be same. Keeping this in back of your mind let us go back to
the previous example and know more

Python internally maintains a dictionary, the name of this dictionary


is interned dictionary. All the single characters are stored as keys
and address of those characters are stored as values.

Let us see how exactly that happens

8 Python Fundamentals| Rooman Technologies


Output:

Pictorial representation of string in dictionary format:

9 Python Fundamentals| Rooman Technologies


Today’s Agenda
 String slicing
 Reversing a string
 Programs on string

String slicing
We have seen how to access single characters from a string. Now let
us see how to take portion of a string, taking a portion of string is
technically called as slicing.

Considering the string Guido Van Russom let us see how slicing can
be done

Syntax: inclusive

string_name [start : stop+1 : step]

exclusive

You can return a range of characters by using the slice syntax.


Specify the start index and the end index, separated by a colon, to
return a part of the string.

If not mentioned anything then by default start value is 0, stop


value is the length of string + 1 and the step is 1.
1 Python Fundamentals| Rooman Technologies
Output:

We have seen how to access a single character, a slice of string. Let


us now see how step value works

Output:

Now let us try slicing the string in reverse way

Output:

2 Python Fundamentals| Rooman Technologies


The reason we did not get the string in reverse is because, the step
value is 1 which represents forward direction. If we want in reverse
direction then step value should be negative.

Output:

In python we also have an additional feature of negative indexes


which is much easier while printing a string in reverse.

Output:

Irrespective of what the start and stop values are, if the step is 1 it
always represents forward direction.

Output:

3 Python Fundamentals| Rooman Technologies


Reversing a string
Unlike other programming languages where reversing a string takes
few set of lines, in python by knowing all the above techniques we
can easily reverse a string.

Let us see how to do it

Output:

Note: If we don’t mention start and stop values and assign step value
as -1. The starting value will be -1 and ending value or stop value will
be negative of length of string.

Programs on strings
1. Program to print all the substrings with length 3 from the
given string

Output:

4 Python Fundamentals| Rooman Technologies


You can try the same program with as many strings as you want.

2. Program to print all the characters of a string except the first


and the last character.

Output:

3. Program to print the characters of a string in the reverse order


except the first and the last character

Output:

4. Program to check whether the given string is palindrome

Let us try the above with two example : Malayalam, python and
see the output

5 Python Fundamentals| Rooman Technologies


Output:

6 Python Fundamentals| Rooman Technologies


Today’s Agenda
▪ Strings Comparison
▪ Programs on strings
▪ String Operations

Strings Comparison
String comparison in python can be performed in three different ways:
1) Comparing Values of Strings using == operator.
2) Comparing References of Strings using id() function or
is operator
3) Comparing String values by ignoring their cases using lower() and
upper().

Let us Understand these different ways of comparing strings in detail with


the help of codes as shown below:

Case I) Comparing Values


1000
Code: S1

1000

2000
S2

2000

1 Python Fundamentals| Rooman Technologies


OUTPUT:

Explanation: In the above code we are comparing two strings using ==


operator which compares the strings based on their values. The two Strings,
Python and Java are not equal and hence we get the output as String values
are unequal.

Case II) Comparing References

Code:

OUTPUT:

Explanation: In the above code we are comparing two strings References


using id() function which compares the address of s1 and s2. S1 has address
1000 and s2 has address 2000 and hence we get the output as String
references are unequal.

Case III) Comparing two similar string objects.


Code: 1000
S1

1000

S2
1000

2 Python Fundamentals| Rooman Technologies


Output:

Explanation: In the above code we are trying to compare two similar string
objects. In the first line, when you assign Python to s1, a new string object
gets created and address is assigned to it which is then stored in S1. In the
second line, you are now trying to create one more string object with the
same value as Python.
Will python create one more object with the same value? Think
Will it
Create?
In order to answer this, one must remember Strings
in python are immutable, hence two similar string
objects are never created in the memory rather they
are shared in the memory.

Thus, the same string object is now shared and its address is copied in s2
which now starts pointing to the same python object. When you now
compare the values using == operator, we get the output as string values are
equal as there is only one string with two references pointing to it.

Case IV) Comparing two similar string objects using is operator.

Code:

Output:

3 Python Fundamentals| Rooman Technologies


Explanation: In the above code we are trying to compare two string
references using is operator. Since s1 and s2 are pointing to the
same object, they both have the same address which is 1000 and
hence we get the output as String references are equal.

Case V) Comparing two similar string objects with different cases.

Code:

Output:

Explanation: In the above code we are trying to compare two string


Values using == operator which are dissimilar in values as s1 is python
in lower case and s2 is PYTHON in upper case and hence we get the
output as String values are unequal.

Programs on strings
Let us now code some important programs on strings which are commonly
asked in many interviews.
1) Write a program to reverse the second half of a string.

Soln: One of the efficient ways of coding the


above question is by making use of Slicing Technique
as shown below.

4 Python Fundamentals| Rooman Technologies


STEPS:

Code:

Output:

String Operations
String operations can be performed by making use of
+ *
and operators.

+ → Performs Concatenation when used between two strings.

* → Performs Replication when used between two strings.

5 Python Fundamentals| Rooman Technologies


+ Operator, When applied between two strings does not perofrm
addition instead performs concatenation which simply means it joins the
strings and creates a new string.

Didn’t get it??? Confused??

Let us try to understand string concatenatiion with the help of coding


examples.

Example1)
1000 2000
0 1 2 3 4

Code: +
3000
S

3000
Output:

Explanation: In the above example, hello is one string object and world
is another string object, when + operator is used between these two
strings, the string values does not change as strings are immutable,
rather a new string object gets created which consists of the
concatenated values of hello and world. It is to this string reference s
is assigned. Since hello string object and world string object do not have
any references pointing to them (Reference count is zero), they are now
treated as garbage objects and are collected by garbage collector

6 Python Fundamentals| Rooman Technologies


Example2)
1000
S1

Code: 1000

2000 3000
0 1 2 3 4

+
4000
Output:

All the three string objects do


not have any reference pointing
at them and hence are collected
by the garbage collector

Explanation: In the above example, hello is one string object to which s1 is


pointing to. In the third line, we are attempting to change the value of an
immutable string by concatenating it with another string called “world” and
hence a copy of string object “hello” gets created. To this string we are now
trying to modify by concatenationg it with world string object. As already
disccussed, strings cannot be modified, due to which a new string object
helloworld gets created to which there is no refernce assigned and hence it
becomes a garbage object. All the string objects with zero refrence count
are now collcted by the garbage collector and hence the only object in the
memory is hello with s1 as refrence poitinting to it, thus the ouput we got is
hello two times.

Example3)
Code:

7 Python Fundamentals| Rooman Technologies


Output
1000
S1

1000

2000 3000
0 1 2 3 4

+
4000
S2

4000

These two string objects do not


have any reference pointing at
them and hence are collected by
the garbage collector

Example4)

Code:

Output

Try to draw the memory map for the above code and understand the
output.

PYTHON IS AN OPEN SOURCE LANGUAGE.

8 Python Fundamentals| Rooman Technologies


Today’s Agenda
▪ String comparison by ignoring cases
▪ Ascii Table
▪ Conversion to lowercase
▪ upper( ) and lower( )
▪ join( )

String Comparison by ignoring cases


We had seen different cases of comparing two strings except the
above case. Let us now learn how to compare two strings by ignoring
their cases.
In order to compare two strings without considering their cases, one
must understand ASCII table as python is case sensitive.
ASCII is the acronym for
the American Standard Code for Information Interchange.
It is a code for representing 128
English characters as numbers, with each letter
assigned a number from 0 to 127.
For example, the ASCII code for uppercase M is
77 and lowercase m is 109. Most computers use
ASCII codes to represent text, which makes it
possible to transfer data from one computer to
another.
Using the range of lowercase alphabets i;e 97 to
122, we can check whether it is a uppercase or
lowercase alphabet and perform the conversion.

1 Python fundamentals| Rooman Technologies


ASCII TABLE
Have a look at the ASCII TABLE shown below:

Let us understand the conversion from uppercase to lowercase and


vice-versa.
Consider characters a and A whose ascii values are 97 and 65.
Simple addition and subtraction will help us perform the conversion.
If we subtract 32 from 97, we get 65 which
is the ascii value of A.
Char Value
a 97
32
A 65
2 Python fundamentals| Rooman Technologies
Note: Uppercase alphabets fall in the range of 65 to 90
Lowercase alphabets fall in the range of 97 to 122.

String Conversion to lowercase


Let us understand the above conversion with the help of codes:

CODE:

OUTPUT:

Explanation: In the above code we used two functions ord() & chr().
ord() converts a character to an integer and gives its ascii value.
chr() converts an integer to a character based on its ascii value.
Above code performs the conversion of lowercase a to uppercase A.

Let us now try writing logic for the conversion of an entire string to
Uppercase.

CODE:

3 Python fundamentals| Rooman Technologies


OUTPUT:
He got the
correct
output.
Did you?

Explanation: In the above code we are first checking if each


character inside the entered string falls in the range of (97,122)
which simply means it is a lowercase character if true. If the condition
gets evaluated to true, we performing the conversion from lowercase
to uppercase by subtracting 32 to the ascii value of character and
storing it in a new string which is s_upper. If in case condition fails,
then the character inside string is not a lowercase and do not require
any conversion and hence we are simply appending the original
character from string s to string s_upper. Thus, by subtracting 32 to
any lowercase character we get the ascii value of its uppercase
character.

The output we got using the above lines of code can also be achieved
in just one line by calling a built-in function upper().
Also vice-versa can be performed by making use of built-in function
lower().

upper() and lower()

upper() function on a string converts all characters to uppercase.


lower() function on a string converts all characters to lowercase().

upper( ) lower( )

4 Python fundamentals| Rooman Technologies


CODE:

OUTPUT:

After getting to know all this, let us now compare two strings by
ignoring their cases.

CODE:

CODE:

OUTPUT:

5 Python fundamentals| Rooman Technologies


upper( )
We have seen how to perform concatenation between strings using +
operator but this approach is not efficient when concatenation
between multiple strings has to be performed.

Why you wonder???

Let us understand this with the help of code.

CODE:

OUTPUT:

Explanation: In the above code, we have first created a list which


now gets allocated memory with some address and has four string
values, Python,Java,Django,Spring with lst as reference pointing to it.
In the next line we are creating an empty string object with s as
reference to it. Inside the for loop to the empty string s, we are
attaching the value of i. The first value of i is Python and when
concatenation happens, a new string object gets created which
consists of added result of an empty string and Python. We are now
storing it back in s which means s is now pointing to this newly created
string object with address 3000 and hence the previous objects to
which s was pointing to, will become garbage object and is collected
by garbage Collector. In the second iteration, i takes the value Java
which is now concatenated with Python String object having address i
3000. Since we are performing concatenation, a new string object
gets created having concatenated result of Python and java with
6 Python fundamentals| Rooman Technologies
address 4000. The added result is now stored back into s and hence
s is now pointing to this string object whose address is 4000. In the
next iteration, i gets the value Django which is now concatenated with
PythonJava. Since we are performing concatenation, a new string
object gets created which consists of added result of
PythonJavaDjango with 5000 as address. Similarly, in the last
iteration i gets the value Spring which is now concatenated with
PythonJavaDjango. Since we are performing concatenation, a new
string object gets created which consists of added result of
PythonJavaDjangoSpring with 6000 as address and this value is
stored back into s which means s is now pointing to this string object
with address 6000 and all the other objects who do not have any
reference become garbage object as their reference count is zero
and hence, are collected by garbage collector.
This way, when we use + operator to perform multiple concatenation
operations, memory is not utilised efficiently as multiple string
objects are allocated and deallocated memory multiple times and
memory gets wasted which directly affects the performance of the
software. Understand the above scenario with the help of memory
map diagram shown below:

7 Python fundamentals| Rooman Technologies


Wondering, is there any better approach to
concatenate multiple strings?

The better approach is using join() function.

join( ) in python joins each element of an iterable ( Such as list, tuple


and strings) and returns the concatenated string.

CODE:

OUTPUT:

Explanation: join( ) in the above code takes all the elements present
in the list and joins them into one string. Have a look at the memory
map diagram shown below where in one shot join( ) concatenates all
the strings and stores them into s.

8 Python fundamentals| Rooman Technologies


Today’s Agenda
 Strings built-in functions (contd)
 Programs on strings
 String translation

Strings built-in functions (contd)


To continue with the built-in functions, let us see the below example
where we shall be checking if the string starts with https, if yes
then print the string

Output:

In the above example we are using string slicing method, now let us
see can we do the same using built-in functions

1 Python fundamentals| Rooman technologies


Output:

Now let us see a similar example but now we shall


check how many amongst the url list ends with com

Output:

Let us see is there any built-in function which can


do the same function with reduction of code
complexity

Output:

2 Python fundamentals| Rooman technologies


We can simplify the above example like below

Note: If we are passing multiple inputs to endswith() then it should


be passed as tuple.

Output:

Programs on strings
1. Program to count number of lower case, upper case, numbers and
special characters present in a string.

3 Python fundamentals| Rooman technologies


Output:

Now why don’t you try the same example without using any built-in
method.

2. Program to swap the case. That is, change upper case to lower and
vice versa using swapcase().

Output:

3. Using the same above example let’s see what title() and
capitalize() do

4 Python fundamentals| Rooman technologies


Output:

String translation
Python string method translate() returns a copy of the string in
which all characters have been translated using table (constructed
with the maketrans() function in the string module)

Logic:

Output:

5 Python fundamentals| Rooman technologies


Today’s Agenda
 String formatting
 Format specification types
 Programs

String formatting
In python we have two ways to achieve string formatting

 format() method
 f string literal

format() method

The format() method formats the specified value(s) and insert them
inside the string's placeholder. The placeholder is defined using
curly brackets { }.

Syntax:

[Link](*args)

1 Python fundamentals| Rooman Technologies


Output:

Let us see another example

Output:

Note: If nothing is specified in place holders, the default order is


considered.

Now let us see an example where order is specified explicitly

Output:

2 Python fundamentals| Rooman Technologies


Within the place holder { } not only can we pass positional values, but
also additional values which is going to change the way of its
representation in different ways.

string ”{position:format_specification}”

format specification types:

 Alignment
 Presentation
 Conversion

Format specification
Alignment:

 >right alignment

Output:

 <left alignment

Output:

 ^ center alignment

Output

3 Python fundamentals| Rooman Technologies


Presentation:

 f-fixed point notation

Output:

We can also have pi value beginning with 0’s and mentioning


number of digits as follows

Output:

 e-exponent notation

Output:

As we know we can adjust the decimal numbers let us see how


we can do it here

Output:

4 Python fundamentals| Rooman Technologies


Let us now try to pass different arguments inside place holders.

Output:

The above input will give an error because we have three place
holders but we are trying to pass three inputs in a single list. Is
there a way to tackle this? Definitely, let us see how

Output:

However there’s also an easy way to do this called as unpacking as


shown below

Output:

5 Python fundamentals| Rooman Technologies


Programs
1. Let us take numbers as input from user and try to find the
average of numbers with only 4 decimal points.

Output:

We now have the list of numbers, but we cannot perform any


math operations on list of strings. So now we have to map
strings to integers as shown below

Logic:

Output:

6 Python fundamentals| Rooman Technologies


Now we have list of integers, next we should reduce the list to
the sum of all the integers by using reduce() function

Logic:

Output:

As expected we got the sum of all the integers, now we should


take the average by dividing it with number of integers present
as shown below

7 Python fundamentals| Rooman Technologies


Output:

Try to solve such programs which


involve application of the
functions you have studied so far
and join the dots.

8 Python fundamentals| Rooman Technologies


Today’s Agenda
 String replication
 String formatting-Conversion
 ‘f’ string literal
 Raw string literal
 Regular expressions

String Replication
We know what is string concatenation, let us know what is string
replication with the help of following example where we are trying to
replicate the string python three times

Output:

We can repeat the single string value the amount of times equivalent
to the integer value passed.

1 Python fundamentals| Rooman Technologies


String formatting- Conversion
 b- decimal to binary

Logic:
2 70

2 35  0

2 17 1

2 8 1

2 4 0

2 20

1 0

Output:

 o- decimal to octal

Logic:
01 000 110

1 0 6
Output:

2 Python fundamentals| Rooman Technologies


 x- decimal to hexadecimal

Logic:
0100 0110

4 6

Output:

‘f’ string literal


As of Python 3.7, f-strings are a great new way to format strings.
Not only are they more readable, more concise, and less prone to
error than other ways of formatting, but they are also faster!

Let us understand by an example

format() f-string

Output:

3 Python fundamentals| Rooman Technologies


Let us compare the performance of both as below

Output:

As we can see f-string is much better than format() from above


output. The timing changes with respect to the processor.

Raw string literal


Let us see an example to understand the meaning of raw string

Output:

4 Python fundamentals| Rooman Technologies


Regular Expressions
Regular expression is a sequence of characters that forms a search
pattern. Why do we need it? Where it is used? Let us see

 In MS word whenever there is a spelling mistake, we get red


underline which notifies us that the spelling is wrong. This is
done by matching the word we enter to the
actual word and if there is a mismatch then
it notifies by the red line.
 Google search engine, where anything that
we entered is matched with whatever is
there in google. It does this with the help of
software called as webscroller who scans the
entire internet to find the search queries
matching the entered data.
 Spam filtering is another best example where all our mails are
being monitored and filtered based on the words present in the
content of it. Every mail goes through the spam filter where if
words like free, discount, cheap, offer etc are encountered
then it is a spam.

Let us see an example and understand in a better way

Output:

5 Python fundamentals| Rooman Technologies


The output says that match is found in the span of 0 to 6 that is
Python. Let us see how to access that in a better way

Output:

Let us now try to find another match

Output:

We can see that we did not get any match object. Which means the
match() starts searching from the beginning and if it doesn’t find
the match in starting then it doesn’t return any match object.

Is there a way to overcome this disadvantage? Definitely there is,


let us see how

Output:

6 Python fundamentals| Rooman Technologies


By making use of search(), irrespective of the position the matching
is done. So we have found a match object in span of 10 to 15 where
15 is exclusive.

Output:

This is how we slice the match object.

From the above examples we understood that match() can be used


for pattern matching where the match object is present in the
beginning whereas search() will do the same irrespective of the
position of the match object.

7 Python fundamentals| Rooman Technologies


Today’s Agenda
 Meta characters
 Programs

Meta characters
A character when used in regular expression has a special meaning to
it is called meta character. There are many meta characters but now
let’s focus on .(dot) which will match single character.

Let us understand with examples

Output:

1 Python fundamentals| Rooman Technologies


search() will only give the first match. If we want to see all the
matches then we should use another function called as findall(). Let
us see how to use it

Output:

We can see that all the matches have been found and a list of every
single character is created including spaces and full point.

Now what if we want to match the .(full point) in the test string, let
us see how to do it

Output:

\ will escape the meaning of . as meta character. That is why \ is


called escape(special character).

Now what if we want to find multiple matches, let us see how to find
them

2 Python fundamentals| Rooman Technologies


Output:

|(pipe) will search for Python or super. Sometimes only one amongst
them can be present and sometimes both, either way | meta
character works.

Now let us consider another example

Output:

We can see only two matches are found, what if we want the match
where w is missing or in other words 0 or many occurrence should be
considered. Let us see which meta character to use then

3 Python fundamentals| Rooman Technologies


Output:

For 0 or many * is the meta character to be used. Similarly if we


want only 0 or 1 occurrence then ? should be used as below

Output:

Now let us see how to search for 1 or many

Output:

Let us see another example to understand better

4 Python fundamentals| Rooman Technologies


Output:

Now let us see another meta character where we can search for
exact number of occurrences

Output:

Let us see another example where multiple occurrences of python is


there, but we want the match that is at beginning.

Output:

5 Python fundamentals| Rooman Technologies


^ helps to search for the particular pattern in beginning of the
string. We see that a match object is found in the span of 0 to 6
which is python.

Similarly to find the match at the end we have another meta


character $,

Output:

Now let us take another example where we want to match all the
vowels present in the test string.

Output:

Character class meta character [] searches for any of the


mentioned characters in the test string.

6 Python fundamentals| Rooman Technologies


Now what if we want to search all the characters which are not
vowels/consonants, let us see what to do

Output:

Note: ^ used inside [] will match all the characters except the ones
specified in [].

Now let us try to match all the lower case, upper case and the digits
in the test string using character class

Output:

As we can see all the lower case has been matched by saying a-z,
upper case by saying A-Z and digits by saying 0-9.

7 Python fundamentals| Rooman Technologies


The above can be performed in other way as well, by using another
meta character \w which will match all alpha numeric characters

Output:

Now let us match only the special characters

Output:

Is there an easier way to do this? Definitely, by using \W

8 Python fundamentals| Rooman Technologies


Output:

\w is for alpha numeric and \W is for non-alpha numeric characters.

Similarly there are shortcuts to find only digits by using \d, and non-
digits by using \D.

Output:

Now let’s see for non-digits

Output:

9 Python fundamentals| Rooman Technologies


Similarly, if you want only white spaces to be matched you can use \s
and try for yourself.

To summarize the list of meta characters studied so far


. single character

\ escape (special character)

| A|B or operator

* 0 or many

? 0 or 1

+ 1 or many

{m} matches exactly m


characters

{m,n} matches
between m and n characters

[] character class

^ start of string

$ end of string

\s any white space


character

\S any non-white space


character

\d any digit

\D any non-digit

\w any word character

\W any non-word character

\b a word boundary

\B non-word boundary

10 Python fundamentals| Rooman Technologies


Programs
Now let’s see how to combine the meta characters based on our
expectation

Example 1: To find the matches of vowels occurring twice

Output:

Example 2: To find the matches week and weak

Output:

11 Python fundamentals| Rooman Technologies


Today’s Agenda
 Word boundary
 Programs on meta characters
 Grouping
 Programs

Word boundary
Word boundary is another meta character which will put boundaries
wherever it is used. From the below example this can be understood
in a better way

Output:

Here abcpqrxyz and abc got matched as there is nothing before abc.

1 Python fundamentals| Rooman Technologies


\b will put a word boundary, where if \b is at the beginning of regex
then if anything present before the boundary it doesn’t get
matched. And if \b is at the end of regex then if anything is present
after the boundary it doesn’t get matched.

Output:

Here pqrxyzabc and abc got matched as there is nothing after abc
in these strings.

Output:

We saw that in all the above three cases pqrabcxyz didn’t get
matched. So to get a match of string which has characters on either
side, we should use \B which is opposite of word boundary.

2 Python fundamentals| Rooman Technologies


Output:

To cross verify, let us print it using search() to get the span of


matched object.

Output:

Programs on meta characters


Example 1: To match first word from the sentence.

3 Python fundamentals| Rooman Technologies


Output:

Example 2: To match last word from the sentence.

Output:

Example 3: Let’s match the words in the test string having the word
length as 4.

Output:

4 Python fundamentals| Rooman Technologies


Example 4: To check if the given email address is valid address or
not. With the following rule set

 Username:
a. Character: alphanumeric
b. Special character: _, - or $
 Domain: [Link]

Output:

Example 5: Similar to previous example but here let us consider


other domains as well

Output:

5 Python fundamentals| Rooman Technologies


Grouping
Whatever a regular expression matches for, that complete string is
actually treated as group 0. Let us verify this

Output:

Now we know that match object belongs to group 0, as we used


search() we could match only first occurrence.

What if we want to create subgroups within regular expression? Is


that possible? Definitely it is possible by using (), let us see how

6 Python fundamentals| Rooman Technologies


Output:

Great!!! But we could only match first occurrence, what about the
rest? How should we match them? Let us see is there a solution for
it

Output:

7 Python fundamentals| Rooman Technologies


Programs
Example 1: From the previous code, replace the domain name to
“@[Link]”

Output:

Example 2: Find the number of times substitution has occurred in


previous example.

8 Python fundamentals| Rooman Technologies


Output:

From above output, we can see that substitutions have happened 8


times.

Example 3: Given the text “1992/04/10”, split the year, month and
day using re module.

Output:

9 Python fundamentals| Rooman Technologies


Today’s Agenda
 Pattern object
 Data structures
 Disadvantages of array

Pattern object
An object which has regular expression inside is called patter
object.

Approach 1 Approach 2

Output: Output:

No approach is better than the other it’s the user comfort and their
preference.

1 Python fundamentals| Rooman Technologies


Data structures
Python has four main data structures which are shown below

These are called data structures because each of these store data
in different manner and access the data in different manner along
with some restrictions of each due to which their behaviour and
application differ.

Let us understand how and where to use data


structures exactly.

Before learning about data structures, one should always know how a
data is strored in RAM. RAM is a collection of bytes, byte consists
of the fundamental building block called bits. 8 bits is one byte. RAM
is collection of crores of such bytes. Data in these bytes is stored in
machine language(binary) which is combination of 1’s and 0’s.

2 Python fundamentals| Rooman Technologies


This is how RAM looks like

Internal representation of RAM

Collection
of bytes

Each byte consists of 8 bits

Inside each byte data is stored as combination of 1’s and 0’s

3 Python fundamentals| Rooman Technologies


Let us now store PYTHON in RAM and see how exactly it is stored
1 Byte

P Y T H O N

1001 1002 1003 1004 1005 1006

In each byte a character gets stored but in binary format, for your
understanding purpose it is shown in characters.

Wherever you see continuous storage of characters or one next to


other it is referred to as array in any programming language.
Technically continuous storage is called as contiguous memory
allocation.

In such cases the address of first byte is stored in the reference


which is called as the base address, which will point to the array.

arr 0 1 2 3 4 5

1001

Base address
If data is stored contiguously like this and if arr has the base
address then you can access any element present in this array as
efficiently and soon as possible. Wonder how? The answer is using
the formula called array arithmetic.

arr[index] = base address + width * index

arr[3] = 1001 + 1 * 3

arr[3] = 1004

Arrays also come with some disadvantages.


Let us see what are those

4 Python fundamentals| Rooman Technologies


Disadvantages of arrays
 Arrays require contiguous memory allocation.
 Arrays can store only homogeneous data.
 The size of an array can neither grow nor shrink.

Let us see the first two drawbacks or disadvantages.

We know that different type of data occupy different size in


memory, let us consider the following example to understand in a
better way
char integer

P 45 Y T 30
1001 1002 1006 1007 1008

Now let us try to apply array arithmetic formula and see if it will
work

arr[3] = 1001 + 1 * 3 //there no uniform width of data

arr[3] = 1004 //which is not the right address

We see that there is mismatch in addresses. This means, if we try


to store different types of data, arrays will fail because arrays
arithmetic doesn’t stand correct for this situation.

5 Python fundamentals| Rooman Technologies


Today’s Agenda
 Disadvantages of arrays(contd)
 Referential array
 Lists
 Operations on list

Disadvantages of arrays (contd)


In previous session we saw two disadvantages, let us understand the
third disadvantage of arrays

The third disadvantage is that the array can neither grow nor
shrink in size. Let us try and understand why this is so

Consider the following situation where PYTHON is stored in certain


memory

1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

P Y T H O N

There is a possibility that after memory for PYTHON was allocated


the memory beside PYTHON was assigned for some other operation.

1 Python Fundamentals| Rooman Technologies


This means that the array cannot grow contiguously in either
direction.

RAM
Dispersed
free memory
locations

The other way of understanding this is, free memory locations are
very rarely found next to each other. Most of the time they are
dispersed in RAM, and we know arrays definitely cannot make use of
dispersed memory locations as it won’t satisfy arrays arithmetic
formula. But there are other data structures like linked lists, which
can link these dispersed memory locations and form another data
structure.

Referential array
Python has a different take on arrays because it uses referential
arrays, let us see what this means

Consider the following example where different type data is present

45  integer

Python  String

99.9  float

False  Boolean
2 Python Fundamentals| Rooman Technologies
Motive is to store these data contiguously, let us see how

1000 2000 3000 4000

45 python 99.9 false

r_arr 0 1 2 3

6000 1000 2000 3000 4000

6000

The solution to store different types of data in a single array is by


storing the addresses of the objects rather than their values, the
addresses will refer/point the objects and hence this type of array
is called referential arrays. As the addresses will be of same type
there won’t be a problem in giving base address as the reference of
the array which will point to it and satisfy array arithmetic formula
as well.

Most of the data structures in python make


use of referential arrays. Strings are also
stored in the same format, where each
character’s object is created with its own
address and these addresses are stored in an
array.

Lists
Let us start with the first data structure list, which uses dynamic
array. Dynamic array is an array which can grow and shrink in size.
Confused? Let us understand the explanation shall we?

3 Python Fundamentals| Rooman Technologies


Let us consider we want to store the following data (data here can
be heterogeneous as well)

Data: 10 20 30 40 50 60 70

Initially there will be no memory, but let


us assume we want to store 10, then
instead of giving exact amount of
memory it will over allocated the
memory, if you want to store one element a list will provide you four
memory allocations. This is called as over allocation or amortization
which is allocating more than required amount.

Once one by one data is stored in allotted memory at some point


there won’t be any space left, at that time new array will be created
with few more memory allocations. In the new memory the values
present earlier are copied and next values will be stored. And the
old memory gets de-allocated. Definitely this also comes with its own
disadvantages.

Memory New Memory


Values gets
0 10 copied 0 10

1 20 1 20

2 30 2 30

3 40 3 40

No more 4 50
space
5 60

6 70

7 Extra
space

4 Python Fundamentals| Rooman Technologies


If you are wondering about the resizing pattern then here it is

4, 8, 16, 25, 35, 46, 58, 72…

Earlier we said that when one element is stored 4 memories are


allocated, let us see if we can access those memories

Output:

10 can be easily accessible, but can the extra memory allocations be?

Output:

Definitely not! You will get an error stating list index out of range.

Now let us see different ways of creating a list


lst 0 1 2 3 4

1000 10 20 30 40 50
Output: 1000

5 Python Fundamentals| Rooman Technologies


Can we only store homogeneous data? Let us see

lst 0 1 2 3 4

1000 10 20.5 True 1+3j Python


Output:
1000

So yes!! We can store heterogeneous data as well. As internally it is


stored in referential array format.

Let us see what else can be stored inside a list

Output:

0 1 2 3 4

lst
0 1 2 0 1 2
1000
10 20 30 40 50 60 70 {9,10,11} {1:’x’, 2:’y’}

List Tuple Set Dictionary

1000

Certainly we can store any type of data and data structures in list.
Now let us try to access individual values in the below example

6 Python Fundamentals| Rooman Technologies


Output:

Operations on list
List can perform two operations

 Concatenation (using +)
 Replication (using *)

We have seen these operations in strings, let us see how it works in


case of lists.

Concatenation

Output:

7 Python Fundamentals| Rooman Technologies


lst1 0 1 2 lst2 0 1 2

1000 10 20 30 2000 40 50 60

1000 2000

lst3 0 1 2 3 4 5

3000 10 20 30 40 50 60

3000

The order of concatenation matters. If lst2+lst1 is given the you’ll


get the output as [40, 50, 60, 10, 20, 30]. Why don’t you check it
yourself?

Replication

Now let us see how to fill entire list with one value

Output:

Let us see one more way of using replication

Output:

8 Python Fundamentals| Rooman Technologies


As we know list is a sequence and so were strings, so let us see if the
operations performed on string can be performed with lists as well

Output:

Slicing in python applies to every sequence type like list, tuple and
strings.

Now let us see how loops and lists work together

Output:

9 Python Fundamentals| Rooman Technologies


Now let try to access the values using the index values

Output:

10 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Mutability of list
 Addition
 Modification
 Removing elements

Mutability of list
Let us explore the mutability of list. Mutability of list means add
elements to the list, modify elements from the list and remove
elements from the list. If these three required are checked then we
say that a particular data structure is mutable.

Addition
Let us consider an example and try to add elements

append()
5

60

1 Python fundamentals| Rooman Technologies


Output:

Now let us try to append multiple values

Output:

As we can see the error is stating that append() can take only one
argument. To overcome this we can convert 3 inputs to one like
below

Output:

2 Python fundamentals| Rooman Technologies


0 1 2 3 4 5 6
lst
0 1 2
1000
10 20 30 40 50 60 70 80 90

1000

What if we don’t want it like this and want to add it individually, let
us see

2000

lst 0 1 2 3 4 5 6 7 8

3000 10 20 30 40 50 60 70 80 90

3000

Once the reference is reallocated to new concatenated list, the old


ones are dislocated.

Output:

3 Python fundamentals| Rooman Technologies


Even though the above method is providing the expected output, it is
not the efficient way. There is a much easier way to achieve the
same, let us look at it

extend()

Output:

Now let us try to insert the elements in middle

insert() will take two arguments index and object. In the specified
index if there is no object then the new object gets inserted, if not
the size of list increases and all the elements from the specified
index are moved towards right and then the new value is inserted.

4 Python fundamentals| Rooman Technologies


insert()

lst 0 1 2 3 4 5

1000 10 20 99 30 40 50

Output:

Modification
Now that we have seen addition, let us see the new feature i.e.
modification considering the following example

1001 1003 1004


1000

20 40 50
10

1000 1001 2000 1003 1004

0 1 2 3 4

300 2000
lst 1000

1000 10 20 300 40 50

0 1 2 3 4
5 Python fundamentals| Rooman Technologies
Output:

Let us now consider an example where we want to modify a portion


of the list by one value

Output:

Whenever we are doing slicing assignment, we should always assign


an iterable. 99 can be easily converted to an iterable by placing it
within [] like below

lst 0 1 2

1000 10 99 50

1000

6 Python fundamentals| Rooman Technologies


Output:

Now let us try to modify multiple values

Output:

But now what if we want to add more than three values to a slice of
three values? Let us see

Output:

Certainly even that is possible. We can add as many elements as we


want in certain portion of list.

7 Python fundamentals| Rooman Technologies


Now our expectation is to modify every alternative element by a
value

Output:

Removing elements
Now that we have seen addition of elements, modification of
elements, let us see the last but not the least removing elements.
Consider the following example

remove()

lst 0 1 2 3 4

1000 10 20 40 50 60

1000

8 Python fundamentals| Rooman Technologies


Output:

But what if we have two same values which will get removed? Let us
see in below example

Output:

Always the first occurrence is going to be removed. But what if we


want to remove all occurrences of the value? But before we do that
we should first check for that value. So let us see below how to do it

Output:

So now that we know how to check presence/absence of an object


we shall next see how to remove all the occurrences

9 Python fundamentals| Rooman Technologies


We know that whenever we are not aware of how many times an
operation must be performed, while loop should be used.

Output:

10 Python fundamentals| Rooman Technologies


Today’s Agenda
 Removing elements (contd)
 Creation a copy of list
 Nested list

Removing elements (contd)


In previous session we have seen different ways to remove an
element. Let us continue to explore some more methods

pop()

pop() method by default pop the last element from the list as shown
below

pop()

1 Python Fundamentals| Rooman Technologies


Output:

Now what if we want to pop an element in between the list, let us


see how to do it

pop(3)

lst 0 1 2 3 4

1000 10 20 30 50 60

1000
Output:

del

del is another keyword using which you can delete an elements from
the list by mentioning its index

Let us consider the following example and get to know it in better


way

2 Python Fundamentals| Rooman Technologies


lst 0 1 2 3 4 5 6 7 8 9

10 20 30 40 50 60 70 80 90 100
1000

1000
del lst[3]

lst 0 1 2 3 4 5 6 7 8

1000 10 20 30 50 60 70 80 90 100

1000

Output:

Now let us see how to delete a portion of the list

del lst[2:8]

lst 0 1 2 3

1000 10 20 90 100

1000

3 Python Fundamentals| Rooman Technologies


Output:

Now let’s try to delete alternative elements from the same list

del lst[::2]

lst 0 1 2 3 4

1000 20 40 60 80 100

1000

Output:

Now let us try deleting a portion of elements in reverse order

Consider we want to delete elements from -4 to -9 in reverse


direction i.e. -1

4 Python Fundamentals| Rooman Technologies


del lst[-4:-9:-1]

lst 0 1 2 3 4

1000 10 20 80 90 100

1000 -5 -4 -3 -2 -1

Output:

Deletion of elements from a list

Based on values Based on index


remove() – will delete pop() – will delete elements
elements based on based on indexes, but cannot
values. delete more than one value.

del keyword helps in deleting


more than one element using
its index values.

5 Python Fundamentals| Rooman Technologies


Creation a copy of list
Creating a copy of list in python is super easy, let us see how

lst1 0 1 2 3 4

1000 10 20 30 40 50

-5 -4 -3 -2 -1

1000

lst1[:]

Output:

There is also another way to create a copy, let us see how

6 Python Fundamentals| Rooman Technologies


list(lst1)

Output:

Nested list
Just like nested loops, nested list means presence of lists within a
list. Let us see how to copy nested lists and by any means do they
differ

7 Python Fundamentals| Rooman Technologies


Let us consider the following example where we are trying to create
a copy of list lst1 and if made changes in original list lst1 the copy
lst2 shouldn’t get affected

Output:

If tried to modify the values in original list lst1 the so called copy of
list lst2 also got reflected. Which is not what we expected, so let us
see what happens through memory perspective

8 Python Fundamentals| Rooman Technologies


lst2
4001
lst1 3001
2001
4001
1001
3001
0 1001 10
0 0 2001
2001 1002
1 1002
20

2002 1003

0 30
1003
1
1
2002 1004 2002
1 1004
40

2003 1005
2
2003 0 1005 50

1006
1 1006
60

Above is the memory perspective of the given example. lst2 is the


shallow copy of lst1. A shallow copy constructs a new compound
object and then (to the extent possible) inserts references into it
to the objects found in the original.

To overcome the result of shallow copy we have something called as


deep copy which is present in copy module. Let us see how to make
use of it in below example

9 Python Fundamentals| Rooman Technologies


Output:

Great!! Now the output is as we expected, but let us see from


memory perspective what has changed

lst2
4001
lst1 3001
4001
2001 1001
3001 5001
0 1001 10
1001 0
0
2001 1002 0
1 1002 5001
20 1002 1

2002 1003 5002

0 30
1003
1 1003 0
2002 1004
1004
5002 1
1 40 1004 1

2003 1005
2
2003 0 1005 50

1006
1 1006
60

1. A deep copy constructs a new compound object and then,


recursively, inserts copies into it of the objects found in the
original.

10 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Built-in functions (lists)
 Methods
 Programs

Built-in functions (lists)


Any function that is provided as part of a high-level language and can
be executed by a simple reference with specification of arguments.

max()
min()
range()
len()
enumerate()
any()
eval()
sum()
list()
sorted()
all()
reversed()

Let us get to know the need of these built-in functions one by one

1 Python fundamentals| Rooman Technologies


Consider the following example

Output:

The below built-in functions will be using while looping a list or


iterate a list

Output:

Methods
Everything in python is an object, which means everything has its
own type and type is technically referred to as class. And the
functions present within a class are called as methods.

2 Python fundamentals| Rooman Technologies


append()
insert()
extend()
pop() count()
remove()
index()
clear()
reverse()
sort()

Let us see some examples using these methods

Output:

Next example is to show how to delete all the elements from list

Output:

3 Python fundamentals| Rooman Technologies


Now our expectation is to arrange the elements in certain order. Let
us see how to achieve it

1000

lst 1000 25 17 36 7 55 13

sorted(lst)

2000

lst 2000 13 36
7 17 25 55

Output:

Now if we want the same in descending order


1000

lst 1000 25 17 36 7 55 13

sorted(lst, reverse=True)

2000

lst 2000 36
55 25 17 13 7

4 Python fundamentals| Rooman Technologies


Output:

sorted() was the built-in function. But we also have a method which
can perform the same operation. Let us see

Output:

If descending order is what we want, then

Output:

5 Python fundamentals| Rooman Technologies


The main difference between sorted() and method sort() is that in
sorted() a new copy of list in created where the sorting is done and
new reference needs to be given. That means extra memory. But in
sort() the sorting happens within the same list.

Now we want to reverse the list


1000

lst 1000 25 17 36 7 55 13

reversed(lst)

2000

lst 2000 36
55 25 17 13 7

Output:

But is there a method which can do the same operation in an


efficient way? Definitely there is

Output:

6 Python fundamentals| Rooman Technologies


Programs
Example 1: Program to find sum of sublist.

lst 1000 0 1 2 3 4 5 6

1000 1 2 3 6 10 16 25

0 1 2 3

3 6 10 16

sum()

34

Example 2: Program to append the elements which is not present in


the primary list

Output:

7 Python fundamentals| Rooman Technologies


Today’s Agenda
 Programs on list

Programs
Example 1: Program to insert an element at right position within a
sorted list.

Expected output

lst 0 1 2 3 4 5

1000 10 20 30 35 40 50

1000
1 Python Fundamentals| Rooman Technologies
Output:

Example 2: Given five positive integers, find the minimum and


maximum values that can be calculated by summing exactly four of
the five integers. Then print the respective minimum and maximum
values as a single line of two space-separated long integers.

For example, arr[1,3,5,7,9] . Our minimum sum is 1+3+5+7=16 and our


maximum sum is 3+5+7+9=24. We would print 16 24

Let us consider the following case

lst 0 1 2 3 4

1000 4 2 1 5 3

1000

Missing
number

15 = 3 + 4 + 2 + 1 + 5 = 12

sum(lst) – max(lst) 15 = 5 + 4 + 2 + 1 + 3 = 10 min

sum(lst) – min(lst) 15 = 1 + 4 + 2 + 5 + 3 = 14 max

15 = 2 + 4 + 1 + 5 + 3 = 13

15 = 4 + 2 + 1 + 5 + 3 = 11

2 Python Fundamentals| Rooman Technologies


Output:

Example 3: Find the sum of minimum number and maximum number of


a list without using any built-in functions

lst 0 1 2 3 4 5

1000 50 80 40 20 10 30

1000
minimum = 10 maximum = 80

Sum = minimum + maximum

Sum = 10 + 80 = 90

Output:

3 Python Fundamentals| Rooman Technologies


Example 4: To calculate the length of list without using built-in
functions

lst 0 1 2 3 4 5 6

1000 50 80 40 20 10 30 100

1000

Output:

Example 5: To calculate the sum of values of entire list without using


built-in method.

Output:

4 Python Fundamentals| Rooman Technologies


Example 6: Similarly calculate product of all elements.

Output:

Try yourself what happens if the list is empty?

And find a solution for it.

5 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Programs on lists
 List comprehension

Program on list
Example 1: Program to check if the expression contains balanced
parenthesis.

s 0 1 2 3 4 5 6 7 8 9 10 11

1000 [ ( { } [ ] ) ] ( { } )

1000

1 Python Fundamentals | Rooman Technologies


Output:

Example 2: Comparison of lists.


lst1 0 1 2 lst2 0 1 2

1000 7 3 5 2000 7 13 5

1000 2000

Output:

Output:

2 Python Fundamentals | Rooman Technologies


Output:

Output:

lst1 0 1 2 3 lst2 0 1 2 2

1000 5 3 7 6 2000 7 3 5 6

1000 2000

Output:

3 Python Fundamentals | Rooman Technologies


lst1 0 1 2 3 lst2 0 1 2 3

1000 7 6 2 3 2000 7 6 1 3

1000 2000

Output:

lst1 0 1 2 3 lst2 0 1 2

1000 5 3 7 1 2000 5 3 7

1000 2000

Output:

lst1 0 1 2 3 lst2 0 1

1000 1 5 7 9 2000 3 2

1000 2000

4 Python Fundamentals | Rooman Technologies


Output:

List Comprehension
Before knowing what is list comprehension let us consider an
example and later on see how the same example can be written in
much simpler way using list comprehension

Output:

Now let us see the same example with list comprehension

Syntax:

[What I want From which loop On what condition] //non-technical

[Expression for item in list If condition] //technical

Optional

5 Python Fundamentals | Rooman Technologies


Output:

Now let us consider an example where the condition is used. The


condition is, instead of printing squares of all the numbers let us
print only even numbers square in both traditional way and using list
comprehension

Output:

Now let us see how the same code changes when used list
comprehension

6 Python Fundamentals | Rooman Technologies


Output:

7 Python Fundamentals | Rooman Technologies


Today’s Agenda
 Zip function
 Programs
 all( ) and any( )

Zip function
Let us understand the zip function with the help of an example
lst1 0 1 2 3 lst2 0 1 2 3

1000 5 12 15 7 2000 15 8 15 3

1000 2000
Expected Output

res 0 2
1 3

3000 (5,15) (12,8) (15,15) (7,3)

3000

1 Python fundamentals| Rooman Technologies


Output:

The actual use case of zip() is not to zip multiple lists, it can iterate
over multiple lists at the same time. Wonder how? Let us see

Output:

Now our expectation is to join two lists and then form a sentence
out of it.
lst1 0 1 2 3 4 5 6 7

1000 ‘A’ ‘App’ ‘’ ‘da’ ‘kee’ ‘t’ ‘doc’ ‘a’

1000
lst2 0 1 2 3 4 5 6 7

2000 ‘n’ ‘le’ ‘a’ ‘y’ ‘ps’ ‘he’ ‘tor’ ‘way’

2000 Expected output


res 3 4 5 6 7
0 1 2

3000 ‘Apple’ ‘a’ ‘day’ ‘keeps’ ‘the’ ‘doctor’ ‘away’


‘An’

3000

2 Python fundamentals| Rooman Technologies


Output:

Let us try to do the same using list comprehension

Output:

Programs
Example 1: If the length of word is greater than 5, it should be
converted to lowercase and if it is less than or equal to then it
should be converted uppercase.

3 Python fundamentals| Rooman Technologies


s
1000

K n o w l e d g e i s p o w e r
K
1000 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

lst 0 1 2

2000 Knowledge is power

2000 Expected Output


res 0 1 2

3000 Knowledge IS POWER

3000

Output:

Can we reduce the size of code? Definitely we can by making use of


list comprehension as shown in the below example

4 Python fundamentals| Rooman Technologies


Output:

all( ) and any( )


Let us understand what these functions do with an example where
we want to check if the elements are positive or not
lst 0 1 2 3 4 5

1000 10 20 30 40 50 60

1000

Output:

Let us try putting some negative number and then test the output

5 Python fundamentals| Rooman Technologies


Output:

all( ) will check the condition for all the elements present whereas
any( ) will check if at least one element satisfies the condition.

Output:

Now coming to real time application, let us take an example where we


are checking if a student has failed in any of the object or in other
words if he/she has passed in all subjects

lst 0 1 2 3 4 5

1000 45 75 30 80 95 65

1000

6 Python fundamentals| Rooman Technologies


Output:

Now to the same list let us see if any of the marks scored are above
70

Output:

7 Python fundamentals| Rooman Technologies


Today’s Agenda
 Performance analysis list

Performance analysis list


Every data structure comes with a certain efficiency of operations
on which it performs on the particular system. The software that a
programmer code runs in several systems, hence knowing the
efficiency of particular data structure is very important for a
programmer to make right decisions of when to use and when not to
use certain things. To know this we have to perform performance
analysis of list. To know what it exactly is, let us consider an
example of list and try to modify its values
lst 0 1 2 3 4

2000 10 20 30 40 50

2000

lst[2]=300
Array arithmetic => arr[index] = base address + width*index

1 Python fundamentals| Rooman Technnologies


lst 0 1 2 3 4

2000 10 20 300 40 50

2000
Using array arithmetic formula we can access any nth element in
same time. That means irrespective of the position we can perform
the operation in a constant time and index doesn’t matter at the
time. If we should speak the same thing in terms of time complexity
or asymptotic analysis then

Time Complexity O(1) 1 representing constant time

Now let us consider the same list and try to append an element and
see it’s time complexity
Amortized list

lst 0 1 2 3 4 5 6 7

2000 10 20 30 40 50

2000
Appended list

lst 0 1 2 3 4 5 6 7

2000 10 20 30 40 50 90

2000

Time Complexity O(1) 1 representing constant time

It doesn’t matter if we are appending a value to a list of length 5 or


50 or 5000. We’ll be still appending it to the last element and we
know that lists always over allocate the memory. So the time is same
for all the elements. Hence time complexity is constant.

2 Python fundamentals| Rooman Technnologies


But now let us consider that the list is full and to append another
value it has to copy all elements and then grow in size and only after
that append operation can be done. Does in this case also time
complexity remains constant? Let us see

lst 0 1 2 3 4 5 6 7

2000 10 20 30 40 50 60 70 80

1000

0 1 2 3 4 5 6 7 8 9

10 20 30 40 50 60 70 80 90

2000 //list grows to the size of 16 elements

Here time complexity certainly will not be constant because,


depending upon the length of the list, new list has to grow in size and
then copying operation should be carried only then an element can be
appended.

Time Complexity O(n) Linear time

Linear time means, as the number of elements increases the time


also increases.

Now let us consider inserting an element. Remember that insertion


can be done in any position unlike appending at last. So during
insertion certain elements must be shifted towards their right and
then the element gets inserted (Considering amortized list).

Time complexity is always calculated considering the worst situation


which is inserting an element in 0th position where all the elements
must be shifted to right and then the new element will be inserted.

3 Python fundamentals| Rooman Technnologies


lst 0 1 2 3 4 5

2000 10 20 30 40 50 60

2000

lst 0 1 2 3 4 5 6

2000 100 10 20 30 40 50 60

2000
//n elements gets shifted to right

Time Complexity O(n) Linear time

Now let us consider extending a list. Which can be done using for
loop but let us see what happens if we do that
lst 0 1 2 3 4 5 6 7

2000 10 20 30 40 50

2000

0 1 2 3 4 5 6 7
lst
3000 10 20 30 40 50 60 70 80

2000 //no space for 90 to be appended

0 1 2 3 4 5 6 7 8

10 20 30 40 50 60 70 80 90

3000 //resized list with 16 memory locations

4 Python fundamentals| Rooman Technnologies


We can see that using for loop is not the efficient way to extend
list. There is extend() which performs the same operation in
efficient way, let us see how

3000

0 1 2 3 4 5 6 7 8

10 20 30 40 50 60 70 80 90

3000 //resized list with 16 memory locations

Time Complexity O(n2) n2 represents the no of elements in second list

extend() will check beforehand if all the elements can be placed


inside the list, if not the list gets resized and then the operations is
carried further. Whereas in previous situation for loop was not
checking the vacancies beforehand and only after realisation of no
space the new grown list was created and then the elements were
copied.

Now next let us consider popping an element. In first case let us


not pass anything in pop() which will result in popping of last element.

lst 0 1 2 3 4 5 6 7 8

2000 10 20 30 40 50 60

2000

5 Python fundamentals| Rooman Technnologies


lst 0 1 2 3 4 5 6 7 8

2000 10 20 30 40 50

2000

Irrespective of the length of list pop() will delete the last element
if not mentioned otherwise. Therefore time complexity will remain
constant in this case.

Time Complexity O(1) 1 represents constant time

Now what if we pass the index value of the element to be popped?


How does it change the time complexity? Let us see, considering the
worst case that is, popping the 0th element

lst 0 1 2 3 4 5 6 7 8

2000 20 30 40 50 60

2000

Time Complexity O(n) Linear time

All the elements must left shift which is n-1 elements.

Now let us try removing an element from the list


lst 0 1 2 3 4 5 6 7 8

2000 10 20 30 40 50

2000

lst 0 1 2 3 4 5 6 7 8

2000 10 20 30 50 60

2000

6 Python fundamentals| Rooman Technnologies


Time Complexity O(n) Linear time

40 should be first searched by iterating on each element and then


removed. So complexity in time increases as increase in elements.
But what if the element was not present in list? Let us see

Output:

Certainly we will get an error saying element is not in the list. But to
throw this error it has to iterate over n elements and then give a
message saying element not in list. So the time complexity is indeed
linear in this case as well.

Now next let us try reversing a list.

lst 0 1 2 3 4 5 6 7

2000 10 20 30 40 50 60 70 80

2000

lst 0 1 2 3 4 5 6 7

2000 80 70 60 50 40 30 20 10

2000

Time Complexity O(n) Linear time

7 Python fundamentals| Rooman Technnologies


While reversing a list n/2 swap operations happen. But that doesn’t
imply n/2 time complexity because as elements increase time
complexity will increase which says it is linear in nature.

Next let us have a look at count of an element.


lst 0 1 2 3 4 5 6 7

2000 10 20 30 20 10 60 70 20

2000

count

Time Complexity O(n) Linear time

To know the count of an element we certainly have to iterate over


each element. Thereby the time complexity will be linear in nature.

Next let us try to find the index of the element passed.

lst 0 1 2 3 4 5 6 7

2000 10 20 30 40 50 60 70 80

2000

Time Complexity O(n) Linear time

Certainly to find the index of the element we need to first search


for the element by iterating on the list n times for worst situation.
Thereby time complexity will be linear.

8 Python fundamentals| Rooman Technnologies


Let us now try to get an element from the list

Array arithmetic => arr[index] = base address + width*index

Irrespective of the length of the list, getting an element will take


constant time as we are mentioning the index of the element we
want to get.

Time Complexity O(1) Constant time

Next let us try with len() function


2000

2000

ob_size= 6

Time Complexity O(1) Constant time

List object

State: Behaviour:
ob_size appear()
pop()
insert()

9 Python fundamentals| Rooman Technnologies


List is an object which has certain states in which a variable called
as ob_size stores the length of list. So irrespective of the size of
list the length can be accessed easily by the help of this variable and
hence the time complexity is constant.

10 Python fundamentals| Rooman Technnologies


Today’s Agenda
 Time complexity of operators
 Tuples

Time complexity of operators


Let us now begin with finding the time complexity of operators like
in, ==, !=, <, <=, >, >=, +, * in list.

Let us consider an example for in operator where we are trying to


find a value in list.

lst 0 1 2 3 4 5 6 7

1000 10 20 30 40 50 60 70 80

1000

Time Complexity O(n) Linear time

When we use in operator, in worst situation every element is


checked.

1 Python fundamentals| Rooman Technologies


Now let us see the comparison operators : ==, !=, <, <=, >,>=

lst2 0 1 2 3 4 5 6 7

2000 10 20 30 40 50 60 70 90

2000

Time Complexity O(n) Linear time

Amongst all operators let us now consider == operator, which has to


check each value to know if two lists are equal or not. Same case
with other operators as well.

Now let’s see + operator (Concatenation)


lst1 0 1 2 3

1000 10 20 30 40

1000
+
lst2 0 1 2 3 4 5

2000 50 60 70 80 90 100

2000 concatenation

lst3 0 1 2 3 4 5 6 7 8 9

3000 10 20 30 40 50 60 70 80 90 100

3000 // amortized list

2 Python fundamentals| Rooman Technologies


Time Complexity O(n1+n2) Linear time

As each elements copy has to be made before concatenation, the


time complexity will be linear.

Last but not the least let us see * operator (Replication)

lst 0

1000 10

1000

Rep_lst 0 1 2 3 4 5 6 7 8 9

2000 10 10 10 10 10 10 10 10 10 10

2000

Time Complexity O(c*n) Linear time

C is number of times n has to be repeated, which increases linearly.

Tuple
Tuples are similar to lists, but tuples are immutable in nature and
internally they make use of static arrays and not dynamic arrays.
Unlike in lists here static array means they cannot grow or shrink in
size. Let us understand through an example
Memory

0 10

1 20

2 30

3 40

3 Python fundamentals| Rooman Technologies


Output:

In tuple we don’t have option of appending or removing elements. Let


us see different ways of creating a tuple

Output:

Next way of creating a tuple is

Output:

Storing homogeneous data

4 Python fundamentals| Rooman Technologies


Output:

Can we store heterogeneous data as well? Let us give a try

Output:

Great!! Now let us see if just like lists can tuple also store a tuple,
list, set, dictionary in it

tup
1000

0 1 2 3 4

0 1 2 0 1 2

10 20 30 40 50 60 70 {9,10,11} {1:’x’, 2:’y’}


set Dictionary
list tuple

1000

Output:

5 Python fundamentals| Rooman Technologies


Now let us see does tuple support the features that list supported

Output:

We will get similar error saying that those attributes doesn’t exist
in tuple data structure.

Let us see other modifications considering same example

Output:

We certainly cannot change anything inside a tuple. But we definitely


can access individual elements or portion of elements. let us see in
below example

6 Python fundamentals| Rooman Technologies


Output:

Now let us try to create a tuple of single element and see what
happens

Output:

We see that type of object is not tuple instead it is int. Whenever


we try to store a single element or singleton tuple there’s a certain
way to do it, let us see how to do it

Output:

7 Python fundamentals| Rooman Technologies


Let us see another interesting thing about tuple

Output:

Even without () the elements are treated as tuple because they are
packed inside a tuple.

8 Python fundamentals| Rooman Technologies


Today’s Agenda
 Set
 Separate chaining

Set
We know that set is a collection which is unordered and un-indexed.
In Python sets are written with curly brackets. To understand sets
in better way and to know why they are unordered, we should first
know the internal implementation of it. So let us consider an example
and get to know it

1 Python Fundamentals | Rooman Technologies


95 1001 Hash table

45 1002 1010 0

1006 1
160 1003
2
1005
80 1004
1001 3 Hash function

1005
20 1011 4
sum(data) % size
1006 1007 5
66

1008 6
88
1007
1003
7
15 1008
1004 8

1009 1002
15 9
No duplicates
10
65 1010

22 1011

Sets use a methodology called hashing to store data. There are two
components associated with hashing hash functions and has table.

Now what if we have another data in the set as 92, its sum is 11
(9+2) and 11%11 is 0. But at 0th position we already have a value
store. At this time collision occurs. Is there a way to resolve this
issue? Certainly it can be solved by using collision resolution
techniques

2 Python Fundamentals | Rooman Technologies


Collision Resolution Techniques

Separate chaining Open addressing


(Open hashing) (Closed hashing)

Linear Probing

Quadratic Probing

Double Probing

Amongst all, let us focus on separate chaining.

Separate chaining
Let us consider the following example and see how collision is
resolved. Hash table

92 65 0
Data

1
18
45 2

95
30 95 3 Hash function
88
30
4
23 sum(data) % size
41 23 88 5
54
41
6
80
65 7
92
80 8

54 45 18
9

10

3 Python Fundamentals | Rooman Technologies


Whenever collision happens a separate block is chained to the same
position and in the new block the value is stored. This is known as
separate chaining.

So far we have seen that set uses hashing to store data, set is
unordered data, and set will not allow duplicate entries to store.

The next feature of set is that, inside a set we cannot store


mutable datatypes. Is there any particular reason for this? Let us
see

To understand this we should first know hashable data / immutable


data.
Hashable / Immutable data

 Hash key is calculated using


all the data.
 Hash key must be unique
and should not change.

Why can’t a set be stored in a set

Let us see what happens if we store mutable data inside a set.

We know that, to generate the hash


key all the data must be used. Now
what if we store a mutable data like list
and get a hash key, but later on what if
we want to append an element or
remove an element certainly the data is
going to change and so would the hash
key. And we cannot have two hash keys
for the same object. Hence the entire
hashing algorithm would be faulty.

4 Python Fundamentals | Rooman Technologies


Let us see an example with code

Output:

We can see that the output is unordered, duplicates have been


removed. And note that the hash function computer uses is
different and complicated than the one which is explained above for
your understanding.

Now let us see if we can store immutable data in set

Output:

Great! We can store immutable data. What about mutable data? Let
us see

Output:

5 Python Fundamentals | Rooman Technologies


We certainly cannot store mutable datatypes. If you are wondering
can we access the hash key generated by hash function; Let us see in
the next example

Output:

Output:

hash() definitely will not accept mutable datatypes, it will only


accept hashable/immutable datatypes.

Let us see how set is a mutable datatype

6 Python Fundamentals | Rooman Technologies


Output:

Let us see some more features of set

Output:

discard() will check if the element is present in the set, if yes it


removes it and if not it just discards and doesn’t give any error.

Output:

The set is updated, definitely in unordered way.

7 Python Fundamentals | Rooman Technologies


Today’s Agenda
 Set operations
 Subset
 Programs on sets

Set Operations
Operations performed on two sets at the same time are called as set
operations. Set operations include set union, set intersection, set
difference, complement of set and Cartesian product.

1 Python Fundamentals| Rooman Technologies


Let us consider an example and see the operations

1000 s1

1 2 3 4 5 6 7 8 9 10 11 13

1000

2000 s2

7 9 10 77 14 15 16 22 86

2000

Union of s1 and s2 is the set of elements present in s1, in s2 or in


both s1 and s2.

Output:

2 Python Fundamentals| Rooman Technologies


Output:

Next let us see the intersection of two sets. Intersection of two


given sets s1 and s2 is a set which consists of all the elements which
are common to both s1 and s2.

s1

1000 1 2 3 4 5 6 7 8

1000
s2

2000 1 2 3 6 9 10 12

2000

3 Python Fundamentals| Rooman Technologies


Output:

Next operation is the difference of two sets. Difference of two


sets considering s1-s2 will return the elements in s1 after removing
the elements of s2 in s1.

4 Python Fundamentals| Rooman Technologies


Output:

Note: s1-s2 is not same as s2-s1.

Next let us see the symmetric difference of two sets. The


symmetric difference of two sets s1 and s2 is the set of elements
that are in either A or B, but not in their intersection.

Output:

5 Python Fundamentals| Rooman Technologies


Now let us see some more built-in functions of set operations;

intersection_update(): Will update the first set as the intersection


result of the two sets.

Output:

difference_update():Will update the first set as the difference


result of the two sets.

Output:

6 Python Fundamentals| Rooman Technologies


Subset, Superset and disjoint set
A set of which all the elements are contained in another set is called
as a subset.

s2

2000 3 11 4 7

2000

Output:

A set(s1) is said to be superset if all the elements of s2 are in s1.

7 Python Fundamentals| Rooman Technologies


Output:

Two sets are said to be disjoint when their intersection is null, or in


other words when the two sets have nothing in common.

Output:

Programs on set
Example 1: Take the input from the user and remove all the
duplicates from it.

Output:

8 Python Fundamentals| Rooman Technologies


Example 2: Write a program to print the number of duplicate
elements in the list.

Output:

Example 3: Given 3 set of roll numbers of students who play hockey,


football and cricket. Print the roll numbers according to the below
conditions.

a) Who play any game


b) Who play all 3 games
c) Who play only hockey
d) Who play either football or cricket but not both

Output:

9 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Set comprehension
 Programs
 Frozen set

Set Comprehension
Similar to list comprehension python also has set comprehension. Let
us understand with an example

Output:

1 Python Fundamentals| Rooman Technologies


Output:

Now our expectation is to find the square of


only even numbers

Output:

2 Python Fundamentals| Rooman Technologies


Output:

Let us see if the syntax changes after including else condition

Output:

Output:

3 Python Fundamentals| Rooman Technologies


Programs
Example 1: Check is a string is pangram.

Output:

Output:

4 Python Fundamentals| Rooman Technologies


Can the above code be more efficient and smaller? Certainly using
set comprehension it can be achieved

Output:

Example 2: Check if the string is heterogram.

Output:

Can the code be written using list comprehension? Definitely it can

5 Python Fundamentals| Rooman Technologies


Output:

Output:

6 Python Fundamentals| Rooman Technologies


Frozen set
We know that set is mutable. But what if we don’t want it to be
mutable? Is there a way? Definitely. A set can be made immutable
by wrapping it in a built-in function called as frozenset() which will
disable the operations involving modification.

Output:

The following operations can’t be performed as they modify the


existing set

add(), update(), remove(), discard(), pop(), difference_update(),


intersection_update(), symmetric_difference_update()

The following operation are allowed


to be performed on frozenset as
they don’t modify the existing set

union(), intersection(), difference(),


symmetric_difference(),
isdisjoint(), issubset(), issuperset()

7 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Performance analysis of sets
 Dictionary

Performance analysis of sets


Let us see the performance analysis of several operations in sets.
Consider the following example with respective hash table and hash
function

Hash table
s
0 1 2 3 4 5 6 7 8 9 10

65 100 20 12 22 41 33 52 80 73

Hash Function

sum(data) % size

1 Python fundamentals| Rooman Technologies


To add an element:

[Link](45) is an operation of constant time irrespective of the size of


the set.
Time complexity: O(1) Constant Time

To remove an element:

[Link](45) is an operation of constant time irrespective of the


size of the set.

Time complexity: O(1) Constant Time

Popping of an element:

[Link]() is also an operation with constant time irrespective of the


size of the set.
Time complexity: O(1) Constant Time

Search of an element:

Unlike in lists, search operation 33 in s is very efficient in sets as


each element is stored based on its hash key. Therefore even the
search operation is constant time.

Time complexity: O(1) Constant Time

Now let us see the time complexity of set operations like union,
intersection, difference and symmetric difference etc

2 Python fundamentals| Rooman Technologies


Union of two sets:

When union of two sets is taken then each and every element is
considered from both the sets. So with increase in number of
elements in the set, time complexity increases.

Time complexity: O(n1+n2) Linear Time

Intersection of sets:

When we are finding the intersection or the elements common in


both the sets, we need to check with all the elements present. So
here also the time complexity is linear.

Time complexity: O(n1+n2) Linear Time

Difference of sets:

Even while finding the difference all the elements are considered so
here as well the time complexity increases as increase in number of
elements.
Time complexity: O(n1+n2) Linear Time

Symmetric difference of sets:

Similar to the difference of sets, time complexity in symmetric


difference also increases as increase in number of elements.
Time complexity: O(n1+n2) Linear Time

Checking if s2 is subset of s1:

To check if s2 is subset of s1, we need to see if all the elements of


s2 are present in s1. So time complexity depends on number of
elements in s2.

Time complexity: O(n2) Linear Time

3 Python fundamentals| Rooman Technologies


Checking if s1 is superset of s2:

To check if s1 is superset of s2, again we need to see if all the


elements of s2 are present in s1. So time complexity depends on
number of elements in s2.

Time complexity: O(n2) Linear Time

Checking is s1 and s2 are disjoint sets:

To check if both s1 and s2 are disjoint sets, we need to check each


and every element and see they are present in both the sets or not.
So the time complexity increases as increase in number of elements.
Time complexity: O(n1+n2) Linear Time

Dictionary
Earlier we saw how elements are stored in lists, tuple and set. We
saw the efficiency of operations like search. Where lists take linear
time to search for an element set takes constant time. But we can
store duplicate elements in list, we can access each element using its
index, but this is not possible in sets. So is there any data structure
which can store duplicate elements, mutable, immutable data with
index based access and more importantly without compromising the
time efficiency, certainly to achieve all of the above we need to use
dictionaries.

4 Python fundamentals| Rooman Technologies


Let us see how the elements are stored in dictionary

d{2:45, 1:92, 16:64, 22:56, 18:72, 26:88}


Hash table

<1,92> 1

<2,45> 2
Hash function
3

<22,56> 4 sum(data) % size

<16,64> 7

<26,88> 8

<18,72> 9

10

The key difference in storing an element in dictionary is, instead of


the values passing through hash function they key is passed and
based on the hash key generated the key and its associated value
gets stored. So all the restrictions are now imposed on the key and
not to the values.

Let us see different ways of keys passed in dictionary

5 Python fundamentals| Rooman Technologies


Output:

We can also pass string as a key

Output:

We can pass all immutable data structures as keys. Only the mutable
data structures cannot be passed as keys.

Now let us see how to add elements to dictionary

We are trying to add a single element, add multiple elements in two


different ways using update() and try to modify existing element and
pass an existing value.

6 Python fundamentals| Rooman Technologies


Output:

7 Python fundamentals| Rooman Technologies


Today’s Agenda
 Built-in methods in Dictionary
 Storing elements
 Accessing elements in dictionary

Built in methods in dictionary


Let us see some how to modify dictionary using some built-in
methods

d <1:’p’> <2:’y’> <3:’t’> <4:’h’> <5:’o’> <6:’n’> <7:’a’>

Output:

1 Python Fundamentals| Rooman Technologies


Let us see some features of pop()

Output:

Output:

Storing elements
Let us understand by an example where we have stored a string and
a list in dictionary

2 Python Fundamentals| Rooman Technologies


Output:

Great the output is as expected where the dictionary values


remained intact. Let us see what happens to list if we do the same
operations

Output:

We can see that the output is not as expected. The list value inside
dictionary has also changed. Wonder why? Let us see through
memory perspective

3 Python Fundamentals| Rooman Technologies


3000 Hash Table
x
‘b’ 0
3000
1000 <1,1000> 1
lst
‘a’ <2,2000> 2
2000
3 Hash Function

10 20 30 99 4 sum(data) % size

2000 0 1 2 3 5

10

Accessing elements in dictionary


We know there are keys and their values in dictionary. Let us see
how to access keys first

Output:

4 Python Fundamentals| Rooman Technologies


d <2:’Java’ <3:’Python’
<1:’C’>
> >

[Link]()

dict_keys

1 2 3

list([Link]())

0 1 2
1000
1 2 3

Next let us see how to access only the values

d <2:’Java’ <3:’Python’
<1:’C’>
> >

[Link]()

dict_values

‘C’ ‘Java’ ‘Python’

list([Link]()
)
0 1 2
1000
‘C’ ‘Java’ ‘Python’

5 Python Fundamentals| Rooman Technologies


Output:

Now our expectation is to access keys as well as values or also called


as key value pair

d <2:’Java’ <3:’Python’
<1:’C’>
> >

[Link]()

dict_items

(1,‘C’) (2,‘Java’) (3,‘Python’)

list([Link]()
)
0 1 2
1000
(1,‘C’) (2,‘Java’) (3,‘Python’)

6 Python Fundamentals| Rooman Technologies


Output:

Let us see what happens if we don’t mention anything and try to


iterate over d

Output:

If we don’t specify anything, by default it’ll iterate over the keys.

7 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Programs on dictionary

Programs on dictionary
Example 1: Write a Program to count the occurrence of each
character in the given strings.
s

1000

0 1 2 3 4 5 6 7 8 9 10

‘M’ ‘I’ ‘S’ ‘S’ ‘I’ ‘S’ ‘S’ ‘I’ ‘P’ ‘P’ ‘I’

1000

1 Python Fundamentals| Rooman Technologies


Output:

To the same example we now want to print those characters which


have occurred more than 3 times

d Key Values

‘M’ 1

‘I’ 4

‘S’ 4

‘P’ 2

Output:

Example 2: Write the program to count total number of pairs.

lst 0 1 2 3 4 5 6 7 8

1 7 1 1 7 3 5 2 3
1000

1000

2 Python Fundamentals| Rooman Technologies


d
key value

1 3

7 2

3 2

5 1

2 1

Output:

Example 3: Write the program to print the mobile number


associated with the name, if the name is not among the entry display
‘contact not found’.

Contacts

Bob : 778965123
Charli : 998564213
Alex : 775641321

3 Python Fundamentals| Rooman Technologies


Output:

Example 4: Write a program to print the Kth non-repeating character


in the given string.
lst

1000

0 1 2 3 4 5 6 7 8 9 10 11 12

‘C’ ‘o’ ‘m’ ‘p’ ‘r’ ‘e’ ‘h’ ‘e’ ‘n’ ‘s’ ‘i’ ‘o’ ‘n’

1000

4 Python Fundamentals| Rooman Technologies


d Key Value

‘C’ 1

‘o’ 2

‘m’ 1

‘p’ 1

‘r’ 1

‘e’ 2

‘h’ 1

‘n’ 2

‘s’ 1

‘i’ 1

Output:

5 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Programs on Dictionary contd…

Programs on Dictionary contd…


Example 1: Write a program to count the occurrence of each word in
the given sentence. And print the words that have occurred more
than 3 times.

Input sentence: That That Is Is That That Is Not Is Not Is That It


It Is

d
Key Value

‘THAT’ 5

‘IS’ 6

‘NOT’ 2

‘IT’ 2

1 Python Fundamentals| Rooman Technologies


Output:

Example 2: Write the program to print the highest marks of every


person.

Input: Alex 50, Bob 70, Alex 90, Bob 30

Output: Alex 90, Bob 70

lst 1000

Swathi 80 Lavanya 75 Rohit 62 Swathi 72 Lavanya 85

1000 0 1 2 3 4

2 Python Fundamentals| Rooman Technologies


Output:

Example 3: Write a program to inverse the dictionary in such a way


keys becomes values and values becomes keys.

d Key Value res Key Value

1 ‘A’ 0 1

‘A’ 1
2 ‘B’ 3

3 ‘A’ 0 1 2

‘B’ ‘B’ 2 4 5
4

5 ‘B’
0

‘C’ ‘C’ 6
6

3 Python Fundamentals| Rooman Technologies


Output:

4 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Programs on dictionary contd…
 Dictionary comprehension

Programs on dictionary contd…


Example 1: Write a program that splits the sentence and arrange
them into descending order based on their length and then in
chronological order.

lst 0 1 2 3 4 5 6

1000 jack and jill went up the hill

1000

1 Python fundamentals| Rooman Technologies


d Key Value

0 1 2 3
4
jack jill went hill

0 1
3
and the

0
2
up

Output:

2 Python fundamentals| Rooman Technologies


Dictionary comprehension
Similar to list comprehension and set comprehension, dictionary
comprehension is a concise way of creating dictionaries.

Let us start with an example where we take input from user and
want to store it as key and the value should be the length of the
word.

lst 0 1 2 3

1000 ‘India’ ‘Germany’ ‘Poland’ ‘USA’

1000

d Key Value

‘India’ 5

‘Germany’ 7

‘Poland’ 6

‘USA’ 3

Output:

3 Python fundamentals| Rooman Technologies


Output:

Example 2: From the given list of numbers take even numbers as the
key and square of it as values.

Output:

4 Python fundamentals| Rooman Technologies


Output:

Now in the same example along with the even numbers for odd
numbers let us print their cube.

Output:

Output:

5 Python fundamentals| Rooman Technologies


Example 3: To the given list check if the length is less than 6 if so
convert it into uppercase and cube the value of length and if the
length is greater than or equal to 6 then just square the length
value.

Output:

Output:

6 Python fundamentals| Rooman Technologies


Today’s Agenda
 Performance analysis
 Difference between list, set,
tuple and dictionary
 Collection module

Performance analysis of dictionary


The performance analysis of dictionary is similar to that of sets. As
both of them use hashing function to store the data. Kindly refer
back if you don’t remember.

1 Python fundamentals| Rooman Technologies


Difference between list, set, tuple
and dictionary
List Set Dictionary Tuple
lst=[10,12,15] st={1,23,24} dict={1:32,2:45} tup=(“spam”,55)
print(lst[0]) print(st) print(dict[1]) print(tup[0])
Set elements can’t
be indexed.
Can contain Can’t contain Can’t contain Can contain
duplicate duplicate duplicate keys, duplicate
elements. elements. Faster but can contain elements. Faster
compared to list duplicate values compared to list
Mutable Mutable Mutable Immutable, Values
can’t be changed
ones assigned.
Slicing can be Slicing can’t be Slicing can’t be Slicing can be
done done(unordered done done
data)
Memory Memory Memory Memory efficient
inefficient inefficient inefficient
Slow creation Slow creation Slow creation Fast creation
Usage: Usage: Usage: Usage:
Use list if you Membership When you need Use tuples when
have a collection testing and the logical association your data cannot
of data that elimination of between key:value change.
doesn’t need duplicate entries. pair. A tuple is used in
random access. When you need When you need combination with a
Use lists when you uniqueness for the fast lookup for dictionary. For
need a simple, elements. your data, based example a tuple
iterable collection on a custom key. might represent a
that is modified When your data is key because it’s
frequently. being constantly immutable.
modified.

2 Python fundamentals| Rooman Technologies


Collection module
Collection module in python has certain classes like chainmap,
counter, namedtuple and deque these classes are very effective
and great tools to work with. Let us start with chainmap

To understand the use of chainmap, let us consider the following


example of hypermarket where you find all the necessary items for
day to day life.

Output:

3 Python fundamentals| Rooman Technologies


We see that the value of shirts is not reflected in the original
dictionary. To make this happen we should use the class chainmap
present in collection module as below

Output:

Now we can see the changes being reflected both in both the
dictionaries.

Let us now see what happens if we try to add an element

4 Python fundamentals| Rooman Technologies


Output:

New element always gets added in the first dictionary.

Let us now look at the next class that is counter

Output:

The above code can be written in a single line using counter class.

5 Python fundamentals| Rooman Technologies


Output:

Whenever you want to count the number of occurrences and store it


as a dictionary then always make use of counter class.

Next let us see the different ways of using counter class

Output:

6 Python fundamentals| Rooman Technologies


Below are some of the methods commonly used in counter class

Output:

Next let us see some operation which can be performed on counter


objects

7 Python fundamentals| Rooman Technologies


Output:

Moving ahead let us look into namedTuple

Named tuples assign meaning to each position in a tuple and allow for
more readable, self-documenting code. They can be used wherever
regular tuples are used, and they add the ability to access fields by
name instead of position index. Let us look at the example

Output:

8 Python fundamentals| Rooman Technologies


Last but not the least let us look at deque class which stands for
double ended queue

Output:

The above operation will take linear time. Whereas using deque it
can be done in constant time

Output:

9 Python fundamentals| Rooman Technologies


Today’s Agenda
 Object orientation

Object orientation
So far we have seen the structured style of programming language
where we used different functions to perform operations. Now it’s
time to have a look at providing solutions using the classes and the
objects.

For example: Imagine you are standing in a queue for getting the
food every time. So suddenly you have a eureka moment and plan to
have a mobile application into which all the food items are present.
All you have to do is click on whichever food item you like and get it
delivered at your doorstep. So this person goes to a software
company and proposes this idea, where upon clicking on the food item
it should ask from which store you want to purchase it and then
track down your location after which mode of payment is selected
and within few minutes you can enjoy the food at your desired
location.

1 Python fundamentals| Rooman Technologies


For all this to work software developer should see this in an object
oriented perspective where different objects are interacting with
each other, in this case customer, restaurant and delivery agent are
the objects interacting with one another via app.

For software to recognize real time entities as objects it should


know the state and behaviour of objects.

State:

 Name
 Email
 Phone_num
 Address

Behaviour:

 Sel_restaurant()
 Sel_item()
 Sel_address()
Customer  Place_order()
 Cancel_order()
 Make_payment()
State:  Avail_discount()

 Name
 Address
 Ratings
 Item

Behaviour:

 Confirm_order()
 Add_item()
 Del_item()

2 Python fundamentals| Rooman Technologies


Now let us see how to implement these in python considering the
following example

State: Behaviour:

 Brand  Start()
 CC  Shift_gear()
 Colour  Accelerate()

3 Python fundamentals| Rooman Technologies


Output:

You must be wondering why should we pass self as


the argument and is it mandatory to use it?

Certainly using self as argument is mandatory because internally c1


object is passed as argument which contains the different states of
object. So, not using self will throw an error. But replacing self with
any other character will definitely work. The only issue will be not
following the conventions of python.

We know that there exist multiple objects in real life. So let us see
if the above code could have another object in it

4 Python fundamentals| Rooman Technologies


Object:

5 Python fundamentals| Rooman Technologies


Today’s Agenda
 Object orientation contd…
 Creating instance variables

Object orientation contd…


In previous session we got to know multiple objects can be created.
But we had created duplicate objects. So let us now consider an
example where we shall have different objects of the same type.

Footballer

State: Behaviour:

 Name  Shooting()
 Team  Passing()
 Goals  Running()

Let us see how to write the python code for this particular example.

1 Python fundamentals| Rooman Technologies


Output:

2 Python fundamentals| Rooman Technologies


Great!! But we Python is all above reducing lines of code and making
it more efficient. So let us see how more efficient form of the
above code.

Output:

3 Python fundamentals| Rooman Technologies


From the above example we got to know the following things

 For the given class we can create multiple objects. And objects
can be initialised differently.
 There are two different types of functions
1. __new__ : Is a constructor.
2. __init__ : Is a initialiser.

Creating instance variables


There are two ways in which we can create instance variables.

 During object creation


 After object creation

4 Python fundamentals| Rooman Technologies


Output:

There is also another way of creating instance variables after


object creation, by using built-in method setattr(). Similarly we also
have getattr() and hasattr(). Let us see how to use it

5 Python fundamentals| Rooman Technologies


Output:

Another interesting thing to know is all the instance variables are


present in a dictionary. The name of this dictionary is __dict__. Let
us see is this actually true.

6 Python fundamentals| Rooman Technologies


Output:

7 Python fundamentals| Rooman Technologies


Today’s Agenda
▪ Functions as objects
▪ Decorators

Functions as objects
One of the most powerful features of Python is that
everything is an object, including functions. Functions
in Python are first-class objects. Everything a regular
object is capable of doing such as integer,
floating point numbers, complex numbers, list,
set, tuple, dictionaries etc can also be done
using functions.

Let us now understand first-class objects with


the help of code shown below.
CODE:

fun1 1000
1000

fun2
1000

1 Python fundamentals| Rooman Technologies


OUTPUT:

We see in the above output, when we simply print fun1 and fun2, we
get the address of function object as output which means fun1 and
fun2 are the reference variables pointing to the same object.

Can one function be sent as argument to


another function?
Let us now see can functions be passed as arguments in python?

CODE:

ref

OUTPUT:

As we can see from the above output, beta () function is passed as


input to alpha () function which concludes one function can be passed
as input to other function in python.

2 Python fundamentals| Rooman Technologies


Can a function be passed as output from
another function?
Let us now see can functions be passed as output in python?

CODE:

OUTPUT:

3 Python fundamentals| Rooman Technologies


From the above output, we can conclude that not only can functions
be passed as input but also can be returned as output from another
function.

Can one function be present within


another function?
A function can be present within another function in python and such
functions are only called as Inner functions.
An inner function is simply a function that is
defined inside another function. The inner function is able to access
the variables that have been defined within the scope of the outer
function, but it cannot change them.
We can call an inner function in two ways as shown below:

CODE:

Or

4 Python fundamentals| Rooman Technologies


OUTPUT:

After getting to know all the important points about functions as


objects in python, let us now try to code a scenario where we have a
get_product() which calculates the product of all numbers present in
a list but condition is product should not be calculated if 0 is
present in list without modifying get_product().
Now how do we achieve it?? Have a look at the code given below!

CODE:

5 Python fundamentals| Rooman Technologies


OUTPUT:

The above output can also be achieved by using the concept of


decorators in python.

Decorators in python
Decorators in Python allows programmers to
modify the behaviour of function or class.
Decorators allow us to wrap another function in
order to extend the behaviour of wrapped
function, without permanently modifying it.
In Decorators, functions are taken as the
argument into another function and then called
inside the wrapper function.
Let us now understand how can we achieve the above output using
decorators.
CODE:

Decorator

6 Python fundamentals| Rooman Technologies


OUTPUT:

Let’s jump to another example to understand decorators in detail.

CODE:

7 Python fundamentals| Rooman Technologies


He got the
correct
output.
OUTPUT: Did you?

DID YOU KNOW??


Python is one of the official programming languages at Google and
YouTube is one of Google’s products that are powered by Python.

8 Python fundamentals| Rooman Technologies


Today’s Agenda
 Decorators contd…
 Closures

Decorators contd…
Now our expectation is to take an input list and first find the square
of each element and then find the product of it. Let’s see how to do
it

1 Python fundamentals| Rooman Technologies


Output:

We can do the same in a simpler way

Output:

power_of will automatically consider the power to be 2. But what if


we want it to be any other number? Let us see

2 Python fundamentals| Rooman Technologies


Output:

mod_get_product

decorator 4000

2000 2000

fun1

3000

get_product

1000

1000
lst

3 Python fundamentals| Rooman Technologies


Above code can also be written as

Output:

Closures
Though we have seen the inner/outer function there is another
tricky thing to know. Let us see what it is

Output:

4 Python fundamentals| Rooman Technologies


Now we are trying to delete the outer function. Let us see what
happens

Output:

We get the output even after deleting the oyter function because of
the concept called as closures.

When the outer function is deleted and the inner function is still
present, though the variables in outer function got deleted the inner
function will still have the access to those variables, because
somewhere in memory the values are still present.

Let us look at another example to understand correctly

5 Python fundamentals| Rooman Technologies


Output:

Now let us try deleting the outer functions

Output:

6 Python fundamentals| Rooman Technologies


Today’s Agenda
 Types of methods within class
 Instance method
 Static method
 Class method

Types of methods within class


The functions present within the class are called as methods. We
can have 3 types of methods within the class

 Instance method
 Static method
 Class method

So far the methods we have come across are instance methods.

Let us take the example of BMW car and modify it according to the
necessity and explore the different classes.

1 Python fundamentals| Rooman Technologies


Instance methods
This is a very basic and easy method that we use regularly when we
create classes in python. If we want to print an instance variable or
instance method we must create an object of that required class.
If we are using self as a function parameter or in front of a variable,
that is nothing but the calling instance itself.
As we are working with instance variables we use self keyword.
Note: Instance variables are used with instance methods.

Output:

Now let us modify the above code by adding function that can
convert kilometres to miles.

2 Python fundamentals| Rooman Technologies


Output:

Great! Using the class it successfully works. But can we do the same
using the object? Let us see

3 Python fundamentals| Rooman Technologies


Output:

We certainly cannot, because internally it


is taking only one parameter but two were
given. So let us see how to overcome this

Static method
A static method can be called without an object for that class, using
the class name directly. If you want to do something extra with a
class we use static methods.

4 Python fundamentals| Rooman Technologies


Output:

Class method
There are two ways to create class methods in python:
1. Using classmethod(function)
2. Using @classmethod annotation
As we are working with ClassMethod we use the cls keyword. Class
variables are used with class methods.

5 Python fundamentals| Rooman Technologies


Output:

6 Python fundamentals| Rooman Technologies


Today’s Agenda
 Design principals of object
orientation

Design principals of object


orientation
The four major principles of object orientation are:

 Encapsulation
 Polymorphism
 Inheritance
 Abstraction

An object oriented program is based on classes and there exists a


collection of interacting objects, as opposed to the conventional
model, in which a program consists of functions and routines. In
OOP, each object can receive messages, process data, and send
messages to other objects.

1 Python Fundamentals | Rooman Technologies


Let us consider the same example of food delivery that we had
considered earlier and develop it

State:

 Name
 Email
 Phone_num
 Address

Behaviour:

 Sel_restaurant()
 Sel_item()
 Sel_address()
 Place_order()
Customer  Cancel_order()
 Make_payment()
 Avail_discount()

State:

 Name
 Address
 Ratings
 Item

Behaviour:

 Confirm_order()
 Add_item()
 Del_item()

2 Python Fundamentals | Rooman Technologies


State:

 Name
 Ratings
 Phone_num

Behaviour:

 Confirm_pickup()
 Confirm_delivery()
Delivery Agent
 Contact_customer()

State:

 Name
 Price
 Ratings
 Votes

Food Item

Now all these objects should be having a connection between them.


Let us see

3 Python Fundamentals | Rooman Technologies


Customer

 Name : String
 Email : String
 Phone_num : Number
 Address : String

 Sel_restaurant()
 Sel_item()
 Sel_address()
 Place_order()
 Cancel_order()
 Make_payment()
 Avail_discount()

Aggregation Has-A

Restaurant

 Name : String
 Address : String
 Ratings : Float
 Items : List

 Confirm_order()
 Add_item()
 Delete_item()

Aggregation Has-A Has-A Composition

Delivery agent <Enumeration>

 Name : String Food Item


 Ratings : Float
 Phone_num : Number  Name : String
 Price : Float
 Ratings : Float
 Confirm_pickup()
 Votes : Number
 Confirm_delivery()
 Contact_customer()

4 Python Fundamentals | Rooman Technologies


From the above UML we have derived the relation between all the
objects. Now before going further let us see what is aggregation and
composition

Composition and aggregation are specialised form of Association.


Whereas Association is a relationship between two classes without
any rules.

Composition: One class is container and other class is content and if


you delete the container object then all of its contents objects are
also deleted.

Aggregation: Aggregation is a weak form of composition. If you


delete the container object contents objects can live without
container object.

Now what if we want to add another feature and upgrade. It


wouldn’t be efficient way to start from the scratch. Therefore we
have a feature where we can re-use the code and modify. Let us
consider following as the new feature

Platinum Customer

 Name : String
 Email : String
 Phone_num : Number
 Address : String
 Platinum_id : int
 Credits : int

 Sel_restaurant()
 Sel_item()
 Sel_address()
 Place_order()
 Cancel_order()
 Make_payment()
 Avail_discount()
 Free_delivery()
 Exclusive_offers()

5 Python Fundamentals | Rooman Technologies


Let us try to establish a relation between all the features
Platinum Customer Customer

 Name : String  Name : String


 Email : String  Email : String
 Phone_num : Number Inheritance  Phone_num : Number
 Address : String  Address : String
 Platinum_id : int
 Credits : int Is-A  Sel_restaurant()
 Sel_item()
 Sel_restaurant()  Sel_address()
 Sel_item()  Place_order()
 Sel_address()  Cancel_order()
 Place_order()  Make_payment()
 Cancel_order()  Avail_discount()
 Make_payment()
 Avail_discount()
 Free_delivery() Aggregation Has-A
 Exclusive_offers()

Restaurant

 Name : String
 Address : String
 Ratings : Float
 Items : List

 Confirm_order()
 Add_item()
 Delete_item()

Aggregation Has-A Has-A Composition

Delivery agent <Enumeration>

 Name : String Food Item


 Ratings : Float
 Phone_num : Number  Name : String
 Price : Float
 Ratings : Float
 Confirm_pickup()
 Votes : Number
 Confirm_delivery()
 Contact_customer()

6 Python Fundamentals | Rooman Technologies


Now again we want to upgrade a feature where staff members are
benefitted

Platinum Customer Customer

 Name : String  Name : String


 Email : String  Email : String
 Phone_num : Number Inheritance  Phone_num : Number
 Address : String  Address : String
 Platinum_id : int
 Credits : int Is-A  Sel_restaurant()
 Sel_item()
 Sel_restaurant()  Sel_address()
 Sel_item()  Place_order()
 Sel_address()  Cancel_order()
 Place_order()  Make_payment()
 Cancel_order()  Avail_discount()
 Make_payment()  Provide_live_location()
 Avail_discount()
 Free_delivery()
 Exclusive_offers() Inheritance Is-A
 Provide_live_location()
Staff Customer

 Name : String
 Email : String
 Phone_num : Number
 Address : String

 Sel_restaurant()
 Sel_item()
 Sel_address()
 Place_order()
 Cancel_order()
 Make_payment()
 Avail_discount()
 Avail_special_discount()
 Provide_live_location()

Note: Any changes made in parent class reflect in child class as well.

7 Python Fundamentals | Rooman Technologies


Today’s Agenda
 Encapsulation

Encapsulation
To know what is encapsulation and is it needed. Let us consider an
example

Output:

1 Python Fundamentals | Rooman Technologies


Let us now try giving negative number and see if the value modifies

Output:

But balance in ones’ account is personal and should not be easily


accessible by the third person. And more importantly we shouldn’t
be allowed to mishandle the data. Let us see how to resolve this
issue

2 Python Fundamentals | Rooman Technologies


Output:

Encapsulation in Python is the process of wrapping up variables and


methods into a single entity. In programming, a class is an example
that wraps all the variables and methods defined inside it.

Encapsulation acts as a protective layer by ensuring that, access to


wrapped data is not possible by any code defined outside the class in
which the wrapped data are defined. Encapsulation provides security
by hiding the data from the outside world.

But in the above code we can still access amt by calling bal and can
still modify. How to avoid it?

3 Python Fundamentals | Rooman Technologies


Output:

Although the above declaration of variable is just indication of not


using directly, which means any third member can still aces it
directly who isn’t aware of it. Which says that python doesn’t
strictly enforce anything it’s more of a responsibility of the user
and developer. Is there a solution for this? There certainly is let us
see

Output:

We confirmed that bal is stored in dictionary, but still we haven’t


resolved the situation completely

4 Python Fundamentals | Rooman Technologies


Output:

By adding 2 underscore in front of the variable made the difference.


Python internally changed the __bal to _AccountHolder__bal using a
concept called as data mangling.

There is no strict way to stop the access there are only few tricks
which we can work around with.

Now let us see another example of data mangling

5 Python Fundamentals | Rooman Technologies


Output:

We see that new variable is created with name __bal. This is


because mangling is a process which is only applied to instance
variables which are created within the class.

This is how internally new variable got created

The above code will give the same output.

Let us see another example

6 Python Fundamentals | Rooman Technologies


There’s another way to do the same.

Output:

7 Python Fundamentals | Rooman Technologies


Today’s Agenda
 super() in inheritance

super( ) in Inheritance
The super keyword refers to superclass (parent) objects. It is used
to call superclass methods, and to access the superclass constructor.
The most common use of the super keyword is to eliminate the
confusion between super-classes and sub-classes that have methods
with the same name.

Let us look at an example and see how to use


super()

1 Python fundamentals | Rooman Technologies


Output:

In the above example we can reduce the size of __init__() of child


class i.e. PlatinumCustomer() by using super(). Let us see below how
to do it

2 Python fundamentals | Rooman Technologies


Output:

We can also call any other method of parent class using super(). Let
us take another example to know how

3 Python fundamentals | Rooman Technologies


Output:

Next let us see how to use super() in multilevel inheritance

4 Python fundamentals | Rooman Technologies


Output:

Great!! But can we access class A methods as well? Certainly we can

Output:

Now let us go ahead to multiple inheritance

5 Python fundamentals | Rooman Technologies


Output:

What if we want to check whether the object


or variable is an instance of specified class
type or datatype and check if a class is
subclass of another class. How do we do it?

Output:

6 Python fundamentals | Rooman Technologies


Today’s Agenda
 super() in inheritance

super( ) in Inheritance
The super keyword refers to superclass (parent) objects. It is used
to call superclass methods, and to access the superclass constructor.
The most common use of the super keyword is to eliminate the
confusion between super-classes and sub-classes that have methods
with the same name.

Let us look at an example and see how to use


super()

1 Python fundamentals | Rooman Technologies


Output:

In the above example we can reduce the size of __init__() of child


class i.e. PlatinumCustomer() by using super(). Let us see below how
to do it

2 Python fundamentals | Rooman Technologies


Output:

We can also call any other method of parent class using super(). Let
us take another example to know how

3 Python fundamentals | Rooman Technologies


Output:

Next let us see how to use super() in multilevel inheritance

4 Python fundamentals | Rooman Technologies


Output:

Great!! But can we access class A methods as well? Certainly we can

Output:

Now let us go ahead to multiple inheritance

5 Python fundamentals | Rooman Technologies


Output:

What if we want to check whether the object


or variable is an instance of specified class
type or datatype and check if a class is
subclass of another class. How do we do it?

Output:

6 Python fundamentals | Rooman Technologies


Today’s Agenda
 Extending built-in classes

Extending built-in classes


We can extend all of Python's built-in classes. This allows us to add
or modify features of the data types that come with Python. This
may save us from having to build a program from scratch. Let us
take an example and see how to achieve it

1 Python Fundamentals| Rooman Technologies


Output:

We have list of two objects. Let us try to print the instances within
those objects

Output:

It would be a lot easier if we could get the above output by calling a


function as shown below in the comment section.

2 Python Fundamentals| Rooman Technologies


Output:

Let us now see how to extend the features of built-in data types
using class in the below example

3 Python Fundamentals| Rooman Technologies


Output:

All we did is, instead of directly creating a list we created an object


of the ContactList which is a list on which we can activate the
extended features display_all_contacts and search_contacts which
a traditional list did not have.

4 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Polymorphism
 Duck Typing

Polymorphism
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.

Polymorphism establishes 1:many relation. This means certain line of


code giving different output, or performing different task.

Let us look at the below example which is non-polymorphic and then


convert the same into a code following polymorphism

1 Python fundamentals| Rooman Technologies


Output:

2 Python fundamentals| Rooman Technologies


Now let us write the code implementing polymorphism, to achieve
code flexibility and code reusability.

3 Python fundamentals| Rooman Technologies


Let us trace before seeing the output

ref

1000 or 2000 or 3000 // depending on line of execution

wa 1000
1000

use_keyboard()

send_message()

receive_message()

fb 2000
2000

use_keyboard()

send_message()

receive_message()

im 3000
3000

use_keyboard()

send_message()

receive_message()

4 Python fundamentals| Rooman Technologies


Output:

Great! But what if we want to include specialized


methods? Duck typing is the solution. Didn’t
understand? Let us explore

Duck typing
In duck typing, you do not check types at all.
Instead, you check for the presence of a given method or attribute.
Like shown in the below example

5 Python fundamentals| Rooman Technologies


Output:

Great! So now we know how to make code flexible with specialized


methods as well.

6 Python fundamentals| Rooman Technologies


Today’s Agenda
 Magic methods
 Operator overloading

Magic Methods
Dunder or magic methods in Python are the methods having two
prefix and suffix underscores in the method name. Dunder here
means “Double Under (Underscores)”. These are commonly used for
operator overloading. Few examples for magic methods are:
__init__, __add__, __len__, __repr__ etc.

Let us take an example and see how operator overloading is done

1 Python Fundamentals | Rooman Technologies


Output:

In the above example a=a+5 executes in the following manner

Similar to the above operation subtraction, multiplication, division


and power also execute in same manner.

a=a-5  a=a.__sub__(5)

a=a*5  a=a.__mul__(5)

a=a/5  a=a.__div__(5)

a=a**5  a=a.__pow__(5)

So let us cross verify by using one of these magic method in the


above code.

Output:

2 Python Fundamentals | Rooman Technologies


Let us next take example of concatenation and see how it works,
because we use the same + operator for concatenation as well

Output:

Note that here string class is executing not the int class.

If we try to mix both integer and string and then use + operator, you
will definitely get an error as shown below

3 Python Fundamentals | Rooman Technologies


Output:

If we reverse the order then as well we will get the error

Output:

So be careful when using operators and do not mix the different


types of data

4 Python Fundamentals | Rooman Technologies


Operator overloading
Let us take an example to understand what is operator overloading.
In the above example we saw + operator will perform arithmetic
addition on two numbers, merge two lists, or concatenate two
strings. This feature in Python that allows the same operator to
have different meaning according to the context is called operator
overloading.

Addition Concatenation
int + int str + str
int.__add__(int) str.__add__(str)

All the above examples are on built-in methods. Let us see how to
achieve the same with user defined type.

5 Python Fundamentals | Rooman Technologies


Output:

Now let us see if we can get the third point which will be the added
result of these two points.

Output:

Certainly above code will throw error because there is no __add__


method in point class. So let us see how to create a __add__ method
and see if it works

6 Python Fundamentals | Rooman Technologies


Output:

Let us see if we can print p1, p2, p3 using print() and not by the
display().

7 Python Fundamentals | Rooman Technologies


Output:

Instead of printing the values, it is printing the object. This is


because of the absence of certain feature in __str__() because
print() expects the arguments in it to be string type. If not it tries
to convert it into string.

As __str__() is inherited by point class from object class, we can


override it and modify according to our needs as shown below

Output:

8 Python Fundamentals | Rooman Technologies


But what if the point objects are identical as below and you are not
sure if they are same objects or different objects. How to
distinguish? Let us see

Output:

Great so now we know they are two different objects.

9 Python Fundamentals | Rooman Technologies


Today’s Agenda
 Has-A relationship

Has-A relationship
We have seen is-a relationship which can be achieved using
inheritance but there is also has-a relationship which can be
achieved using aggregation and composition.

Composition and aggregation are specialised form of Association.


Where Association is a relationship between two classes without any
rules.

In composition, one of the classes is composed of one or more


instance of other classes. In other words, one class is container and
other class is content and if you delete the container object then all
of its contents objects are also deleted.

Aggregation is a weak form of composition. If you delete the


container object contents objects can live without container object.

1 Python Fundamentals| Rooman Technologies


Let us take an example of restaurant and understand it correctly

Has-a Has-a

Composition Aggregation

 Name : string
 Addr : string
 Rating : float

Food Item
Delivery Agent
 Name : string
 Price : int  Name : string
 Rating : float  Rating : float
 Is_veg : boolean  Ph_no : int

Let us write the code for above


UML

2 Python Fundamentals| Rooman Technologies


Output:

Let us see if we can access food item and delivery agent without the
restaurant

3 Python Fundamentals| Rooman Technologies


Output:

Next let us see if we remove restaurant from the equation can we


still access food and delivery agent

4 Python Fundamentals| Rooman Technologies


Output:

5 Python Fundamentals| Rooman Technologies


We cannot access food without restaurant which makes complete
sense but we should we able to access delivery agent without
restaurant

Output:

6 Python Fundamentals| Rooman Technologies


We see that Food item is outside the restaurant class, which means
by creating an object of food item the instances can still be
accessed. But that is not how things are in reality. Food items are
present only inside restaurant. Let us see if can implement the same
even in the above code.

Output:

Make sure whenever you are trying to access fooditem, first call
restaurant.
7 Python Fundamentals| Rooman Technologies
Today’s Agenda
 Sorting
 Sorting algorithms

Sorting
Sorting is a process of arranging items systematically, be it in
ascending order or descending order. In python we can sort built-in
objects as well as user defined objects.

Let us understand with the basic example first

Output:

By default the elements in the list get sorted in ascending order.


What to do to get it in descending order let us see below

1 Python Fundamentals| Rooman Technologies


Output:

Next let us try with strings

Output:

The string values are sorted in alphabetical order. And just like
numbers we can have the reverse order of strings as well

Output:

2 Python Fundamentals| Rooman Technologies


So far we have sorted homogeneous data, what if
we provide heterogeneous data? Combination of
multiple datatypes. Let us see

Output:

So as we can see heterogeneous sorting cannot happen, because we


cannot measure two different set of data.

Sorting Algorithms
There are different algorithms (step by step procedure) used for
sorting, below are few algorithms mentioned

 Bubble sort
 Mere sort
 Insertion sort
 Quick sort
 Selection sort
 Heap sort
 Radix sort
 Bucket sort
Amongst all let us select selection sort and know about it.

3 Python Fundamentals| Rooman Technologies


Selection sort:

The selection sort algorithm sorts an array by repeatedly finding


the minimum element (considering ascending order) from unsorted
part and putting it at the beginning. The algorithm maintains two
subarrays in a given array.
1)The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element
(considering ascending order) from the unsorted subarray is picked
and moved to the sorted subarray.

0 1 2 3 4 5

lst 10 2 12 16 14 18

1000
After sorting

0 1 2 3 4 5

lst 2 10 12 14 16 18

1000

Boundary condition Condition

i : range(0,len(lst)-1)
j : range(i+1, len(lst))

Let us try to implement the above code:

4 Python Fundamentals| Rooman Technologies


Output:

Next let us see the selection sort for user defined objects. For that
first we have to create the user defined objects and then shall
proceed with sorting

Output:

5 Python Fundamentals| Rooman Technologies


The user defined objects are ready, but can we just sort them by
using any operators we used for built-in objects? Certainly not! So
what to do?

Output:

6 Python Fundamentals| Rooman Technologies


Now that we know how to compare user defined objects, let us see
how to sort them

0 1 2 3

lst 1000 2000 3000 4000

Name: Messi Name: Critiano Name: Neymar Name: Luis

Goals: 650 Goals: 750 Goals: 450 Goals: 300

Assist: 359 Assist: 250 Assist: 125 Assist: 600

f1 f2 f3 f4

After Sorting

0 1 2 3

lst 4000 3000 1000 2000

Name: Luis Name: Neymar Name: Messi Name: Cristiano

Goals: 300 Goals: 450 Goals: 650 Goals: 750

Assist: 600 Assist: 125 Assist: 359 Assist: 250

f4 f3 f1 f2

7 Python Fundamentals| Rooman Technologies


Output:

8 Python Fundamentals| Rooman Technologies


Great! But is this the optimized code? Definitely not

Output:

9 Python Fundamentals| Rooman Technologies


Today’s Agenda
 Abstraction
 Rules of abstract class

Abstraction
Let us understand the abstraction by taking an example of voice
assistant, we have several voice assistants built-in in our mobile
phones like siri in iPhone, google assistant in android phone, alexa in
amazon products.
Voice Assistant

activate_assistant()
perform_task()
use_builtin_apps()
Is-A Is-A

Is-A

Siri Alexa GoogleAssistant

activate_assistant() activate_assistant() activate_assistant()


perform_task() perform_task() perform_task()
use_builtin_apps() use_builtin_apps() use_builtin_apps()

1 Python Fundamentals| Rooman Technologies


Let us implement the code for the above UML

2 Python Fundamentals| Rooman Technologies


Output:

But in the above code we have just implemented inheritance. We


could also implement polymorphism as below

3 Python Fundamentals| Rooman Technologies


Output:

We see in above code, all the inherited or the child classes have
modified the inherited method as required. So can we remove the
parent class methods and still get the output as expected? And if we

4 Python Fundamentals| Rooman Technologies


remove methods from parent class, we can change the names of
methods in derived classes. Let us see if we can get the same output

5 Python Fundamentals| Rooman Technologies


Output:

We are getting error because ref was previously pointing to the


overridden methods, but now those methods have become
specialised methods. So let us undo the changes done and as body is
the only thing that is not being used by any of the derived or
inherited or child class, let us remove the body of parent class
methods.

The methods which contains only the name is called as abstract


methods and a class which contains abstract methods are called as
abstract class.

Voice Assistant Abstract class

activate_assistant()
perform_task() Abstract methods
use_builtin_apps()
Is-A Is-A

Is-A

Siri Alexa GoogleAssistant

activate_assistant() activate_assistant() activate_assistant()


perform_task() perform_task() perform_task()
use_builtin_apps() use_builtin_apps() use_builtin_apps()

6 Python Fundamentals| Rooman Technologies


7 Python Fundamentals| Rooman Technologies
Output:

Abstract methods are used when you are not sure about the body of
method of the derived classes.

Rules of abstract classes


 An abstract class can contain both concrete as well as abstract
methods.

Output:

Certainly we haven’t called any method so we won’t get anything


on output screen. The point is to see if it works or throws
error.

8 Python Fundamentals| Rooman Technologies


 If a class is abstract class, its objects cannot be created.

Output:

This is because, if the behaviour of object is unknown what is


the use of creating such object.
 A child class if inherited from a parent class which is abstract
can only create an object if it overrides all the methods
inherited from parent class.

9 Python Fundamentals| Rooman Technologies


Output:

10 Python Fundamentals| Rooman Technologies


Today’s agenda
 Abstraction contd
 Problems on abstraction

Abstraction contd
Let us take an example of shapes and try to understand when a
method must be abstract, incomplete or a concrete method

Area=πr2 Area=l*b Area=


(h*b)/2

Circle Rectangle Triangle

r : int l : int h : int


area : int b : int b : int
area : int area : int
take_input()
find_area() take_input() take_input()
disp_area() find_area() find_area()
disp_area() disp_area()

1 Python Fundamentals | Rooman Technologies


2 Python Fundamentals | Rooman Technologies
Output:

But we see the above code is not object oriented, and does not
exhibit any features of object orientation like inheritance,
polymorphism and abstraction.

Let us try to code using these features


Shape

area : int

take_input()
find_area()
disp_area()
Is-A Is-A

Is-A

Circle Rectangle Triangle

r : int l : int h : int


area : int b : int b : int
area : int area : int
take_input()
find_area() take_input() take_input()
disp_area() find_area() find_area()
disp_area() disp_area()

3 Python Fundamentals | Rooman Technologies


4 Python Fundamentals | Rooman Technologies
Output:

5 Python Fundamentals | Rooman Technologies


Problems on abstraction
Example 1: Let’s try a larger application like fund transfer before
moving on to our application. So, in fund transfer there are three
types NEFT/IMPS/PTGS.

We can create an abstract class FundTransfer and extend it in the


child classes. Create an abstract method transfer and implement in
all the child classes.

Create an abstract class FundTransfer with following attributes,


accountNumber:

int, balance : float and following methods,

validate(amount) : to check if the accountNumber is 10 digits,


transfer the amount in non-negative and less than balance, and
return true, if not false

transfer (amount) : abstract method with no definition

Create a class NEFTTransfer which extends FundTransfer and


implements transfer method,

transfer(amount) : Check if transfer amount + 5% of transfer


amount is less than balance, then subtract transfer amount and 5%
service charge from balance and return true, if not return false

Create a class IMPSTransfer which extends FundTransfer and


implements transfer method,

transfer(amount) : Check if the transfer amount + 2% of transfer


amount is less than balance, then subtract transfer amount and 2%
service charge from balance and return true, if not return false

6 Python Fundamentals | Rooman Technologies


Create a class RTGSTransfer which extends FundTransfer and
implements Trandfer method,

transfer(amount) : Check if transfer amount is greater than


Rs.10000, then subtract the transfer amount from balance and
return true, if not return false

Add appropriate getters/setters, constructors with super() to


create objects

Note: Print “Account number or transfer amount seems to be wrong”


if validate function returns false.

Print “Transfer could not be made” if transfer function returns


false.

Sample Input/Output:

Enter your account number: 1234567890

Enter the balance of the amount: 10000

Enter the type of transfer to be made:

1. NEFT
2. IMPS
3. RTGS

Enter the amount to be transferred : 2000

Transfer occurred successfully remaining balance is 7900.0

7 Python Fundamentals | Rooman Technologies


FundTransfer

Account_number : int
balance: float

Validate(amount)
transfer(amount)
Is-A Is-A

Is-A

NEFTTransfer IMPSTransfer RTGSTransfer

Account_number : int Account_number : int Account_number : int


balance: float balance: float balance: float

Validate(amount) Validate(amount) Validate(amount)


transfer(amount) transfer(amount) transfer(amount)

8 Python Fundamentals | Rooman Technologies


9 Python Fundamentals | Rooman Technologies
Output:

As RTGS expects minimum of Rs.10000 transfer could not be made.

10 Python Fundamentals | Rooman Technologies


Today’s Agenda
 Exception handling

Exception handling
In computing and computer programming, exception handling is the
process of responding to the occurrence of exceptions – anomalous
or exceptional conditions requiring special processing - during
the execution of a program.

To understand in a better way let us take non-technical example


first

Consider the following sentence:

A apple a day keep a doctor away.

Clearly we can see some grammatical mistakes in the above sentence.


The correct form of sentence is “An apple a day keeps the doctor
away”. This follows all the set of rules which English language
follows. Similar to these grammatical mistakes in programming
language one can commit some syntactical or logical mistakes.

1 Python Fundamentals | Rooman Technologies


In python we have set of tokens (identifiers, operators, delimiters,
keywords). All commands in python are combination of these tokens.

Tokens

Identifiers: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h I j k l m n o p q r s t u
vwxyz0123456789

Operators: + - * / % ** // << >> & | ^ ~ < <= > >= <> != ==

Delimiters: ( ) { } [ ] , : . = ; += -= *= /= //= %= &= |= ^= >>= <<= **=

Keywords: and del for is raise assert elif from lambda return break else global not try class
except if or while continue exec import pass with def finally in print yield

Consider the following statement

for i in range(6):

print(i)

Above statement is correct according to the


rules of python. Let us take another statement

fun(x):

print(x)

The above statement is invalid as it is not following the syntax of a


normal function. The above statement will cause syntax error which
can be fixed by following the rule and adding def keyword before
the fun(x).

But this is not exception. The mistakes occurred due to syntax are
called syntactical errors. But if the mistake is with the logic then it
is called as an exception. These exceptions occur during the
execution of the program and once an exception is encountered

2 Python Fundamentals | Rooman Technologies


program gets abruptly terminated. To make sure it doesn’t get
abruptly terminated we have to handle these exceptions.

For eg:

Output:

Above code is perfectly fine with the syntax. But logic is not
correct. Hence we get a ZeroDivionError which is one of the
exceptions.
Errors

Syntax Errors Exceptions

3 Python Fundamentals | Rooman Technologies


Syntax Errors Exceptions
 Syntax mistakes  Logical mistakes
 Is easily identified by the  Is not identified by the
interpreter interpreter
 Occurs before runtime  Occurs during runtime

Let us start by considering an example of banking

Output:

The above code is working fine, as no logical errors occur during


execution. But imagine if the input instead of giving in number if it
was entered in string. What would happen? Let us see

4 Python Fundamentals | Rooman Technologies


It has definitely abruptly terminated and the lines below have not
executed. More importantly the connection is not been closed. This
may result in mischievous problem.

Let us see how can we handle these exceptions and can achieve
complete execution of code

 Look for the statement which might arise in logical error.


Especially if the input is taken from the users.
 Put those set of instructions with a special block namely “try”
and “except” as shown below

Output:

Even though we did not get the expected output, the code executed
completely and the connection was closed. Along with it the error
message made sense as to why we did not get the expected output.

5 Python Fundamentals | Rooman Technologies


Note: except block executes only when exception occurs in the try
block and an exception object is generated. As shown in below case

There is another block which can be added namely “else” block,


under which those statements have to be present which must
execute if no exceptions occur in “try” block. As shown below

Output:

6 Python Fundamentals | Rooman Technologies


Today’s agenda
 Exception handling contd

Exception handling contd


Let us take another example

1 Python Fundamentals| Romman Technologies


Output:

This is the ideal case. Let us try with other inputs

In the above case we have given the key which is not present in out
dictionary. Therefore keyerror exception object is generated and it
checks for except block and completes execution. But the message
is not very clear. Let us see another case

2 Python Fundamentals| Romman Technologies


In the above case we don’t have 5th index in list. Therefore while
performing division indexerror exception object is generated and it
checks for the except block and completes the execution. But here
as well we get the same message and it doesn’t convey the clear
message. Let us check for another case

Here we are trying to divide 3rd index by 2nd. 2nd index is 0 which will
result in zerodivision error exception which will check for except
block and return the message.

But as seen in above cases all exceptions generated the same


message which is not conveying the issue properly and hence we need
multiple except block for respective exceptions. As shown below

3 Python Fundamentals| Romman Technologies


Let us try giving the same previous inputs and check the output now

Great! Now we know the entered key does not exist. And can correct
it by giving proper key. And note that once a particular except block
is executed other except blocks do not execute.

Now we know the issue is with the index number. We can now give
appropriate input.

And now the issue is with Zero division.

4 Python Fundamentals| Romman Technologies


But the above except block will catch only specific exception
objects. What if an exception generated cannot be handled by any
of the above except blocks? Let us check

Certainly abrupt termination occurs. To avoid this it is a good habit


to add a generic except block which accept all the possible exception
objects as shown below

5 Python Fundamentals| Romman Technologies


Great! Now we know how to tackle all problems. But now what if you
want to place the generic except bock on top of all except blocks;

Output:

6 Python Fundamentals| Romman Technologies


Well that will give you an error, because when an exception object is
generated it checks for except blocks sequentially therefore once
the generic except block catches the exception, other specific
handlers will never get chance to execute, therefore generic
handlers are suppose be at the end

Next let us try to access the exception object and print its default
message

Let us give the same inputs and check the message.

It just displays the key when keyerror is encountered.

7 Python Fundamentals| Romman Technologies


Okay this is an appropriate message. Great!

Appropriate message here as well

So we are getting appropriate messages. So it is up to the user


which one they want to go with.

8 Python Fundamentals| Romman Technologies


Today’s Agenda
 Exception handling contd

Exception handling contd


Let us see how exception handling mechanism works when multiple
method calls are involved through the following example

1 Python fundamental| Rooman Technologies


Output:

Stack

ZeroDivisionError fun2()
num 100
Traceback

den 0

res 100/0
ZeroDivisionError

fun1()

ZeroDivisionError

main()

Abrupt termination

2 Python fundamental| Rooman Technologies


If except block is not in the method where exception is generated
then it traces back to the method who called for it and checks in
that method. If anywhere it is not present then the program is
abruptly terminated.

Let us try to handle this exception

Output:

3 Python fundamental| Rooman Technologies


Stack

ZeroDivisionError fun2()
num 100

den 0

Execution completes res 100/0

fun1()

main()

Let us see what happens when the except block is in fun1()

4 Python fundamental| Rooman Technologies


Output:

We can see that exception is been handled, but fun2() did not finish
it’s execution as the control came to fun1() along with exception
object.

Let us also try placing the except block in main()

5 Python fundamental| Rooman Technologies


Output:

As we see exception is handled but fun1() and fun2() did not finish
their execution.

6 Python fundamental| Rooman Technologies


Today’s agenda
 Exception handling keywords

Exception handling keywords


During handling the exceptions, we came across few keywords such
as try, except, else. But there are few more keywords you should be
aware of like raise and finally.

Try: The try block lets you test a block of code for errors.

Except: The except block lets you handle the error.

Else: The else block is used to define the code to be executed if no


errors were raised.

Let us see the other two keyword’s functionality with the example
below

Raise: As a python developer you can choose to throw an exception


if the condition occurs. To throw (or raise) an exception, use the
raise keyword. As shown below

1 Python Fundamentals| Rooman Technologies


Output:

In the above example we are trying to just raise a value error


exception.

Let us see if it works fine with 10 digit input.

We can see the code works perfectly well with 10 digit input.

Let us take another example where we are trying to raise


NameError exception

2 Python Fundamentals| Rooman Technologies


Output:

As the input given was pasta, and none of the condition is true else
block is executed where we are trying to generate NameError
exception.

And it works completely fine with expected food items.

Let us next explore the finally keyword with an example

Finally: The finally block if specified will be executed regardless if


the try block raises an error or not.
3 Python Fundamentals| Rooman Technologies
Output:

In the above output we can see the code is working fine. Let us give
another incorrect input and check the working flow

4 Python Fundamentals| Rooman Technologies


We can notice the exception generated and handled in fun() but
main() is unaware of the exception generated. Let us see below how
to resolve this

Output:

In above output we can see main() has received the exception. But
fun() has not completed its execution. Let’s resolve this

5 Python Fundamentals| Rooman Technologies


Output:

Now all the function are executing and are completing the execution
process perfectly as expected.

At last let us consider all the blocks and see the flow of program.

6 Python Fundamentals| Rooman Technologies


Output:

As the given input is valid, except block will not execute and as no
errors/exception were encountered else block will execute and then
at last irrespective of the exception generated finally block will
execute.

As 0 is the input, ZeroDivisionError exception object will be


generated and except block is executed and then at the last finally
block gets executed.

7 Python Fundamentals| Rooman Technologies


Today’s agenda
 Valid combinations
 Exception hierarchy
 Custom Exceptions

Valid Combinations
We have seen several blocks used in exception handling. Let us see
what are these valid combinations of blocks in below segment

try: try: try: try: try:

except: except: except: except: finally:

else: else: finally:

finally:

1 Python fundamentals| Rooman Technologies


We can also have these nested in one another

try: try: try: try:

try:

except:

except: try: except: except:

else: except:

else: finally:

finally: else: try: try:

except: finally: except: except:

else: else:

finally: finally:

Exception Hierarchy
The Python exception class hierarchy consists of a few dozen
different exceptions spread across a handful of important base
class types. In below chart let us see hierarchy in detail

2 Python fundamentals| Rooman Technologies


BaseException

Exception SystemExit GeneratorExit KeyboardInterrupt

Attribute Arithmetic EOF Name Lookup OS Type Value


Error Error Error Error Error Error Error Error

ZeroDivision
Index FileNotFound
Error
Error Error

FloatingPoint
Error Key Interrupted
Error Error

OverFlow
Error Permission
Error

Timeout
Error

Custom Exceptions
Let us previous example

3 Python fundamentals| Rooman Technologies


Output:

We can see we have got the value error. But it is not conveying
proper message. The user might not understand why value error is
generated. So to resolve this issue, in python users can create
custom exceptions. Let us see how

Output:

4 Python fundamentals| Rooman Technologies


Now we can see exception generated clearly conveys the message.
Let us take another example and get more clarity

Output:

Given pasta as the input we got NameError. But user may not know
why is error generated, therefore lets customise the exception

5 Python fundamentals| Rooman Technologies


Output:

Now we can see the proper message and resolve it by giving try and
except blocks

Output:

6 Python fundamentals| Rooman Technologies


Now let us take an example of creating an account. Which will check
if the username is unique and password satisfying the conditions

7 Python fundamentals| Rooman Technologies


Output:

Let us give existing username and check the output

8 Python fundamentals| Rooman Technologies


Today’s Agenda
 Loggers
 Levels of logging
 Examples

Loggers
In simple words logger is a piece of code which the user will be
attaching in the program. This logger will capture some information
from your program and store it in a log file.

What is the information it is going to capture? Why should it be


stored in a file? What is the advantage of doing this? Is what we
shall see one by one. Let’s start with one example that takes list of
integers from user, the program will call a function which will take
only even elements present in the list add them and return the sum.

1 Python Fundamentals| Rooman Technologies


Output:

There’s nothing new in the above code, but let’s trace it once

2 Python Fundamentals| Rooman Technologies


Output:

We can see the above code has too much of information which is not
important for the user or the client. Only if the programmer know
the code and it’s tracing it’s enough. And using print statements
everywhere is not a good habit of experienced programmer. To
overcome this we have loggers where we can store the tracing of
program and refer it whenever needed. Let us see how to achieve it

 Create a logger – let’s start with basic one i.e. root logger.
 Connect the logger to a file (log file).
 Tell what information to be collected and stored in log file.

3 Python Fundamentals| Rooman Technologies


Output:

Now we can see no print statements is visible on


output screen. Wondering how to access that
information? Let us see

The information is stored in a certain order i.e.


<level> : <logger> : <message>

This information will be present in your hard disk


where the program is saved.

4 Python Fundamentals| Rooman Technologies


Levels of logging
We have several levels in logging which will define what data is being
stored in the log file.

Debug: It is used when we want to store debugging related


information in log file.

Info: It is used for tracing of program.

Warning: It is used to store warning related information.

Error: It is used whenever exception related information is to be


stored.

Critical: It is used to capture information which results in critical


failure of application.

Let us start exploring with examples

5 Python Fundamentals| Rooman Technologies


Example for debugging:

Output:

Above is the normal code. Let us make changes and add logging
features to it.

6 Python Fundamentals| Rooman Technologies


Output:

Definitely all the results will be stored in log file. As shown below

7 Python Fundamentals| Rooman Technologies


Example for Warning:

Output:

Let us see how to log the warning message into the log file

8 Python Fundamentals| Rooman Technologies


Output:

Let us see if the log file has got updated log message

Certainly log file has got updated as expected.


9 Python Fundamentals| Rooman Technologies
Now let us see next example with error level

Output:

Let us modify according with the concept of loggers

10 Python Fundamentals| Rooman Technologies


Output:

We can see that no error is displayed neither is the respective


message. Let us check the log file to get the respective message.

Great!! We can see the message now, but is it conveying entire


message? No. Let us see how to get the trace back of the exception
occurred

11 Python Fundamentals| Rooman Technologies


Output:

Let us check the log file and see what is the message we’ll get after
including exception info argument

Great! We have received the trace back of


the exception generated. But every single
time the log message gets appended
making it hard to know which message is
appropriate one. Let us see how to change
this, and get only the log message of that
particular file executing.

12 Python Fundamentals| Rooman Technologies


Output:

Output will be same as previous ones. Let us directly take a look at


log file

Awesome! We got it as expected. Here by default the filemode will


be append(a), but we have changed it to write mode(w) and executed.

13 Python Fundamentals| Rooman Technologies

You might also like